From a408139bb0166f6e0a5d9fd17fc934da960c354e Mon Sep 17 00:00:00 2001
From: Changkun Ou
Date: Mon, 14 Sep 2020 10:24:59 +0200
Subject: testing: fix panicking tests hang if Cleanup calls FailNow
Previously, it was impossible to call FailNow in a Cleanup.
Because it can terminate a panicking goroutine and cause its
parent hangs on t.signal channel. This CL sends the signal
in a deferred call to prevent the hang.
Fixes #41355
Change-Id: I4552d3a7ea763ef86817bf9b50c0e37fb34bf20f
Reviewed-on: https://go-review.googlesource.com/c/go/+/254637
Reviewed-by: Ian Lance Taylor
Reviewed-by: Emmanuel Odeke
Run-TryBot: Ian Lance Taylor
TryBot-Result: Go Bot
Trust: Emmanuel Odeke
---
src/testing/testing.go | 12 +++++++++++-
1 file changed, 11 insertions(+), 1 deletion(-)
(limited to 'src/testing')
diff --git a/src/testing/testing.go b/src/testing/testing.go
index 66f296234a..d86354093a 100644
--- a/src/testing/testing.go
+++ b/src/testing/testing.go
@@ -1075,6 +1075,7 @@ func tRunner(t *T, fn func(t *T)) {
// If the test panicked, print any test output before dying.
err := recover()
signal := true
+
if !t.finished && err == nil {
err = errNilPanicOrGoexit
for p := t.parent; p != nil; p = p.parent {
@@ -1086,6 +1087,15 @@ func tRunner(t *T, fn func(t *T)) {
}
}
}
+ // Use a deferred call to ensure that we report that the test is
+ // complete even if a cleanup function calls t.FailNow. See issue 41355.
+ didPanic := false
+ defer func() {
+ t.signal <- signal
+ if err != nil && !didPanic {
+ panic(err)
+ }
+ }()
doPanic := func(err interface{}) {
t.Fail()
@@ -1103,6 +1113,7 @@ func tRunner(t *T, fn func(t *T)) {
fmt.Fprintf(root.parent.w, "cleanup panicked with %v", r)
}
}
+ didPanic = true
panic(err)
}
if err != nil {
@@ -1144,7 +1155,6 @@ func tRunner(t *T, fn func(t *T)) {
if t.parent != nil && atomic.LoadInt32(&t.hasSub) == 0 {
t.setRan()
}
- t.signal <- signal
}()
defer func() {
if len(t.sub) == 0 {
--
cgit v1.3
From 4cba6c703f68a7c1718e589feaeb2530d7812fbf Mon Sep 17 00:00:00 2001
From: Changkun Ou
Date: Sat, 19 Sep 2020 23:32:12 +0200
Subject: testing: send t.signal only if there is no panic
If a signal is sent to t.signal before the panic is triggered,
a panicking test may end up with "warning: no tests to run" because
the tRunner that invokes the test in t.Run calls runtime.Goexit on
panic, which causes the panicking test not be recorded in runTests.
Send the signal if and only if there is no panic.
Fixes #41479
Change-Id: I812f1303bfe02c443a1902732e68d21620d6672e
Reviewed-on: https://go-review.googlesource.com/c/go/+/256098
Run-TryBot: Emmanuel Odeke
TryBot-Result: Go Bot
Reviewed-by: Ian Lance Taylor
Reviewed-by: Emmanuel Odeke
Trust: Emmanuel Odeke
Trust: Bryan C. Mills
---
src/cmd/go/testdata/script/test_cleanup_failnow.txt | 14 ++++++++++++++
src/testing/testing.go | 10 ++++++++--
2 files changed, 22 insertions(+), 2 deletions(-)
(limited to 'src/testing')
diff --git a/src/cmd/go/testdata/script/test_cleanup_failnow.txt b/src/cmd/go/testdata/script/test_cleanup_failnow.txt
index 5ad4185fc1..0737a93db2 100644
--- a/src/cmd/go/testdata/script/test_cleanup_failnow.txt
+++ b/src/cmd/go/testdata/script/test_cleanup_failnow.txt
@@ -1,11 +1,25 @@
# For issue 41355
[short] skip
+# This test could fail if the testing package does not wait until
+# a panicking test does the panic. Turn off multithreading, GC, and
+# async preemption to increase the probability of such a failure.
+env GOMAXPROCS=1
+env GOGC=off
+env GODEBUG=asyncpreempt=off
+
+# If the test exits with 'no tests to run', it means the testing package
+# implementation is incorrect and does not wait until a test panic.
+# If the test exits with '(?s)panic: die.*panic: die', it means
+# the testing package did an extra panic for a panicking test.
+
! go test -v cleanup_failnow/panic_nocleanup_test.go
+! stdout 'no tests to run'
stdout '(?s)panic: die \[recovered\].*panic: die'
! stdout '(?s)panic: die \[recovered\].*panic: die.*panic: die'
! go test -v cleanup_failnow/panic_withcleanup_test.go
+! stdout 'no tests to run'
stdout '(?s)panic: die \[recovered\].*panic: die'
! stdout '(?s)panic: die \[recovered\].*panic: die.*panic: die'
diff --git a/src/testing/testing.go b/src/testing/testing.go
index d86354093a..a44c0a0749 100644
--- a/src/testing/testing.go
+++ b/src/testing/testing.go
@@ -1091,10 +1091,16 @@ func tRunner(t *T, fn func(t *T)) {
// complete even if a cleanup function calls t.FailNow. See issue 41355.
didPanic := false
defer func() {
- t.signal <- signal
- if err != nil && !didPanic {
+ if didPanic {
+ return
+ }
+ if err != nil {
panic(err)
}
+ // Only report that the test is complete if it doesn't panic,
+ // as otherwise the test binary can exit before the panic is
+ // reported to the user. See issue 41479.
+ t.signal <- signal
}()
doPanic := func(err interface{}) {
--
cgit v1.3
From c4971a14a7cac78849f4d0908e7140263129bdf7 Mon Sep 17 00:00:00 2001
From: Emmanuel T Odeke
Date: Thu, 24 Sep 2020 15:33:45 -0700
Subject: testing: add benchmark for TB.Helper
Adds a benchmark for TB.Helper, to use as a judge of future
improvements like CL 231717.
Change-Id: I17c40d482fc12caa3eb2c1cda39fd8c42356b422
Reviewed-on: https://go-review.googlesource.com/c/go/+/257317
Run-TryBot: Emmanuel Odeke
TryBot-Result: Go Bot
Reviewed-by: Tobias Klauser
Trust: Tobias Klauser
Trust: Emmanuel Odeke
---
src/testing/helper_test.go | 31 +++++++++++++++++++++++++++++++
1 file changed, 31 insertions(+)
(limited to 'src/testing')
diff --git a/src/testing/helper_test.go b/src/testing/helper_test.go
index 7ce58c67fb..8858196cf0 100644
--- a/src/testing/helper_test.go
+++ b/src/testing/helper_test.go
@@ -70,3 +70,34 @@ func TestTBHelperParallel(t *T) {
t.Errorf("got output line %q; want %q", got, want)
}
}
+
+type noopWriter int
+
+func (nw *noopWriter) Write(b []byte) (int, error) { return len(b), nil }
+
+func BenchmarkTBHelper(b *B) {
+ w := noopWriter(0)
+ ctx := newTestContext(1, newMatcher(regexp.MatchString, "", ""))
+ t1 := &T{
+ common: common{
+ signal: make(chan bool),
+ w: &w,
+ },
+ context: ctx,
+ }
+ f1 := func() {
+ t1.Helper()
+ }
+ f2 := func() {
+ t1.Helper()
+ }
+ b.ResetTimer()
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ if i&1 == 0 {
+ f1()
+ } else {
+ f2()
+ }
+ }
+}
--
cgit v1.3
From 9ad090c5fea60c9925b7eb30155ce01961c3537f Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Sat, 18 Jul 2020 22:26:00 -0400
Subject: testing/iotest: add TestReader to test readers
There are many reader behaviors that are subtle and
worth testing, and it's nice to have one complete tester
instead of many incomplete ones.
For #41190, which will use this as part of a larger
file system implementation tester.
Change-Id: Ib4cc7fae94b0d9b45dfacadc52baa77ad3761322
Reviewed-on: https://go-review.googlesource.com/c/go/+/243909
Trust: Russ Cox
Run-TryBot: Russ Cox
TryBot-Result: Go Bot
Reviewed-by: Rob Pike
Reviewed-by: Emmanuel Odeke
---
src/testing/iotest/reader.go | 175 +++++++++++++++++++++++++++++++++++++-
src/testing/iotest/reader_test.go | 10 +++
2 files changed, 181 insertions(+), 4 deletions(-)
(limited to 'src/testing')
diff --git a/src/testing/iotest/reader.go b/src/testing/iotest/reader.go
index bc2f72a911..33b782dcb6 100644
--- a/src/testing/iotest/reader.go
+++ b/src/testing/iotest/reader.go
@@ -6,8 +6,11 @@
package iotest
import (
+ "bytes"
"errors"
+ "fmt"
"io"
+ "io/ioutil"
)
// OneByteReader returns a Reader that implements
@@ -90,13 +93,177 @@ func (r *timeoutReader) Read(p []byte) (int, error) {
// ErrReader returns an io.Reader that returns 0, err from all Read calls.
func ErrReader(err error) io.Reader {
- return &alwaysErrReader{err: err}
+ return &errReader{err: err}
}
-type alwaysErrReader struct {
+type errReader struct {
err error
}
-func (aer *alwaysErrReader) Read(p []byte) (int, error) {
- return 0, aer.err
+func (r *errReader) Read(p []byte) (int, error) {
+ return 0, r.err
+}
+
+type smallByteReader struct {
+ r io.Reader
+ off int
+ n int
+}
+
+func (r *smallByteReader) Read(p []byte) (int, error) {
+ if len(p) == 0 {
+ return 0, nil
+ }
+ r.n = r.n%3 + 1
+ n := r.n
+ if n > len(p) {
+ n = len(p)
+ }
+ n, err := r.r.Read(p[0:n])
+ if err != nil && err != io.EOF {
+ err = fmt.Errorf("Read(%d bytes at offset %d): %v", n, r.off, err)
+ }
+ r.off += n
+ return n, err
+}
+
+// TestReader tests that reading from r returns the expected file content.
+// It does reads of different sizes, until EOF.
+// If r implements io.ReaderAt or io.Seeker, TestReader also checks
+// that those operations behave as they should.
+//
+// If TestReader finds any misbehaviors, it returns an error reporting them.
+// The error text may span multiple lines.
+func TestReader(r io.Reader, content []byte) error {
+ if len(content) > 0 {
+ n, err := r.Read(nil)
+ if n != 0 || err != nil {
+ return fmt.Errorf("Read(0) = %d, %v, want 0, nil", n, err)
+ }
+ }
+
+ data, err := ioutil.ReadAll(&smallByteReader{r: r})
+ if err != nil {
+ return err
+ }
+ if !bytes.Equal(data, content) {
+ return fmt.Errorf("ReadAll(small amounts) = %q\n\twant %q", data, content)
+ }
+ n, err := r.Read(make([]byte, 10))
+ if n != 0 || err != io.EOF {
+ return fmt.Errorf("Read(10) at EOF = %v, %v, want 0, EOF", n, err)
+ }
+
+ if r, ok := r.(io.ReadSeeker); ok {
+ // Seek(0, 1) should report the current file position (EOF).
+ if off, err := r.Seek(0, 1); off != int64(len(content)) || err != nil {
+ return fmt.Errorf("Seek(0, 1) from EOF = %d, %v, want %d, nil", off, err, len(content))
+ }
+
+ // Seek backward partway through file, in two steps.
+ // If middle == 0, len(content) == 0, can't use the -1 and +1 seeks.
+ middle := len(content) - len(content)/3
+ if middle > 0 {
+ if off, err := r.Seek(-1, 1); off != int64(len(content)-1) || err != nil {
+ return fmt.Errorf("Seek(-1, 1) from EOF = %d, %v, want %d, nil", -off, err, len(content)-1)
+ }
+ if off, err := r.Seek(int64(-len(content)/3), 1); off != int64(middle-1) || err != nil {
+ return fmt.Errorf("Seek(%d, 1) from %d = %d, %v, want %d, nil", -len(content)/3, len(content)-1, off, err, middle-1)
+ }
+ if off, err := r.Seek(+1, 1); off != int64(middle) || err != nil {
+ return fmt.Errorf("Seek(+1, 1) from %d = %d, %v, want %d, nil", middle-1, off, err, middle)
+ }
+ }
+
+ // Seek(0, 1) should report the current file position (middle).
+ if off, err := r.Seek(0, 1); off != int64(middle) || err != nil {
+ return fmt.Errorf("Seek(0, 1) from %d = %d, %v, want %d, nil", middle, off, err, middle)
+ }
+
+ // Reading forward should return the last part of the file.
+ data, err := ioutil.ReadAll(&smallByteReader{r: r})
+ if err != nil {
+ return fmt.Errorf("ReadAll from offset %d: %v", middle, err)
+ }
+ if !bytes.Equal(data, content[middle:]) {
+ return fmt.Errorf("ReadAll from offset %d = %q\n\twant %q", middle, data, content[middle:])
+ }
+
+ // Seek relative to end of file, but start elsewhere.
+ if off, err := r.Seek(int64(middle/2), 0); off != int64(middle/2) || err != nil {
+ return fmt.Errorf("Seek(%d, 0) from EOF = %d, %v, want %d, nil", middle/2, off, err, middle/2)
+ }
+ if off, err := r.Seek(int64(-len(content)/3), 2); off != int64(middle) || err != nil {
+ return fmt.Errorf("Seek(%d, 2) from %d = %d, %v, want %d, nil", -len(content)/3, middle/2, off, err, middle)
+ }
+
+ // Reading forward should return the last part of the file (again).
+ data, err = ioutil.ReadAll(&smallByteReader{r: r})
+ if err != nil {
+ return fmt.Errorf("ReadAll from offset %d: %v", middle, err)
+ }
+ if !bytes.Equal(data, content[middle:]) {
+ return fmt.Errorf("ReadAll from offset %d = %q\n\twant %q", middle, data, content[middle:])
+ }
+
+ // Absolute seek & read forward.
+ if off, err := r.Seek(int64(middle/2), 0); off != int64(middle/2) || err != nil {
+ return fmt.Errorf("Seek(%d, 0) from EOF = %d, %v, want %d, nil", middle/2, off, err, middle/2)
+ }
+ data, err = ioutil.ReadAll(r)
+ if err != nil {
+ return fmt.Errorf("ReadAll from offset %d: %v", middle/2, err)
+ }
+ if !bytes.Equal(data, content[middle/2:]) {
+ return fmt.Errorf("ReadAll from offset %d = %q\n\twant %q", middle/2, data, content[middle/2:])
+ }
+ }
+
+ if r, ok := r.(io.ReaderAt); ok {
+ data := make([]byte, len(content), len(content)+1)
+ for i := range data {
+ data[i] = 0xfe
+ }
+ n, err := r.ReadAt(data, 0)
+ if n != len(data) || err != nil && err != io.EOF {
+ return fmt.Errorf("ReadAt(%d, 0) = %v, %v, want %d, nil or EOF", len(data), n, err, len(data))
+ }
+ if !bytes.Equal(data, content) {
+ return fmt.Errorf("ReadAt(%d, 0) = %q\n\twant %q", len(data), data, content)
+ }
+
+ n, err = r.ReadAt(data[:1], int64(len(data)))
+ if n != 0 || err != io.EOF {
+ return fmt.Errorf("ReadAt(1, %d) = %v, %v, want 0, EOF", len(data), n, err)
+ }
+
+ for i := range data {
+ data[i] = 0xfe
+ }
+ n, err = r.ReadAt(data[:cap(data)], 0)
+ if n != len(data) || err != io.EOF {
+ return fmt.Errorf("ReadAt(%d, 0) = %v, %v, want %d, EOF", cap(data), n, err, len(data))
+ }
+ if !bytes.Equal(data, content) {
+ return fmt.Errorf("ReadAt(%d, 0) = %q\n\twant %q", len(data), data, content)
+ }
+
+ for i := range data {
+ data[i] = 0xfe
+ }
+ for i := range data {
+ n, err = r.ReadAt(data[i:i+1], int64(i))
+ if n != 1 || err != nil && (i != len(data)-1 || err != io.EOF) {
+ want := "nil"
+ if i == len(data)-1 {
+ want = "nil or EOF"
+ }
+ return fmt.Errorf("ReadAt(1, %d) = %v, %v, want 1, %s", i, n, err, want)
+ }
+ if data[i] != content[i] {
+ return fmt.Errorf("ReadAt(1, %d) = %q want %q", i, data[i:i+1], content[i:i+1])
+ }
+ }
+ }
+ return nil
}
diff --git a/src/testing/iotest/reader_test.go b/src/testing/iotest/reader_test.go
index 6004e841e5..f149e74c74 100644
--- a/src/testing/iotest/reader_test.go
+++ b/src/testing/iotest/reader_test.go
@@ -8,6 +8,7 @@ import (
"bytes"
"errors"
"io"
+ "strings"
"testing"
)
@@ -249,3 +250,12 @@ func TestErrReader(t *testing.T) {
})
}
}
+
+func TestStringsReader(t *testing.T) {
+ const msg = "Now is the time for all good gophers."
+
+ r := strings.NewReader(msg)
+ if err := TestReader(r, []byte(msg)); err != nil {
+ t.Fatal(err)
+ }
+}
--
cgit v1.3
From 90c924ff88a8b5ab65538ccc16d160922b1b4003 Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Mon, 6 Jul 2020 10:58:05 -0400
Subject: testing/fstest: new package for testing file system code
This change adds basic test helpers for file system code.
The type MapFS is a simple map-based file system for use when
exercising general file system code.
The func TestFS tests a file system implementation.
For #41190.
Change-Id: I5a2036f57e733915ad508651ad7317749794423c
Reviewed-on: https://go-review.googlesource.com/c/go/+/243910
Trust: Russ Cox
Reviewed-by: Rob Pike
---
src/go/build/deps_test.go | 3 +-
src/testing/fstest/mapfs.go | 204 ++++++++++++++++++++++
src/testing/fstest/mapfs_test.go | 19 ++
src/testing/fstest/testfs.go | 364 +++++++++++++++++++++++++++++++++++++++
4 files changed, 589 insertions(+), 1 deletion(-)
create mode 100644 src/testing/fstest/mapfs.go
create mode 100644 src/testing/fstest/mapfs_test.go
create mode 100644 src/testing/fstest/testfs.go
(limited to 'src/testing')
diff --git a/src/go/build/deps_test.go b/src/go/build/deps_test.go
index 9e72c8f234..4867a5031a 100644
--- a/src/go/build/deps_test.go
+++ b/src/go/build/deps_test.go
@@ -468,7 +468,8 @@ var depsRules = `
# Test-only
log
- < testing/iotest;
+ < testing/iotest
+ < testing/fstest;
FMT, flag, math/rand
< testing/quick;
diff --git a/src/testing/fstest/mapfs.go b/src/testing/fstest/mapfs.go
new file mode 100644
index 0000000000..84a943f409
--- /dev/null
+++ b/src/testing/fstest/mapfs.go
@@ -0,0 +1,204 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fstest
+
+import (
+ "io"
+ "io/fs"
+ "path"
+ "sort"
+ "strings"
+ "time"
+)
+
+// A MapFS is a simple in-memory file system for use in tests,
+// represented as a map from path names (arguments to Open)
+// to information about the files or directories they represent.
+//
+// The map need not include parent directories for files contained
+// in the map; those will be synthesized if needed.
+// But a directory can still be included by setting the MapFile.Mode's ModeDir bit;
+// this may be necessary for detailed control over the directory's FileInfo
+// or to create an empty directory.
+//
+// File system operations read directly from the map,
+// so that the file system can be changed by editing the map as needed.
+// An implication is that file system operations must not run concurrently
+// with changes to the map, which would be a race.
+// Another implication is that opening or reading a directory requires
+// iterating over the entire map, so a MapFS should typically be used with not more
+// than a few hundred entries or directory reads.
+type MapFS map[string]*MapFile
+
+// A MapFile describes a single file in a MapFS.
+type MapFile struct {
+ Data []byte // file content
+ Mode fs.FileMode // FileInfo.Mode
+ ModTime time.Time // FileInfo.ModTime
+ Sys interface{} // FileInfo.Sys
+}
+
+var _ fs.FS = MapFS(nil)
+var _ fs.File = (*openMapFile)(nil)
+
+// Open opens the named file.
+func (fsys MapFS) Open(name string) (fs.File, error) {
+ if !fs.ValidPath(name) {
+ return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
+ }
+ file := fsys[name]
+ if file != nil && file.Mode&fs.ModeDir == 0 {
+ // Ordinary file
+ return &openMapFile{name, mapFileInfo{path.Base(name), file}, 0}, nil
+ }
+
+ // Directory, possibly synthesized.
+ // Note that file can be nil here: the map need not contain explicit parent directories for all its files.
+ // But file can also be non-nil, in case the user wants to set metadata for the directory explicitly.
+ // Either way, we need to construct the list of children of this directory.
+ var list []mapFileInfo
+ var elem string
+ var need = make(map[string]bool)
+ if name == "." {
+ elem = "."
+ for fname, f := range fsys {
+ i := strings.Index(fname, "/")
+ if i < 0 {
+ list = append(list, mapFileInfo{fname, f})
+ } else {
+ need[fname[:i]] = true
+ }
+ }
+ } else {
+ elem = name[strings.LastIndex(name, "/")+1:]
+ prefix := name + "/"
+ for fname, f := range fsys {
+ if strings.HasPrefix(fname, prefix) {
+ felem := fname[len(prefix):]
+ i := strings.Index(felem, "/")
+ if i < 0 {
+ list = append(list, mapFileInfo{felem, f})
+ } else {
+ need[fname[len(prefix):len(prefix)+i]] = true
+ }
+ }
+ }
+ // If the directory name is not in the map,
+ // and there are no children of the name in the map,
+ // then the directory is treated as not existing.
+ if file == nil && list == nil && len(need) == 0 {
+ return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
+ }
+ }
+ for _, fi := range list {
+ delete(need, fi.name)
+ }
+ for name := range need {
+ list = append(list, mapFileInfo{name, &MapFile{Mode: fs.ModeDir}})
+ }
+ sort.Slice(list, func(i, j int) bool {
+ return list[i].name < list[j].name
+ })
+
+ if file == nil {
+ file = &MapFile{Mode: fs.ModeDir}
+ }
+ return &mapDir{name, mapFileInfo{elem, file}, list, 0}, nil
+}
+
+// A mapFileInfo implements fs.FileInfo and fs.DirEntry for a given map file.
+type mapFileInfo struct {
+ name string
+ f *MapFile
+}
+
+func (i *mapFileInfo) Name() string { return i.name }
+func (i *mapFileInfo) Size() int64 { return int64(len(i.f.Data)) }
+func (i *mapFileInfo) Mode() fs.FileMode { return i.f.Mode }
+func (i *mapFileInfo) Type() fs.FileMode { return i.f.Mode.Type() }
+func (i *mapFileInfo) ModTime() time.Time { return i.f.ModTime }
+func (i *mapFileInfo) IsDir() bool { return i.f.Mode&fs.ModeDir != 0 }
+func (i *mapFileInfo) Sys() interface{} { return i.f.Sys }
+func (i *mapFileInfo) Info() (fs.FileInfo, error) { return i, nil }
+
+// An openMapFile is a regular (non-directory) fs.File open for reading.
+type openMapFile struct {
+ path string
+ mapFileInfo
+ offset int64
+}
+
+func (f *openMapFile) Stat() (fs.FileInfo, error) { return &f.mapFileInfo, nil }
+
+func (f *openMapFile) Close() error { return nil }
+
+func (f *openMapFile) Read(b []byte) (int, error) {
+ if f.offset >= int64(len(f.f.Data)) {
+ return 0, io.EOF
+ }
+ if f.offset < 0 {
+ return 0, &fs.PathError{Op: "read", Path: f.path, Err: fs.ErrInvalid}
+ }
+ n := copy(b, f.f.Data[f.offset:])
+ f.offset += int64(n)
+ return n, nil
+}
+
+func (f *openMapFile) Seek(offset int64, whence int) (int64, error) {
+ switch whence {
+ case 0:
+ // offset += 0
+ case 1:
+ offset += f.offset
+ case 2:
+ offset += int64(len(f.f.Data))
+ }
+ if offset < 0 || offset > int64(len(f.f.Data)) {
+ return 0, &fs.PathError{Op: "seek", Path: f.path, Err: fs.ErrInvalid}
+ }
+ f.offset = offset
+ return offset, nil
+}
+
+func (f *openMapFile) ReadAt(b []byte, offset int64) (int, error) {
+ if offset < 0 || offset > int64(len(f.f.Data)) {
+ return 0, &fs.PathError{Op: "read", Path: f.path, Err: fs.ErrInvalid}
+ }
+ n := copy(b, f.f.Data[offset:])
+ if n < len(b) {
+ return n, io.EOF
+ }
+ return n, nil
+}
+
+// A mapDir is a directory fs.File (so also an fs.ReadDirFile) open for reading.
+type mapDir struct {
+ path string
+ mapFileInfo
+ entry []mapFileInfo
+ offset int
+}
+
+func (d *mapDir) Stat() (fs.FileInfo, error) { return &d.mapFileInfo, nil }
+func (d *mapDir) Close() error { return nil }
+func (d *mapDir) Read(b []byte) (int, error) {
+ return 0, &fs.PathError{Op: "read", Path: d.path, Err: fs.ErrInvalid}
+}
+
+func (d *mapDir) ReadDir(count int) ([]fs.DirEntry, error) {
+ n := len(d.entry) - d.offset
+ if count > 0 && n > count {
+ n = count
+ }
+ if n == 0 && count > 0 {
+ return nil, io.EOF
+ }
+ list := make([]fs.DirEntry, n)
+ for i := range list {
+ list[i] = &d.entry[d.offset+i]
+ }
+ d.offset += n
+ return list, nil
+}
diff --git a/src/testing/fstest/mapfs_test.go b/src/testing/fstest/mapfs_test.go
new file mode 100644
index 0000000000..2abedd6735
--- /dev/null
+++ b/src/testing/fstest/mapfs_test.go
@@ -0,0 +1,19 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fstest
+
+import (
+ "testing"
+)
+
+func TestMapFS(t *testing.T) {
+ m := MapFS{
+ "hello": {Data: []byte("hello, world\n")},
+ "fortune/k/ken.txt": {Data: []byte("If a program is too slow, it must have a loop.\n")},
+ }
+ if err := TestFS(m, "hello", "fortune/k/ken.txt"); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/src/testing/fstest/testfs.go b/src/testing/fstest/testfs.go
new file mode 100644
index 0000000000..2bb2120c19
--- /dev/null
+++ b/src/testing/fstest/testfs.go
@@ -0,0 +1,364 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package fstest implements support for testing implementations and users of file systems.
+package fstest
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "io/ioutil"
+ "sort"
+ "strings"
+ "testing/iotest"
+)
+
+// TestFS tests a file system implementation.
+// It walks the entire tree of files in fsys,
+// opening and checking that each file behaves correctly.
+// It also checks that the file system contains at least the expected files.
+//
+// If TestFS finds any misbehaviors, it returns an error reporting all of them.
+// The error text spans multiple lines, one per detected misbehavior.
+//
+// Typical usage inside a test is:
+//
+// if err := fstest.TestFS(myFS, "file/that/should/be/present"); err != nil {
+// t.Fatal(err)
+// }
+//
+func TestFS(fsys fs.FS, expected ...string) error {
+ t := fsTester{fsys: fsys}
+ t.checkDir(".")
+ t.checkOpen(".")
+ found := make(map[string]bool)
+ for _, dir := range t.dirs {
+ found[dir] = true
+ }
+ for _, file := range t.files {
+ found[file] = true
+ }
+ for _, name := range expected {
+ if !found[name] {
+ t.errorf("expected but not found: %s", name)
+ }
+ }
+ if len(t.errText) == 0 {
+ return nil
+ }
+ return errors.New("TestFS found errors:\n" + string(t.errText))
+}
+
+// An fsTester holds state for running the test.
+type fsTester struct {
+ fsys fs.FS
+ errText []byte
+ dirs []string
+ files []string
+}
+
+// errorf adds an error line to errText.
+func (t *fsTester) errorf(format string, args ...interface{}) {
+ if len(t.errText) > 0 {
+ t.errText = append(t.errText, '\n')
+ }
+ t.errText = append(t.errText, fmt.Sprintf(format, args...)...)
+}
+
+func (t *fsTester) openDir(dir string) fs.ReadDirFile {
+ f, err := t.fsys.Open(dir)
+ if err != nil {
+ t.errorf("%s: Open: %v", dir, err)
+ return nil
+ }
+ d, ok := f.(fs.ReadDirFile)
+ if !ok {
+ f.Close()
+ t.errorf("%s: Open returned File type %T, not a io.ReadDirFile", dir, f)
+ return nil
+ }
+ return d
+}
+
+// checkDir checks the directory dir, which is expected to exist
+// (it is either the root or was found in a directory listing with IsDir true).
+func (t *fsTester) checkDir(dir string) {
+ // Read entire directory.
+ t.dirs = append(t.dirs, dir)
+ d := t.openDir(dir)
+ if d == nil {
+ return
+ }
+ list, err := d.ReadDir(-1)
+ if err != nil {
+ d.Close()
+ t.errorf("%s: ReadDir(-1): %v", dir, err)
+ return
+ }
+
+ // Check all children.
+ var prefix string
+ if dir == "." {
+ prefix = ""
+ } else {
+ prefix = dir + "/"
+ }
+ for _, info := range list {
+ name := info.Name()
+ switch {
+ case name == ".", name == "..", name == "":
+ t.errorf("%s: ReadDir: child has invalid name: %#q", dir, name)
+ continue
+ case strings.Contains(name, "/"):
+ t.errorf("%s: ReadDir: child name contains slash: %#q", dir, name)
+ continue
+ case strings.Contains(name, `\`):
+ t.errorf("%s: ReadDir: child name contains backslash: %#q", dir, name)
+ continue
+ }
+ path := prefix + name
+ t.checkStat(path, info)
+ t.checkOpen(path)
+ if info.IsDir() {
+ t.checkDir(path)
+ } else {
+ t.checkFile(path)
+ }
+ }
+
+ // Check ReadDir(-1) at EOF.
+ list2, err := d.ReadDir(-1)
+ if len(list2) > 0 || err != nil {
+ d.Close()
+ t.errorf("%s: ReadDir(-1) at EOF = %d entries, %v, wanted 0 entries, nil", dir, len(list2), err)
+ return
+ }
+
+ // Check ReadDir(1) at EOF (different results).
+ list2, err = d.ReadDir(1)
+ if len(list2) > 0 || err != io.EOF {
+ d.Close()
+ t.errorf("%s: ReadDir(1) at EOF = %d entries, %v, wanted 0 entries, EOF", dir, len(list2), err)
+ return
+ }
+
+ // Check that close does not report an error.
+ if err := d.Close(); err != nil {
+ t.errorf("%s: Close: %v", dir, err)
+ }
+
+ // Check that closing twice doesn't crash.
+ // The return value doesn't matter.
+ d.Close()
+
+ // Reopen directory, read a second time, make sure contents match.
+ if d = t.openDir(dir); d == nil {
+ return
+ }
+ defer d.Close()
+ list2, err = d.ReadDir(-1)
+ if err != nil {
+ t.errorf("%s: second Open+ReadDir(-1): %v", dir, err)
+ return
+ }
+ t.checkDirList(dir, "first Open+ReadDir(-1) vs second Open+ReadDir(-1)", list, list2)
+
+ // Reopen directory, read a third time in pieces, make sure contents match.
+ if d = t.openDir(dir); d == nil {
+ return
+ }
+ defer d.Close()
+ list2 = nil
+ for {
+ n := 1
+ if len(list2) > 0 {
+ n = 2
+ }
+ frag, err := d.ReadDir(n)
+ if len(frag) > n {
+ t.errorf("%s: third Open: ReadDir(%d) after %d: %d entries (too many)", dir, n, len(list2), len(frag))
+ return
+ }
+ list2 = append(list2, frag...)
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.errorf("%s: third Open: ReadDir(%d) after %d: %v", dir, n, len(list2), err)
+ return
+ }
+ if n == 0 {
+ t.errorf("%s: third Open: ReadDir(%d) after %d: 0 entries but nil error", dir, n, len(list2))
+ return
+ }
+ }
+ t.checkDirList(dir, "first Open+ReadDir(-1) vs third Open+ReadDir(1,2) loop", list, list2)
+}
+
+// formatEntry formats an fs.DirEntry into a string for error messages and comparison.
+func formatEntry(entry fs.DirEntry) string {
+ return fmt.Sprintf("%s IsDir=%v Type=%v", entry.Name(), entry.IsDir(), entry.Type())
+}
+
+// formatInfoEntry formats an fs.FileInfo into a string like the result of formatEntry, for error messages and comparison.
+func formatInfoEntry(info fs.FileInfo) string {
+ return fmt.Sprintf("%s IsDir=%v Type=%v", info.Name(), info.IsDir(), info.Mode().Type())
+}
+
+// formatInfo formats an fs.FileInfo into a string for error messages and comparison.
+func formatInfo(info fs.FileInfo) string {
+ return fmt.Sprintf("%s IsDir=%v Mode=%v Size=%d ModTime=%v", info.Name(), info.IsDir(), info.Mode(), info.Size(), info.ModTime())
+}
+
+// checkStat checks that a direct stat of path matches entry,
+// which was found in the parent's directory listing.
+func (t *fsTester) checkStat(path string, entry fs.DirEntry) {
+ file, err := t.fsys.Open(path)
+ if err != nil {
+ t.errorf("%s: Open: %v", path, err)
+ return
+ }
+ info, err := file.Stat()
+ file.Close()
+ if err != nil {
+ t.errorf("%s: Stat: %v", path, err)
+ return
+ }
+ fentry := formatEntry(entry)
+ finfo := formatInfoEntry(info)
+ if fentry != finfo {
+ t.errorf("%s: mismatch:\n\tentry = %v\n\tfile.Stat() = %v", path, fentry, finfo)
+ }
+}
+
+// checkDirList checks that two directory lists contain the same files and file info.
+// The order of the lists need not match.
+func (t *fsTester) checkDirList(dir, desc string, list1, list2 []fs.DirEntry) {
+ old := make(map[string]fs.DirEntry)
+ checkMode := func(entry fs.DirEntry) {
+ if entry.IsDir() != (entry.Type()&fs.ModeDir != 0) {
+ if entry.IsDir() {
+ t.errorf("%s: ReadDir returned %s with IsDir() = true, Type() & ModeDir = 0", dir, entry.Name())
+ } else {
+ t.errorf("%s: ReadDir returned %s with IsDir() = false, Type() & ModeDir = ModeDir", dir, entry.Name())
+ }
+ }
+ }
+
+ for _, entry1 := range list1 {
+ old[entry1.Name()] = entry1
+ checkMode(entry1)
+ }
+
+ var diffs []string
+ for _, entry2 := range list2 {
+ entry1 := old[entry2.Name()]
+ if entry1 == nil {
+ checkMode(entry2)
+ diffs = append(diffs, "+ "+formatEntry(entry2))
+ continue
+ }
+ if formatEntry(entry1) != formatEntry(entry2) {
+ diffs = append(diffs, "- "+formatEntry(entry1), "+ "+formatEntry(entry2))
+ }
+ delete(old, entry2.Name())
+ }
+ for _, entry1 := range old {
+ diffs = append(diffs, "- "+formatEntry(entry1))
+ }
+
+ if len(diffs) == 0 {
+ return
+ }
+
+ sort.Slice(diffs, func(i, j int) bool {
+ fi := strings.Fields(diffs[i])
+ fj := strings.Fields(diffs[j])
+ // sort by name (i < j) and then +/- (j < i, because + < -)
+ return fi[1]+" "+fj[0] < fj[1]+" "+fi[0]
+ })
+
+ t.errorf("%s: diff %s:\n\t%s", dir, desc, strings.Join(diffs, "\n\t"))
+}
+
+// checkFile checks that basic file reading works correctly.
+func (t *fsTester) checkFile(file string) {
+ t.files = append(t.files, file)
+
+ // Read entire file.
+ f, err := t.fsys.Open(file)
+ if err != nil {
+ t.errorf("%s: Open: %v", file, err)
+ return
+ }
+
+ data, err := ioutil.ReadAll(f)
+ if err != nil {
+ f.Close()
+ t.errorf("%s: Open+ReadAll: %v", file, err)
+ return
+ }
+
+ if err := f.Close(); err != nil {
+ t.errorf("%s: Close: %v", file, err)
+ }
+
+ // Check that closing twice doesn't crash.
+ // The return value doesn't matter.
+ f.Close()
+
+ // Use iotest.TestReader to check small reads, Seek, ReadAt.
+ f, err = t.fsys.Open(file)
+ if err != nil {
+ t.errorf("%s: second Open: %v", file, err)
+ return
+ }
+ defer f.Close()
+ if err := iotest.TestReader(f, data); err != nil {
+ t.errorf("%s: failed TestReader:\n\t%s", file, strings.ReplaceAll(err.Error(), "\n", "\n\t"))
+ }
+}
+
+func (t *fsTester) checkFileRead(file, desc string, data1, data2 []byte) {
+ if string(data1) != string(data2) {
+ t.errorf("%s: %s: different data returned\n\t%q\n\t%q", file, desc, data1, data2)
+ return
+ }
+}
+
+// checkOpen checks that various invalid forms of file's name cannot be opened.
+func (t *fsTester) checkOpen(file string) {
+ bad := []string{
+ "/" + file,
+ file + "/.",
+ }
+ if file == "." {
+ bad = append(bad, "/")
+ }
+ if i := strings.Index(file, "/"); i >= 0 {
+ bad = append(bad,
+ file[:i]+"//"+file[i+1:],
+ file[:i]+"/./"+file[i+1:],
+ file[:i]+`\`+file[i+1:],
+ file[:i]+"/../"+file,
+ )
+ }
+ if i := strings.LastIndex(file, "/"); i >= 0 {
+ bad = append(bad,
+ file[:i]+"//"+file[i+1:],
+ file[:i]+"/./"+file[i+1:],
+ file[:i]+`\`+file[i+1:],
+ file+"/../"+file[i+1:],
+ )
+ }
+
+ for _, b := range bad {
+ if f, err := t.fsys.Open(b); err == nil {
+ f.Close()
+ t.errorf("%s: Open(%s) succeeded, want error", file, b)
+ }
+ }
+}
--
cgit v1.3
From f098ccf04a33e2e4d2dffa2e90fe77ca8a0fcbb4 Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Mon, 6 Jul 2020 11:26:26 -0400
Subject: io/fs: add ReadFile and ReadFileFS
Add ReadFile helper function, ReadFileFS interface, and test.
Add ReadFile method to fstest.MapFS.
Add testing of ReadFile method to fstest.TestFS.
For #41190.
Change-Id: I5b6a41e2e582824e570463b698b635abaa436c32
Reviewed-on: https://go-review.googlesource.com/c/go/+/243912
Trust: Russ Cox
Reviewed-by: Rob Pike
---
src/go/build/deps_test.go | 4 ++-
src/io/fs/readfile.go | 63 ++++++++++++++++++++++++++++++++++++++++++++
src/io/fs/readfile_test.go | 43 ++++++++++++++++++++++++++++++
src/testing/fstest/mapfs.go | 12 +++++++++
src/testing/fstest/testfs.go | 39 ++++++++++++++++++++++++---
5 files changed, 156 insertions(+), 5 deletions(-)
create mode 100644 src/io/fs/readfile.go
create mode 100644 src/io/fs/readfile_test.go
(limited to 'src/testing')
diff --git a/src/go/build/deps_test.go b/src/go/build/deps_test.go
index 4867a5031a..ccee539086 100644
--- a/src/go/build/deps_test.go
+++ b/src/go/build/deps_test.go
@@ -165,7 +165,9 @@ var depsRules = `
os/signal, STR
< path/filepath
- < io/ioutil, os/exec
+ < io/ioutil, os/exec;
+
+ io/ioutil, os/exec, os/signal
< OS;
reflect !< OS;
diff --git a/src/io/fs/readfile.go b/src/io/fs/readfile.go
new file mode 100644
index 0000000000..7ee9eadac4
--- /dev/null
+++ b/src/io/fs/readfile.go
@@ -0,0 +1,63 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs
+
+import "io"
+
+// ReadFileFS is the interface implemented by a file system
+// that provides an optimized implementation of ReadFile.
+type ReadFileFS interface {
+ FS
+
+ // ReadFile reads the named file and returns its contents.
+ // A successful call returns a nil error, not io.EOF.
+ // (Because ReadFile reads the whole file, the expected EOF
+ // from the final Read is not treated as an error to be reported.)
+ ReadFile(name string) ([]byte, error)
+}
+
+// ReadFile reads the named file from the file system fs and returns its contents.
+// A successful call returns a nil error, not io.EOF.
+// (Because ReadFile reads the whole file, the expected EOF
+// from the final Read is not treated as an error to be reported.)
+//
+// If fs implements ReadFileFS, ReadFile calls fs.ReadFile.
+// Otherwise ReadFile calls fs.Open and uses Read and Close
+// on the returned file.
+func ReadFile(fsys FS, name string) ([]byte, error) {
+ if fsys, ok := fsys.(ReadFileFS); ok {
+ return fsys.ReadFile(name)
+ }
+
+ file, err := fsys.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+
+ var size int
+ if info, err := file.Stat(); err == nil {
+ size64 := info.Size()
+ if int64(int(size64)) == size64 {
+ size = int(size64)
+ }
+ }
+
+ data := make([]byte, 0, size+1)
+ for {
+ if len(data) >= cap(data) {
+ d := append(data[:cap(data)], 0)
+ data = d[:len(data)]
+ }
+ n, err := file.Read(data[len(data):cap(data)])
+ data = data[:len(data)+n]
+ if err != nil {
+ if err == io.EOF {
+ err = nil
+ }
+ return data, err
+ }
+ }
+}
diff --git a/src/io/fs/readfile_test.go b/src/io/fs/readfile_test.go
new file mode 100644
index 0000000000..0afa334ace
--- /dev/null
+++ b/src/io/fs/readfile_test.go
@@ -0,0 +1,43 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs_test
+
+import (
+ . "io/fs"
+ "testing"
+ "testing/fstest"
+ "time"
+)
+
+var testFsys = fstest.MapFS{
+ "hello.txt": {
+ Data: []byte("hello, world"),
+ Mode: 0456,
+ ModTime: time.Now(),
+ Sys: &sysValue,
+ },
+}
+
+var sysValue int
+
+type readFileOnly struct{ ReadFileFS }
+
+func (readFileOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+type openOnly struct{ FS }
+
+func TestReadFile(t *testing.T) {
+ // Test that ReadFile uses the method when present.
+ data, err := ReadFile(readFileOnly{testFsys}, "hello.txt")
+ if string(data) != "hello, world" || err != nil {
+ t.Fatalf(`ReadFile(readFileOnly, "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
+ }
+
+ // Test that ReadFile uses Open when the method is not present.
+ data, err = ReadFile(openOnly{testFsys}, "hello.txt")
+ if string(data) != "hello, world" || err != nil {
+ t.Fatalf(`ReadFile(openOnly, "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
+ }
+}
diff --git a/src/testing/fstest/mapfs.go b/src/testing/fstest/mapfs.go
index 84a943f409..e969ac2bd1 100644
--- a/src/testing/fstest/mapfs.go
+++ b/src/testing/fstest/mapfs.go
@@ -108,6 +108,18 @@ func (fsys MapFS) Open(name string) (fs.File, error) {
return &mapDir{name, mapFileInfo{elem, file}, list, 0}, nil
}
+// fsOnly is a wrapper that hides all but the fs.FS methods,
+// to avoid an infinite recursion when implementing special
+// methods in terms of helpers that would use them.
+// (In general, implementing these methods using the package fs helpers
+// is redundant and unnecessary, but having the methods may make
+// MapFS exercise more code paths when used in tests.)
+type fsOnly struct{ fs.FS }
+
+func (fsys MapFS) ReadFile(name string) ([]byte, error) {
+ return fs.ReadFile(fsOnly{fsys}, name)
+}
+
// A mapFileInfo implements fs.FileInfo and fs.DirEntry for a given map file.
type mapFileInfo struct {
name string
diff --git a/src/testing/fstest/testfs.go b/src/testing/fstest/testfs.go
index 2bb2120c19..66725ca2a4 100644
--- a/src/testing/fstest/testfs.go
+++ b/src/testing/fstest/testfs.go
@@ -310,6 +310,27 @@ func (t *fsTester) checkFile(file string) {
// The return value doesn't matter.
f.Close()
+ // Check that ReadFile works if present.
+ if fsys, ok := t.fsys.(fs.ReadFileFS); ok {
+ data2, err := fsys.ReadFile(file)
+ if err != nil {
+ t.errorf("%s: fsys.ReadFile: %v", file, err)
+ return
+ }
+ t.checkFileRead(file, "ReadAll vs fsys.ReadFile", data, data2)
+
+ t.checkBadPath(file, "ReadFile",
+ func(name string) error { _, err := fsys.ReadFile(name); return err })
+ }
+
+ // Check that fs.ReadFile works with t.fsys.
+ data2, err := fs.ReadFile(t.fsys, file)
+ if err != nil {
+ t.errorf("%s: fs.ReadFile: %v", file, err)
+ return
+ }
+ t.checkFileRead(file, "ReadAll vs fs.ReadFile", data, data2)
+
// Use iotest.TestReader to check small reads, Seek, ReadAt.
f, err = t.fsys.Open(file)
if err != nil {
@@ -329,8 +350,19 @@ func (t *fsTester) checkFileRead(file, desc string, data1, data2 []byte) {
}
}
-// checkOpen checks that various invalid forms of file's name cannot be opened.
+// checkBadPath checks that various invalid forms of file's name cannot be opened using t.fsys.Open.
func (t *fsTester) checkOpen(file string) {
+ t.checkBadPath(file, "Open", func(file string) error {
+ f, err := t.fsys.Open(file)
+ if err == nil {
+ f.Close()
+ }
+ return err
+ })
+}
+
+// checkBadPath checks that various invalid forms of file's name cannot be opened using open.
+func (t *fsTester) checkBadPath(file string, desc string, open func(string) error) {
bad := []string{
"/" + file,
file + "/.",
@@ -356,9 +388,8 @@ func (t *fsTester) checkOpen(file string) {
}
for _, b := range bad {
- if f, err := t.fsys.Open(b); err == nil {
- f.Close()
- t.errorf("%s: Open(%s) succeeded, want error", file, b)
+ if err := open(b); err == nil {
+ t.errorf("%s: %s(%s) succeeded, want error", file, desc, b)
}
}
}
--
cgit v1.3
From 10a1a1a37c007adef8425d273e6b276547982889 Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Mon, 6 Jul 2020 11:26:45 -0400
Subject: io/fs: add Stat and StatFS
Add Stat helper function, StatFS interface, and test.
Add Stat method to fstest.MapFS.
Add testing of Stat method to fstest.TestFS.
For #41190.
Change-Id: Icf8b6eb1c3fa6f93a9be8405ec5a9468fb1da97b
Reviewed-on: https://go-review.googlesource.com/c/go/+/243913
Trust: Russ Cox
Reviewed-by: Rob Pike
---
src/io/fs/stat.go | 31 +++++++++++++++++++++++++++++++
src/io/fs/stat_test.go | 36 ++++++++++++++++++++++++++++++++++++
src/testing/fstest/mapfs.go | 4 ++++
src/testing/fstest/testfs.go | 25 ++++++++++++++++++++++++-
4 files changed, 95 insertions(+), 1 deletion(-)
create mode 100644 src/io/fs/stat.go
create mode 100644 src/io/fs/stat_test.go
(limited to 'src/testing')
diff --git a/src/io/fs/stat.go b/src/io/fs/stat.go
new file mode 100644
index 0000000000..735a6e3281
--- /dev/null
+++ b/src/io/fs/stat.go
@@ -0,0 +1,31 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs
+
+// A StatFS is a file system with a Stat method.
+type StatFS interface {
+ FS
+
+ // Stat returns a FileInfo describing the file.
+ // If there is an error, it should be of type *PathError.
+ Stat(name string) (FileInfo, error)
+}
+
+// Stat returns a FileInfo describing the named file from the file system.
+//
+// If fs implements StatFS, Stat calls fs.Stat.
+// Otherwise, Stat opens the file to stat it.
+func Stat(fsys FS, name string) (FileInfo, error) {
+ if fsys, ok := fsys.(StatFS); ok {
+ return fsys.Stat(name)
+ }
+
+ file, err := fsys.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ return file.Stat()
+}
diff --git a/src/io/fs/stat_test.go b/src/io/fs/stat_test.go
new file mode 100644
index 0000000000..e312b6fbd9
--- /dev/null
+++ b/src/io/fs/stat_test.go
@@ -0,0 +1,36 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs_test
+
+import (
+ "fmt"
+ . "io/fs"
+ "testing"
+)
+
+type statOnly struct{ StatFS }
+
+func (statOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+func TestStat(t *testing.T) {
+ check := func(desc string, info FileInfo, err error) {
+ t.Helper()
+ if err != nil || info == nil || info.Mode() != 0456 {
+ infoStr := ""
+ if info != nil {
+ infoStr = fmt.Sprintf("FileInfo(Mode: %#o)", info.Mode())
+ }
+ t.Fatalf("Stat(%s) = %v, %v, want Mode:0456, nil", desc, infoStr, err)
+ }
+ }
+
+ // Test that Stat uses the method when present.
+ info, err := Stat(statOnly{testFsys}, "hello.txt")
+ check("statOnly", info, err)
+
+ // Test that Stat uses Open when the method is not present.
+ info, err = Stat(openOnly{testFsys}, "hello.txt")
+ check("openOnly", info, err)
+}
diff --git a/src/testing/fstest/mapfs.go b/src/testing/fstest/mapfs.go
index e969ac2bd1..b01911e589 100644
--- a/src/testing/fstest/mapfs.go
+++ b/src/testing/fstest/mapfs.go
@@ -120,6 +120,10 @@ func (fsys MapFS) ReadFile(name string) ([]byte, error) {
return fs.ReadFile(fsOnly{fsys}, name)
}
+func (fsys MapFS) Stat(name string) (fs.FileInfo, error) {
+ return fs.Stat(fsOnly{fsys}, name)
+}
+
// A mapFileInfo implements fs.FileInfo and fs.DirEntry for a given map file.
type mapFileInfo struct {
name string
diff --git a/src/testing/fstest/testfs.go b/src/testing/fstest/testfs.go
index 66725ca2a4..290d2596cc 100644
--- a/src/testing/fstest/testfs.go
+++ b/src/testing/fstest/testfs.go
@@ -230,7 +230,30 @@ func (t *fsTester) checkStat(path string, entry fs.DirEntry) {
fentry := formatEntry(entry)
finfo := formatInfoEntry(info)
if fentry != finfo {
- t.errorf("%s: mismatch:\n\tentry = %v\n\tfile.Stat() = %v", path, fentry, finfo)
+ t.errorf("%s: mismatch:\n\tentry = %s\n\tfile.Stat() = %s", path, fentry, finfo)
+ }
+
+ info2, err := fs.Stat(t.fsys, path)
+ if err != nil {
+ t.errorf("%s: fs.Stat: %v", path, err)
+ return
+ }
+ finfo = formatInfo(info)
+ finfo2 := formatInfo(info2)
+ if finfo2 != finfo {
+ t.errorf("%s: fs.Stat(...) = %s\n\twant %s", path, finfo2, finfo)
+ }
+
+ if fsys, ok := t.fsys.(fs.StatFS); ok {
+ info2, err := fsys.Stat(path)
+ if err != nil {
+ t.errorf("%s: fsys.Stat: %v", path, err)
+ return
+ }
+ finfo2 := formatInfo(info2)
+ if finfo2 != finfo {
+ t.errorf("%s: fsys.Stat(...) = %s\n\twant %s", path, finfo2, finfo)
+ }
}
}
--
cgit v1.3
From 7a131acfd142f0fc7612365078b9f00e371fc0e2 Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Mon, 6 Jul 2020 11:26:56 -0400
Subject: io/fs: add ReadDir and ReadDirFS
Add ReadDir helper function, ReadDirFS interface, and test.
Add ReadDir method to fstest.MapFS.
Add testing of ReadDir method to fstest.TestFS.
For #41190.
Change-Id: Ib860770ec7433ba77b29e626682b238f1b3bf54f
Reviewed-on: https://go-review.googlesource.com/c/go/+/243914
Trust: Russ Cox
Reviewed-by: Rob Pike
---
src/io/fs/readdir.go | 47 ++++++++++++++++++++++++++++++++++++++++++++
src/io/fs/readdir_test.go | 35 +++++++++++++++++++++++++++++++++
src/testing/fstest/mapfs.go | 4 ++++
src/testing/fstest/testfs.go | 42 ++++++++++++++++++++++++++++++++++++++-
4 files changed, 127 insertions(+), 1 deletion(-)
create mode 100644 src/io/fs/readdir.go
create mode 100644 src/io/fs/readdir_test.go
(limited to 'src/testing')
diff --git a/src/io/fs/readdir.go b/src/io/fs/readdir.go
new file mode 100644
index 0000000000..3a5aa6d86a
--- /dev/null
+++ b/src/io/fs/readdir.go
@@ -0,0 +1,47 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs
+
+import (
+ "errors"
+ "sort"
+)
+
+// ReadDirFS is the interface implemented by a file system
+// that provides an optimized implementation of ReadDir.
+type ReadDirFS interface {
+ FS
+
+ // ReadDir reads the named directory
+ // and returns a list of directory entries sorted by filename.
+ ReadDir(name string) ([]DirEntry, error)
+}
+
+// ReadDir reads the named directory
+// and returns a list of directory entries sorted by filename.
+//
+// If fs implements ReadDirFS, ReadDir calls fs.ReadDir.
+// Otherwise ReadDir calls fs.Open and uses ReadDir and Close
+// on the returned file.
+func ReadDir(fsys FS, name string) ([]DirEntry, error) {
+ if fsys, ok := fsys.(ReadDirFS); ok {
+ return fsys.ReadDir(name)
+ }
+
+ file, err := fsys.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+
+ dir, ok := file.(ReadDirFile)
+ if !ok {
+ return nil, &PathError{Op: "readdir", Path: name, Err: errors.New("not implemented")}
+ }
+
+ list, err := dir.ReadDir(-1)
+ sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
+ return list, err
+}
diff --git a/src/io/fs/readdir_test.go b/src/io/fs/readdir_test.go
new file mode 100644
index 0000000000..46a4bc2788
--- /dev/null
+++ b/src/io/fs/readdir_test.go
@@ -0,0 +1,35 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs_test
+
+import (
+ . "io/fs"
+ "testing"
+)
+
+type readDirOnly struct{ ReadDirFS }
+
+func (readDirOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+func TestReadDir(t *testing.T) {
+ check := func(desc string, dirs []DirEntry, err error) {
+ t.Helper()
+ if err != nil || len(dirs) != 1 || dirs[0].Name() != "hello.txt" {
+ var names []string
+ for _, d := range dirs {
+ names = append(names, d.Name())
+ }
+ t.Errorf("ReadDir(%s) = %v, %v, want %v, nil", desc, names, err, []string{"hello.txt"})
+ }
+ }
+
+ // Test that ReadDir uses the method when present.
+ dirs, err := ReadDir(readDirOnly{testFsys}, ".")
+ check("readDirOnly", dirs, err)
+
+ // Test that ReadDir uses Open when the method is not present.
+ dirs, err = ReadDir(openOnly{testFsys}, ".")
+ check("openOnly", dirs, err)
+}
diff --git a/src/testing/fstest/mapfs.go b/src/testing/fstest/mapfs.go
index b01911e589..1eaf8f0040 100644
--- a/src/testing/fstest/mapfs.go
+++ b/src/testing/fstest/mapfs.go
@@ -124,6 +124,10 @@ func (fsys MapFS) Stat(name string) (fs.FileInfo, error) {
return fs.Stat(fsOnly{fsys}, name)
}
+func (fsys MapFS) ReadDir(name string) ([]fs.DirEntry, error) {
+ return fs.ReadDir(fsOnly{fsys}, name)
+}
+
// A mapFileInfo implements fs.FileInfo and fs.DirEntry for a given map file.
type mapFileInfo struct {
name string
diff --git a/src/testing/fstest/testfs.go b/src/testing/fstest/testfs.go
index 290d2596cc..4ea6ed6095 100644
--- a/src/testing/fstest/testfs.go
+++ b/src/testing/fstest/testfs.go
@@ -196,6 +196,36 @@ func (t *fsTester) checkDir(dir string) {
}
}
t.checkDirList(dir, "first Open+ReadDir(-1) vs third Open+ReadDir(1,2) loop", list, list2)
+
+ // If fsys has ReadDir, check that it matches and is sorted.
+ if fsys, ok := t.fsys.(fs.ReadDirFS); ok {
+ list2, err := fsys.ReadDir(dir)
+ if err != nil {
+ t.errorf("%s: fsys.ReadDir: %v", dir, err)
+ return
+ }
+ t.checkDirList(dir, "first Open+ReadDir(-1) vs fsys.ReadDir", list, list2)
+
+ for i := 0; i+1 < len(list2); i++ {
+ if list2[i].Name() >= list2[i+1].Name() {
+ t.errorf("%s: fsys.ReadDir: list not sorted: %s before %s", dir, list2[i].Name(), list2[i+1].Name())
+ }
+ }
+ }
+
+ // Check fs.ReadDir as well.
+ list2, err = fs.ReadDir(t.fsys, dir)
+ if err != nil {
+ t.errorf("%s: fs.ReadDir: %v", dir, err)
+ return
+ }
+ t.checkDirList(dir, "first Open+ReadDir(-1) vs fs.ReadDir", list, list2)
+
+ for i := 0; i+1 < len(list2); i++ {
+ if list2[i].Name() >= list2[i+1].Name() {
+ t.errorf("%s: fs.ReadDir: list not sorted: %s before %s", dir, list2[i].Name(), list2[i+1].Name())
+ }
+ }
}
// formatEntry formats an fs.DirEntry into a string for error messages and comparison.
@@ -233,12 +263,22 @@ func (t *fsTester) checkStat(path string, entry fs.DirEntry) {
t.errorf("%s: mismatch:\n\tentry = %s\n\tfile.Stat() = %s", path, fentry, finfo)
}
+ einfo, err := entry.Info()
+ if err != nil {
+ t.errorf("%s: entry.Info: %v", path, err)
+ return
+ }
+ fentry = formatInfo(einfo)
+ finfo = formatInfo(info)
+ if fentry != finfo {
+ t.errorf("%s: mismatch:\n\tentry.Info() = %s\n\tfile.Stat() = %s\n", path, fentry, finfo)
+ }
+
info2, err := fs.Stat(t.fsys, path)
if err != nil {
t.errorf("%s: fs.Stat: %v", path, err)
return
}
- finfo = formatInfo(info)
finfo2 := formatInfo(info2)
if finfo2 != finfo {
t.errorf("%s: fs.Stat(...) = %s\n\twant %s", path, finfo2, finfo)
--
cgit v1.3
From b64202bc29b9c1cf0118878d1c0acc9cdb2308f6 Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Mon, 6 Jul 2020 11:27:12 -0400
Subject: io/fs: add Glob and GlobFS
Add Glob helper function, GlobFS interface, and test.
Add Glob method to fstest.MapFS.
Add testing of Glob method to fstest.TestFS.
For #41190.
Change-Id: If89dd7f63e310ba5ca2651340267a9ff39fcc0c7
Reviewed-on: https://go-review.googlesource.com/c/go/+/243915
Trust: Russ Cox
Reviewed-by: Rob Pike
---
src/go/build/deps_test.go | 2 +-
src/io/fs/glob.go | 116 +++++++++++++++++++++++++++++++++++++++++++
src/io/fs/glob_test.go | 82 ++++++++++++++++++++++++++++++
src/testing/fstest/mapfs.go | 4 ++
src/testing/fstest/testfs.go | 96 +++++++++++++++++++++++++++++++++++
5 files changed, 299 insertions(+), 1 deletion(-)
create mode 100644 src/io/fs/glob.go
create mode 100644 src/io/fs/glob_test.go
(limited to 'src/testing')
diff --git a/src/go/build/deps_test.go b/src/go/build/deps_test.go
index ccee539086..16a67791cf 100644
--- a/src/go/build/deps_test.go
+++ b/src/go/build/deps_test.go
@@ -123,7 +123,7 @@ var depsRules = `
< context
< TIME;
- TIME, io, sort
+ TIME, io, path, sort
< io/fs;
# MATH is RUNTIME plus the basic math packages.
diff --git a/src/io/fs/glob.go b/src/io/fs/glob.go
new file mode 100644
index 0000000000..77f6ebbaaf
--- /dev/null
+++ b/src/io/fs/glob.go
@@ -0,0 +1,116 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs
+
+import (
+ "path"
+ "runtime"
+)
+
+// A GlobFS is a file system with a Glob method.
+type GlobFS interface {
+ FS
+
+ // Glob returns the names of all files matching pattern,
+ // providing an implementation of the top-level
+ // Glob function.
+ Glob(pattern string) ([]string, error)
+}
+
+// Glob returns the names of all files matching pattern or nil
+// if there is no matching file. The syntax of patterns is the same
+// as in path.Match. The pattern may describe hierarchical names such as
+// /usr/*/bin/ed (assuming the Separator is '/').
+//
+// Glob ignores file system errors such as I/O errors reading directories.
+// The only possible returned error is path.ErrBadPattern, reporting that
+// the pattern is malformed.
+//
+// If fs implements GlobFS, Glob calls fs.Glob.
+// Otherwise, Glob uses ReadDir to traverse the directory tree
+// and look for matches for the pattern.
+func Glob(fsys FS, pattern string) (matches []string, err error) {
+ if fsys, ok := fsys.(GlobFS); ok {
+ return fsys.Glob(pattern)
+ }
+
+ if !hasMeta(pattern) {
+ if _, err = Stat(fsys, pattern); err != nil {
+ return nil, nil
+ }
+ return []string{pattern}, nil
+ }
+
+ dir, file := path.Split(pattern)
+ dir = cleanGlobPath(dir)
+
+ if !hasMeta(dir) {
+ return glob(fsys, dir, file, nil)
+ }
+
+ // Prevent infinite recursion. See issue 15879.
+ if dir == pattern {
+ return nil, path.ErrBadPattern
+ }
+
+ var m []string
+ m, err = Glob(fsys, dir)
+ if err != nil {
+ return
+ }
+ for _, d := range m {
+ matches, err = glob(fsys, d, file, matches)
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// cleanGlobPath prepares path for glob matching.
+func cleanGlobPath(path string) string {
+ switch path {
+ case "":
+ return "."
+ default:
+ return path[0 : len(path)-1] // chop off trailing separator
+ }
+}
+
+// glob searches for files matching pattern in the directory dir
+// and appends them to matches, returning the updated slice.
+// If the directory cannot be opened, glob returns the existing matches.
+// New matches are added in lexicographical order.
+func glob(fs FS, dir, pattern string, matches []string) (m []string, e error) {
+ m = matches
+ infos, err := ReadDir(fs, dir)
+ if err != nil {
+ return // ignore I/O error
+ }
+
+ for _, info := range infos {
+ n := info.Name()
+ matched, err := path.Match(pattern, n)
+ if err != nil {
+ return m, err
+ }
+ if matched {
+ m = append(m, path.Join(dir, n))
+ }
+ }
+ return
+}
+
+// hasMeta reports whether path contains any of the magic characters
+// recognized by path.Match.
+func hasMeta(path string) bool {
+ for i := 0; i < len(path); i++ {
+ c := path[i]
+ if c == '*' || c == '?' || c == '[' || runtime.GOOS == "windows" && c == '\\' {
+ return true
+ }
+ }
+ return false
+}
diff --git a/src/io/fs/glob_test.go b/src/io/fs/glob_test.go
new file mode 100644
index 0000000000..0183a49b6c
--- /dev/null
+++ b/src/io/fs/glob_test.go
@@ -0,0 +1,82 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs_test
+
+import (
+ . "io/fs"
+ "os"
+ "testing"
+)
+
+var globTests = []struct {
+ fs FS
+ pattern, result string
+}{
+ {os.DirFS("."), "glob.go", "glob.go"},
+ {os.DirFS("."), "gl?b.go", "glob.go"},
+ {os.DirFS("."), "*", "glob.go"},
+ {os.DirFS(".."), "*/glob.go", "fs/glob.go"},
+}
+
+func TestGlob(t *testing.T) {
+ for _, tt := range globTests {
+ matches, err := Glob(tt.fs, tt.pattern)
+ if err != nil {
+ t.Errorf("Glob error for %q: %s", tt.pattern, err)
+ continue
+ }
+ if !contains(matches, tt.result) {
+ t.Errorf("Glob(%#q) = %#v want %v", tt.pattern, matches, tt.result)
+ }
+ }
+ for _, pattern := range []string{"no_match", "../*/no_match"} {
+ matches, err := Glob(os.DirFS("."), pattern)
+ if err != nil {
+ t.Errorf("Glob error for %q: %s", pattern, err)
+ continue
+ }
+ if len(matches) != 0 {
+ t.Errorf("Glob(%#q) = %#v want []", pattern, matches)
+ }
+ }
+}
+
+func TestGlobError(t *testing.T) {
+ _, err := Glob(os.DirFS("."), "[]")
+ if err == nil {
+ t.Error("expected error for bad pattern; got none")
+ }
+}
+
+// contains reports whether vector contains the string s.
+func contains(vector []string, s string) bool {
+ for _, elem := range vector {
+ if elem == s {
+ return true
+ }
+ }
+ return false
+}
+
+type globOnly struct{ GlobFS }
+
+func (globOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+func TestGlobMethod(t *testing.T) {
+ check := func(desc string, names []string, err error) {
+ t.Helper()
+ if err != nil || len(names) != 1 || names[0] != "hello.txt" {
+ t.Errorf("Glob(%s) = %v, %v, want %v, nil", desc, names, err, []string{"hello.txt"})
+ }
+ }
+
+ // Test that ReadDir uses the method when present.
+ names, err := Glob(globOnly{testFsys}, "*.txt")
+ check("readDirOnly", names, err)
+
+ // Test that ReadDir uses Open when the method is not present.
+ names, err = Glob(openOnly{testFsys}, "*.txt")
+ check("openOnly", names, err)
+}
diff --git a/src/testing/fstest/mapfs.go b/src/testing/fstest/mapfs.go
index 1eaf8f0040..10e56f5b3c 100644
--- a/src/testing/fstest/mapfs.go
+++ b/src/testing/fstest/mapfs.go
@@ -128,6 +128,10 @@ func (fsys MapFS) ReadDir(name string) ([]fs.DirEntry, error) {
return fs.ReadDir(fsOnly{fsys}, name)
}
+func (fsys MapFS) Glob(pattern string) ([]string, error) {
+ return fs.Glob(fsOnly{fsys}, pattern)
+}
+
// A mapFileInfo implements fs.FileInfo and fs.DirEntry for a given map file.
type mapFileInfo struct {
name string
diff --git a/src/testing/fstest/testfs.go b/src/testing/fstest/testfs.go
index 4ea6ed6095..21cd00e5b6 100644
--- a/src/testing/fstest/testfs.go
+++ b/src/testing/fstest/testfs.go
@@ -11,6 +11,8 @@ import (
"io"
"io/fs"
"io/ioutil"
+ "path"
+ "reflect"
"sort"
"strings"
"testing/iotest"
@@ -226,6 +228,8 @@ func (t *fsTester) checkDir(dir string) {
t.errorf("%s: fs.ReadDir: list not sorted: %s before %s", dir, list2[i].Name(), list2[i+1].Name())
}
}
+
+ t.checkGlob(dir, list)
}
// formatEntry formats an fs.DirEntry into a string for error messages and comparison.
@@ -243,6 +247,98 @@ func formatInfo(info fs.FileInfo) string {
return fmt.Sprintf("%s IsDir=%v Mode=%v Size=%d ModTime=%v", info.Name(), info.IsDir(), info.Mode(), info.Size(), info.ModTime())
}
+// checkGlob checks that various glob patterns work if the file system implements GlobFS.
+func (t *fsTester) checkGlob(dir string, list []fs.DirEntry) {
+ if _, ok := t.fsys.(fs.GlobFS); !ok {
+ return
+ }
+
+ // Make a complex glob pattern prefix that only matches dir.
+ var glob string
+ if dir != "." {
+ elem := strings.Split(dir, "/")
+ for i, e := range elem {
+ var pattern []rune
+ for j, r := range e {
+ if r == '*' || r == '?' || r == '\\' || r == '[' {
+ pattern = append(pattern, '\\', r)
+ continue
+ }
+ switch (i + j) % 5 {
+ case 0:
+ pattern = append(pattern, r)
+ case 1:
+ pattern = append(pattern, '[', r, ']')
+ case 2:
+ pattern = append(pattern, '[', r, '-', r, ']')
+ case 3:
+ pattern = append(pattern, '[', '\\', r, ']')
+ case 4:
+ pattern = append(pattern, '[', '\\', r, '-', '\\', r, ']')
+ }
+ }
+ elem[i] = string(pattern)
+ }
+ glob = strings.Join(elem, "/") + "/"
+ }
+
+ // Try to find a letter that appears in only some of the final names.
+ c := rune('a')
+ for ; c <= 'z'; c++ {
+ have, haveNot := false, false
+ for _, d := range list {
+ if strings.ContainsRune(d.Name(), c) {
+ have = true
+ } else {
+ haveNot = true
+ }
+ }
+ if have && haveNot {
+ break
+ }
+ }
+ if c > 'z' {
+ c = 'a'
+ }
+ glob += "*" + string(c) + "*"
+
+ var want []string
+ for _, d := range list {
+ if strings.ContainsRune(d.Name(), c) {
+ want = append(want, path.Join(dir, d.Name()))
+ }
+ }
+
+ names, err := t.fsys.(fs.GlobFS).Glob(glob)
+ if err != nil {
+ t.errorf("%s: Glob(%#q): %v", dir, glob, err)
+ return
+ }
+ if reflect.DeepEqual(want, names) {
+ return
+ }
+
+ if !sort.StringsAreSorted(names) {
+ t.errorf("%s: Glob(%#q): unsorted output:\n%s", dir, glob, strings.Join(names, "\n"))
+ sort.Strings(names)
+ }
+
+ var problems []string
+ for len(want) > 0 || len(names) > 0 {
+ switch {
+ case len(want) > 0 && len(names) > 0 && want[0] == names[0]:
+ want, names = want[1:], names[1:]
+ case len(want) > 0 && (len(names) == 0 || want[0] < names[0]):
+ problems = append(problems, "missing: "+want[0])
+ want = want[1:]
+ default:
+ problems = append(problems, "extra: "+names[0])
+ names = names[1:]
+ }
+ }
+ t.errorf("%s: Glob(%#q): wrong output:\n%s", dir, glob, strings.Join(problems, "\n"))
+}
+
// checkStat checks that a direct stat of path matches entry,
// which was found in the parent's directory listing.
func (t *fsTester) checkStat(path string, entry fs.DirEntry) {
--
cgit v1.3
From 1b09d430678d4a6f73b2443463d11f75851aba8a Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Fri, 16 Oct 2020 00:49:02 -0400
Subject: all: update references to symbols moved from io/ioutil to io
The old ioutil references are still valid, but update our code
to reflect best practices and get used to the new locations.
Code compiled with the bootstrap toolchain
(cmd/asm, cmd/dist, cmd/compile, debug/elf)
must remain Go 1.4-compatible and is excluded.
Also excluded vendored code.
For #41190.
Change-Id: I6d86f2bf7bc37a9d904b6cee3fe0c7af6d94d5b1
Reviewed-on: https://go-review.googlesource.com/c/go/+/263142
Trust: Russ Cox
Run-TryBot: Russ Cox
TryBot-Result: Go Bot
Reviewed-by: Emmanuel Odeke
---
src/archive/tar/reader.go | 7 +-
src/archive/tar/reader_test.go | 2 +-
src/archive/tar/tar_test.go | 8 +-
src/archive/zip/reader_test.go | 6 +-
src/archive/zip/register.go | 3 +-
src/archive/zip/writer_test.go | 4 +-
src/archive/zip/zip_test.go | 3 +-
src/bufio/bufio_test.go | 19 ++--
src/bytes/reader_test.go | 9 +-
src/cmd/fix/main.go | 3 +-
src/cmd/go/internal/clean/clean.go | 3 +-
src/cmd/go/internal/fsys/fsys_test.go | 3 +-
src/cmd/go/internal/imports/read.go | 4 +-
src/cmd/go/internal/lockedfile/lockedfile.go | 5 +-
src/cmd/go/internal/modfetch/codehost/git.go | 5 +-
src/cmd/go/internal/modfetch/codehost/git_test.go | 3 +-
src/cmd/go/internal/modfetch/codehost/shell.go | 3 +-
src/cmd/go/internal/modfetch/coderepo.go | 2 +-
src/cmd/go/internal/modfetch/fetch.go | 2 +-
src/cmd/go/internal/modfetch/proxy.go | 3 +-
src/cmd/go/internal/modfetch/sumdb.go | 4 +-
src/cmd/go/internal/web/api.go | 5 +-
src/cmd/go/proxy_test.go | 4 +-
src/cmd/go/testdata/script/test_cache_inputs.txt | 2 +-
src/cmd/gofmt/gofmt.go | 2 +-
src/cmd/pprof/pprof.go | 4 +-
src/cmd/trace/trace_test.go | 10 +-
src/cmd/trace/trace_unix_test.go | 4 +-
src/compress/bzip2/bzip2_test.go | 6 +-
src/compress/flate/deflate_test.go | 24 ++---
src/compress/flate/flate_test.go | 5 +-
src/compress/flate/inflate_test.go | 3 +-
src/compress/flate/reader_test.go | 4 +-
src/compress/flate/writer_test.go | 9 +-
src/compress/gzip/gunzip_test.go | 9 +-
src/compress/gzip/gzip_test.go | 9 +-
src/compress/lzw/reader_test.go | 4 +-
src/compress/lzw/writer_test.go | 10 +-
src/compress/zlib/writer_test.go | 4 +-
src/crypto/tls/handshake_test.go | 2 +-
src/crypto/tls/tls_test.go | 7 +-
src/crypto/x509/root_ios_gen.go | 2 +-
src/debug/gosym/pclntab_test.go | 3 +-
src/encoding/ascii85/ascii85_test.go | 7 +-
src/encoding/base32/base32_test.go | 13 ++-
src/encoding/base64/base64_test.go | 15 ++-
src/encoding/binary/binary_test.go | 3 +-
src/encoding/gob/encoder_test.go | 4 +-
src/encoding/hex/hex_test.go | 3 +-
src/encoding/json/bench_test.go | 8 +-
src/encoding/json/stream_test.go | 5 +-
src/encoding/pem/pem_test.go | 4 +-
src/flag/flag_test.go | 5 +-
src/go/internal/gccgoimporter/importer.go | 2 +-
src/go/internal/gcimporter/gcimporter.go | 3 +-
src/go/parser/interface.go | 2 +-
src/go/printer/performance_test.go | 2 +-
src/go/types/gotype.go | 4 +-
src/html/template/clone_test.go | 14 +--
src/html/template/exec_test.go | 8 +-
src/image/gif/writer_test.go | 22 ++--
src/image/jpeg/writer_test.go | 6 +-
src/image/png/writer_test.go | 17 ++--
src/internal/obscuretestdata/obscuretestdata.go | 2 +-
src/internal/profile/profile.go | 5 +-
src/io/example_test.go | 5 +-
src/io/io.go | 2 +-
src/io/multi_test.go | 11 +-
src/mime/encodedword_test.go | 3 +-
src/mime/example_test.go | 5 +-
src/mime/multipart/example_test.go | 3 +-
src/mime/multipart/multipart.go | 3 +-
src/mime/multipart/multipart_test.go | 13 ++-
src/mime/multipart/writer_test.go | 8 +-
src/mime/quotedprintable/example_test.go | 4 +-
src/mime/quotedprintable/writer_test.go | 6 +-
src/net/http/alpn_test.go | 5 +-
src/net/http/cgi/child.go | 3 +-
src/net/http/client.go | 5 +-
src/net/http/client_test.go | 25 +++--
src/net/http/clientserver_test.go | 39 ++++---
src/net/http/doc.go | 2 +-
src/net/http/example_test.go | 3 +-
src/net/http/fcgi/child.go | 5 +-
src/net/http/fcgi/fcgi_test.go | 5 +-
src/net/http/filetransport_test.go | 3 +-
src/net/http/fs_test.go | 20 ++--
src/net/http/httptest/example_test.go | 9 +-
src/net/http/httptest/httptest.go | 3 +-
src/net/http/httptest/httptest_test.go | 3 +-
src/net/http/httptest/recorder.go | 4 +-
src/net/http/httptest/recorder_test.go | 3 +-
src/net/http/httptest/server_test.go | 10 +-
src/net/http/httputil/dump.go | 9 +-
src/net/http/httputil/dump_test.go | 9 +-
src/net/http/httputil/example_test.go | 6 +-
src/net/http/httputil/reverseproxy_test.go | 49 +++++----
src/net/http/internal/chunked_test.go | 5 +-
src/net/http/main_test.go | 4 +-
src/net/http/pprof/pprof_test.go | 6 +-
src/net/http/readrequest_test.go | 3 +-
src/net/http/request.go | 11 +-
src/net/http/request_test.go | 22 ++--
src/net/http/requestwrite_test.go | 27 +++--
src/net/http/response_test.go | 5 +-
src/net/http/responsewrite_test.go | 20 ++--
src/net/http/roundtrip_js.go | 3 +-
src/net/http/serve_test.go | 119 +++++++++++-----------
src/net/http/server.go | 5 +-
src/net/http/sniff_test.go | 7 +-
src/net/http/transfer.go | 11 +-
src/net/http/transfer_test.go | 16 +--
src/net/http/transport_internal_test.go | 3 +-
src/net/http/transport_test.go | 100 +++++++++---------
src/net/mail/example_test.go | 4 +-
src/net/mail/message_test.go | 5 +-
src/net/rpc/jsonrpc/all_test.go | 5 +-
src/net/sendfile_test.go | 3 +-
src/net/splice_test.go | 3 +-
src/net/textproto/reader.go | 3 +-
src/net/timeout_test.go | 3 +-
src/net/writev_test.go | 5 +-
src/os/exec/example_test.go | 3 +-
src/os/exec/exec_test.go | 4 +-
src/os/exec/read3.go | 4 +-
src/os/timeout_test.go | 4 +-
src/runtime/crash_unix_test.go | 2 +-
src/runtime/testdata/testprogcgo/eintr.go | 3 +-
src/strings/reader_test.go | 7 +-
src/syscall/mkpost.go | 4 +-
src/syscall/syscall_unix_test.go | 2 +-
src/testing/iotest/reader.go | 9 +-
src/text/tabwriter/tabwriter_test.go | 11 +-
src/text/template/exec_test.go | 8 +-
src/time/genzabbrs.go | 3 +-
135 files changed, 535 insertions(+), 597 deletions(-)
(limited to 'src/testing')
diff --git a/src/archive/tar/reader.go b/src/archive/tar/reader.go
index 4f9135b791..1b1d5b4689 100644
--- a/src/archive/tar/reader.go
+++ b/src/archive/tar/reader.go
@@ -7,7 +7,6 @@ package tar
import (
"bytes"
"io"
- "io/ioutil"
"strconv"
"strings"
"time"
@@ -104,7 +103,7 @@ func (tr *Reader) next() (*Header, error) {
continue // This is a meta header affecting the next header
case TypeGNULongName, TypeGNULongLink:
format.mayOnlyBe(FormatGNU)
- realname, err := ioutil.ReadAll(tr)
+ realname, err := io.ReadAll(tr)
if err != nil {
return nil, err
}
@@ -294,7 +293,7 @@ func mergePAX(hdr *Header, paxHdrs map[string]string) (err error) {
// parsePAX parses PAX headers.
// If an extended header (type 'x') is invalid, ErrHeader is returned
func parsePAX(r io.Reader) (map[string]string, error) {
- buf, err := ioutil.ReadAll(r)
+ buf, err := io.ReadAll(r)
if err != nil {
return nil, err
}
@@ -850,7 +849,7 @@ func discard(r io.Reader, n int64) error {
}
}
- copySkipped, err := io.CopyN(ioutil.Discard, r, n-seekSkipped)
+ copySkipped, err := io.CopyN(io.Discard, r, n-seekSkipped)
if err == io.EOF && seekSkipped+copySkipped < n {
err = io.ErrUnexpectedEOF
}
diff --git a/src/archive/tar/reader_test.go b/src/archive/tar/reader_test.go
index f153b668de..411d1e0b99 100644
--- a/src/archive/tar/reader_test.go
+++ b/src/archive/tar/reader_test.go
@@ -865,7 +865,7 @@ func TestReadTruncation(t *testing.T) {
}
cnt++
if s2 == "manual" {
- if _, err = tr.writeTo(ioutil.Discard); err != nil {
+ if _, err = tr.writeTo(io.Discard); err != nil {
break
}
}
diff --git a/src/archive/tar/tar_test.go b/src/archive/tar/tar_test.go
index f605dae904..d4a3d42312 100644
--- a/src/archive/tar/tar_test.go
+++ b/src/archive/tar/tar_test.go
@@ -328,7 +328,7 @@ func TestRoundTrip(t *testing.T) {
if !reflect.DeepEqual(rHdr, hdr) {
t.Errorf("Header mismatch.\n got %+v\nwant %+v", rHdr, hdr)
}
- rData, err := ioutil.ReadAll(tr)
+ rData, err := io.ReadAll(tr)
if err != nil {
t.Fatalf("Read: %v", err)
}
@@ -805,9 +805,9 @@ func Benchmark(b *testing.B) {
b.Run(v.label, func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
- // Writing to ioutil.Discard because we want to
+ // Writing to io.Discard because we want to
// test purely the writer code and not bring in disk performance into this.
- tw := NewWriter(ioutil.Discard)
+ tw := NewWriter(io.Discard)
for _, file := range v.files {
if err := tw.WriteHeader(file.hdr); err != nil {
b.Errorf("unexpected WriteHeader error: %v", err)
@@ -845,7 +845,7 @@ func Benchmark(b *testing.B) {
if _, err := tr.Next(); err != nil {
b.Errorf("unexpected Next error: %v", err)
}
- if _, err := io.Copy(ioutil.Discard, tr); err != nil {
+ if _, err := io.Copy(io.Discard, tr); err != nil {
b.Errorf("unexpected Copy error : %v", err)
}
}
diff --git a/src/archive/zip/reader_test.go b/src/archive/zip/reader_test.go
index 38ff7badd0..b7a7d7a757 100644
--- a/src/archive/zip/reader_test.go
+++ b/src/archive/zip/reader_test.go
@@ -930,7 +930,7 @@ func returnBigZipBytes() (r io.ReaderAt, size int64) {
if err != nil {
panic(err)
}
- b, err = ioutil.ReadAll(f)
+ b, err = io.ReadAll(f)
if err != nil {
panic(err)
}
@@ -987,7 +987,7 @@ func TestIssue10957(t *testing.T) {
continue
}
if f.UncompressedSize64 < 1e6 {
- n, err := io.Copy(ioutil.Discard, r)
+ n, err := io.Copy(io.Discard, r)
if i == 3 && err != io.ErrUnexpectedEOF {
t.Errorf("File[3] error = %v; want io.ErrUnexpectedEOF", err)
}
@@ -1029,7 +1029,7 @@ func TestIssue11146(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- _, err = ioutil.ReadAll(r)
+ _, err = io.ReadAll(r)
if err != io.ErrUnexpectedEOF {
t.Errorf("File[0] error = %v; want io.ErrUnexpectedEOF", err)
}
diff --git a/src/archive/zip/register.go b/src/archive/zip/register.go
index 51e9c3e4d4..4389246286 100644
--- a/src/archive/zip/register.go
+++ b/src/archive/zip/register.go
@@ -8,7 +8,6 @@ import (
"compress/flate"
"errors"
"io"
- "io/ioutil"
"sync"
)
@@ -111,7 +110,7 @@ func init() {
compressors.Store(Store, Compressor(func(w io.Writer) (io.WriteCloser, error) { return &nopCloser{w}, nil }))
compressors.Store(Deflate, Compressor(func(w io.Writer) (io.WriteCloser, error) { return newFlateWriter(w), nil }))
- decompressors.Store(Store, Decompressor(ioutil.NopCloser))
+ decompressors.Store(Store, Decompressor(io.NopCloser))
decompressors.Store(Deflate, Decompressor(newFlateReader))
}
diff --git a/src/archive/zip/writer_test.go b/src/archive/zip/writer_test.go
index 282f9ec216..2c32eaf4a5 100644
--- a/src/archive/zip/writer_test.go
+++ b/src/archive/zip/writer_test.go
@@ -301,7 +301,7 @@ func TestWriterFlush(t *testing.T) {
}
func TestWriterDir(t *testing.T) {
- w := NewWriter(ioutil.Discard)
+ w := NewWriter(io.Discard)
dw, err := w.Create("dir/")
if err != nil {
t.Fatal(err)
@@ -380,7 +380,7 @@ func testReadFile(t *testing.T, f *File, wt *WriteTest) {
if err != nil {
t.Fatal("opening:", err)
}
- b, err := ioutil.ReadAll(rc)
+ b, err := io.ReadAll(rc)
if err != nil {
t.Fatal("reading:", err)
}
diff --git a/src/archive/zip/zip_test.go b/src/archive/zip/zip_test.go
index b3a7caac7f..ead9cd3aab 100644
--- a/src/archive/zip/zip_test.go
+++ b/src/archive/zip/zip_test.go
@@ -13,7 +13,6 @@ import (
"hash"
"internal/testenv"
"io"
- "io/ioutil"
"runtime"
"sort"
"strings"
@@ -620,7 +619,7 @@ func testZip64(t testing.TB, size int64) *rleBuffer {
t.Fatal("read:", err)
}
}
- gotEnd, err := ioutil.ReadAll(rc)
+ gotEnd, err := io.ReadAll(rc)
if err != nil {
t.Fatal("read end:", err)
}
diff --git a/src/bufio/bufio_test.go b/src/bufio/bufio_test.go
index cb68f3ba23..75086f1f24 100644
--- a/src/bufio/bufio_test.go
+++ b/src/bufio/bufio_test.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"strings"
"testing"
"testing/iotest"
@@ -886,7 +885,7 @@ func TestReadEmptyBuffer(t *testing.T) {
func TestLinesAfterRead(t *testing.T) {
l := NewReaderSize(bytes.NewReader([]byte("foo")), minReadBufferSize)
- _, err := ioutil.ReadAll(l)
+ _, err := io.ReadAll(l)
if err != nil {
t.Error(err)
return
@@ -1130,7 +1129,7 @@ func TestWriterReadFromCounts(t *testing.T) {
}
}
-// A writeCountingDiscard is like ioutil.Discard and counts the number of times
+// A writeCountingDiscard is like io.Discard and counts the number of times
// Write is called on it.
type writeCountingDiscard int
@@ -1300,7 +1299,7 @@ func TestReaderReset(t *testing.T) {
t.Errorf("buf = %q; want foo", buf)
}
r.Reset(strings.NewReader("bar bar"))
- all, err := ioutil.ReadAll(r)
+ all, err := io.ReadAll(r)
if err != nil {
t.Fatal(err)
}
@@ -1645,13 +1644,13 @@ func BenchmarkReaderWriteToOptimal(b *testing.B) {
buf := make([]byte, bufSize)
r := bytes.NewReader(buf)
srcReader := NewReaderSize(onlyReader{r}, 1<<10)
- if _, ok := ioutil.Discard.(io.ReaderFrom); !ok {
- b.Fatal("ioutil.Discard doesn't support ReaderFrom")
+ if _, ok := io.Discard.(io.ReaderFrom); !ok {
+ b.Fatal("io.Discard doesn't support ReaderFrom")
}
for i := 0; i < b.N; i++ {
r.Seek(0, io.SeekStart)
srcReader.Reset(onlyReader{r})
- n, err := srcReader.WriteTo(ioutil.Discard)
+ n, err := srcReader.WriteTo(io.Discard)
if err != nil {
b.Fatal(err)
}
@@ -1722,7 +1721,7 @@ func BenchmarkReaderEmpty(b *testing.B) {
str := strings.Repeat("x", 16<<10)
for i := 0; i < b.N; i++ {
br := NewReader(strings.NewReader(str))
- n, err := io.Copy(ioutil.Discard, br)
+ n, err := io.Copy(io.Discard, br)
if err != nil {
b.Fatal(err)
}
@@ -1737,7 +1736,7 @@ func BenchmarkWriterEmpty(b *testing.B) {
str := strings.Repeat("x", 1<<10)
bs := []byte(str)
for i := 0; i < b.N; i++ {
- bw := NewWriter(ioutil.Discard)
+ bw := NewWriter(io.Discard)
bw.Flush()
bw.WriteByte('a')
bw.Flush()
@@ -1752,7 +1751,7 @@ func BenchmarkWriterEmpty(b *testing.B) {
func BenchmarkWriterFlush(b *testing.B) {
b.ReportAllocs()
- bw := NewWriter(ioutil.Discard)
+ bw := NewWriter(io.Discard)
str := strings.Repeat("x", 50)
for i := 0; i < b.N; i++ {
bw.WriteString(str)
diff --git a/src/bytes/reader_test.go b/src/bytes/reader_test.go
index d799e036f0..8baac5046c 100644
--- a/src/bytes/reader_test.go
+++ b/src/bytes/reader_test.go
@@ -8,7 +8,6 @@ import (
. "bytes"
"fmt"
"io"
- "io/ioutil"
"sync"
"testing"
)
@@ -235,7 +234,7 @@ func TestReaderCopyNothing(t *testing.T) {
type justWriter struct {
io.Writer
}
- discard := justWriter{ioutil.Discard} // hide ReadFrom
+ discard := justWriter{io.Discard} // hide ReadFrom
var with, withOut nErr
with.n, with.err = io.Copy(discard, NewReader(nil))
@@ -248,7 +247,7 @@ func TestReaderCopyNothing(t *testing.T) {
// tests that Len is affected by reads, but Size is not.
func TestReaderLenSize(t *testing.T) {
r := NewReader([]byte("abc"))
- io.CopyN(ioutil.Discard, r, 1)
+ io.CopyN(io.Discard, r, 1)
if r.Len() != 2 {
t.Errorf("Len = %d; want 2", r.Len())
}
@@ -268,7 +267,7 @@ func TestReaderReset(t *testing.T) {
if err := r.UnreadRune(); err == nil {
t.Errorf("UnreadRune: expected error, got nil")
}
- buf, err := ioutil.ReadAll(r)
+ buf, err := io.ReadAll(r)
if err != nil {
t.Errorf("ReadAll: unexpected error: %v", err)
}
@@ -314,7 +313,7 @@ func TestReaderZero(t *testing.T) {
t.Errorf("UnreadRune: got nil, want error")
}
- if n, err := (&Reader{}).WriteTo(ioutil.Discard); n != 0 || err != nil {
+ if n, err := (&Reader{}).WriteTo(io.Discard); n != 0 || err != nil {
t.Errorf("WriteTo: got %d, %v; want 0, nil", n, err)
}
}
diff --git a/src/cmd/fix/main.go b/src/cmd/fix/main.go
index dfba902f48..1cea9a876a 100644
--- a/src/cmd/fix/main.go
+++ b/src/cmd/fix/main.go
@@ -13,6 +13,7 @@ import (
"go/parser"
"go/scanner"
"go/token"
+ "io"
"io/fs"
"io/ioutil"
"os"
@@ -128,7 +129,7 @@ func processFile(filename string, useStdin bool) error {
defer f.Close()
}
- src, err := ioutil.ReadAll(f)
+ src, err := io.ReadAll(f)
if err != nil {
return err
}
diff --git a/src/cmd/go/internal/clean/clean.go b/src/cmd/go/internal/clean/clean.go
index 6bfd7ae21e..095c3cc713 100644
--- a/src/cmd/go/internal/clean/clean.go
+++ b/src/cmd/go/internal/clean/clean.go
@@ -8,6 +8,7 @@ package clean
import (
"context"
"fmt"
+ "io"
"io/ioutil"
"os"
"path/filepath"
@@ -172,7 +173,7 @@ func runClean(ctx context.Context, cmd *base.Command, args []string) {
f, err := lockedfile.Edit(filepath.Join(dir, "testexpire.txt"))
if err == nil {
now := time.Now().UnixNano()
- buf, _ := ioutil.ReadAll(f)
+ buf, _ := io.ReadAll(f)
prev, _ := strconv.ParseInt(strings.TrimSpace(string(buf)), 10, 64)
if now > prev {
if err = f.Truncate(0); err == nil {
diff --git a/src/cmd/go/internal/fsys/fsys_test.go b/src/cmd/go/internal/fsys/fsys_test.go
index ba9f05d00b..28c3f08cb9 100644
--- a/src/cmd/go/internal/fsys/fsys_test.go
+++ b/src/cmd/go/internal/fsys/fsys_test.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"internal/testenv"
+ "io"
"io/fs"
"io/ioutil"
"os"
@@ -418,7 +419,7 @@ this can exist because the parent directory is deleted
t.Errorf("Open(%q): got error %v, want nil", tc.path, err)
continue
}
- contents, err := ioutil.ReadAll(f)
+ contents, err := io.ReadAll(f)
if err != nil {
t.Errorf("unexpected error reading contents of file: %v", err)
}
diff --git a/src/cmd/go/internal/imports/read.go b/src/cmd/go/internal/imports/read.go
index 58c2abdc29..5e270781d7 100644
--- a/src/cmd/go/internal/imports/read.go
+++ b/src/cmd/go/internal/imports/read.go
@@ -198,7 +198,7 @@ func (r *importReader) readImport(imports *[]string) {
r.readString(imports)
}
-// ReadComments is like ioutil.ReadAll, except that it only reads the leading
+// ReadComments is like io.ReadAll, except that it only reads the leading
// block of comments in the file.
func ReadComments(f io.Reader) ([]byte, error) {
r := &importReader{b: bufio.NewReader(f)}
@@ -210,7 +210,7 @@ func ReadComments(f io.Reader) ([]byte, error) {
return r.buf, r.err
}
-// ReadImports is like ioutil.ReadAll, except that it expects a Go file as input
+// ReadImports is like io.ReadAll, except that it expects a Go file as input
// and stops reading the input once the imports have completed.
func ReadImports(f io.Reader, reportSyntaxError bool, imports *[]string) ([]byte, error) {
r := &importReader{b: bufio.NewReader(f)}
diff --git a/src/cmd/go/internal/lockedfile/lockedfile.go b/src/cmd/go/internal/lockedfile/lockedfile.go
index 503024da4b..82e1a89675 100644
--- a/src/cmd/go/internal/lockedfile/lockedfile.go
+++ b/src/cmd/go/internal/lockedfile/lockedfile.go
@@ -10,7 +10,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"os"
"runtime"
)
@@ -104,7 +103,7 @@ func Read(name string) ([]byte, error) {
}
defer f.Close()
- return ioutil.ReadAll(f)
+ return io.ReadAll(f)
}
// Write opens the named file (creating it with the given permissions if needed),
@@ -136,7 +135,7 @@ func Transform(name string, t func([]byte) ([]byte, error)) (err error) {
}
defer f.Close()
- old, err := ioutil.ReadAll(f)
+ old, err := io.ReadAll(f)
if err != nil {
return err
}
diff --git a/src/cmd/go/internal/modfetch/codehost/git.go b/src/cmd/go/internal/modfetch/codehost/git.go
index 58b4b2f2d3..8abc039e7f 100644
--- a/src/cmd/go/internal/modfetch/codehost/git.go
+++ b/src/cmd/go/internal/modfetch/codehost/git.go
@@ -10,7 +10,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"net/url"
"os"
"os/exec"
@@ -832,7 +831,7 @@ func (r *gitRepo) ReadZip(rev, subdir string, maxSize int64) (zip io.ReadCloser,
return nil, err
}
- return ioutil.NopCloser(bytes.NewReader(archive)), nil
+ return io.NopCloser(bytes.NewReader(archive)), nil
}
// ensureGitAttributes makes sure export-subst and export-ignore features are
@@ -863,7 +862,7 @@ func ensureGitAttributes(repoDir string) (err error) {
}
}()
- b, err := ioutil.ReadAll(f)
+ b, err := io.ReadAll(f)
if err != nil {
return err
}
diff --git a/src/cmd/go/internal/modfetch/codehost/git_test.go b/src/cmd/go/internal/modfetch/codehost/git_test.go
index 16908b3e84..981e3fe91f 100644
--- a/src/cmd/go/internal/modfetch/codehost/git_test.go
+++ b/src/cmd/go/internal/modfetch/codehost/git_test.go
@@ -10,6 +10,7 @@ import (
"flag"
"fmt"
"internal/testenv"
+ "io"
"io/fs"
"io/ioutil"
"log"
@@ -433,7 +434,7 @@ func TestReadZip(t *testing.T) {
if tt.err != "" {
t.Fatalf("ReadZip: no error, wanted %v", tt.err)
}
- zipdata, err := ioutil.ReadAll(rc)
+ zipdata, err := io.ReadAll(rc)
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/modfetch/codehost/shell.go b/src/cmd/go/internal/modfetch/codehost/shell.go
index 2762c55720..b9525adf5e 100644
--- a/src/cmd/go/internal/modfetch/codehost/shell.go
+++ b/src/cmd/go/internal/modfetch/codehost/shell.go
@@ -14,6 +14,7 @@ import (
"bytes"
"flag"
"fmt"
+ "io"
"io/ioutil"
"log"
"os"
@@ -115,7 +116,7 @@ func main() {
fmt.Fprintf(os.Stderr, "?%s\n", err)
continue
}
- data, err := ioutil.ReadAll(rc)
+ data, err := io.ReadAll(rc)
rc.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "?%s\n", err)
diff --git a/src/cmd/go/internal/modfetch/coderepo.go b/src/cmd/go/internal/modfetch/coderepo.go
index 7f44e18a70..b6bcf83f1a 100644
--- a/src/cmd/go/internal/modfetch/coderepo.go
+++ b/src/cmd/go/internal/modfetch/coderepo.go
@@ -1052,7 +1052,7 @@ type dataFile struct {
func (f dataFile) Path() string { return f.name }
func (f dataFile) Lstat() (fs.FileInfo, error) { return dataFileInfo{f}, nil }
func (f dataFile) Open() (io.ReadCloser, error) {
- return ioutil.NopCloser(bytes.NewReader(f.data)), nil
+ return io.NopCloser(bytes.NewReader(f.data)), nil
}
type dataFileInfo struct {
diff --git a/src/cmd/go/internal/modfetch/fetch.go b/src/cmd/go/internal/modfetch/fetch.go
index 6ff455e89c..40196c4e9a 100644
--- a/src/cmd/go/internal/modfetch/fetch.go
+++ b/src/cmd/go/internal/modfetch/fetch.go
@@ -461,7 +461,7 @@ func checkMod(mod module.Version) {
// goModSum returns the checksum for the go.mod contents.
func goModSum(data []byte) (string, error) {
return dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) {
- return ioutil.NopCloser(bytes.NewReader(data)), nil
+ return io.NopCloser(bytes.NewReader(data)), nil
})
}
diff --git a/src/cmd/go/internal/modfetch/proxy.go b/src/cmd/go/internal/modfetch/proxy.go
index 819990b403..d75b4da521 100644
--- a/src/cmd/go/internal/modfetch/proxy.go
+++ b/src/cmd/go/internal/modfetch/proxy.go
@@ -10,7 +10,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"net/url"
"path"
pathpkg "path"
@@ -305,7 +304,7 @@ func (p *proxyRepo) getBytes(path string) ([]byte, error) {
return nil, err
}
defer body.Close()
- return ioutil.ReadAll(body)
+ return io.ReadAll(body)
}
func (p *proxyRepo) getBody(path string) (io.ReadCloser, error) {
diff --git a/src/cmd/go/internal/modfetch/sumdb.go b/src/cmd/go/internal/modfetch/sumdb.go
index 5108961a33..4fbc54d15c 100644
--- a/src/cmd/go/internal/modfetch/sumdb.go
+++ b/src/cmd/go/internal/modfetch/sumdb.go
@@ -12,8 +12,8 @@ import (
"bytes"
"errors"
"fmt"
+ "io"
"io/fs"
- "io/ioutil"
"net/url"
"os"
"path/filepath"
@@ -228,7 +228,7 @@ func (*dbClient) WriteConfig(file string, old, new []byte) error {
return err
}
defer f.Close()
- data, err := ioutil.ReadAll(f)
+ data, err := io.ReadAll(f)
if err != nil {
return err
}
diff --git a/src/cmd/go/internal/web/api.go b/src/cmd/go/internal/web/api.go
index f7d3ed60f6..9053b16b62 100644
--- a/src/cmd/go/internal/web/api.go
+++ b/src/cmd/go/internal/web/api.go
@@ -14,7 +14,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"net/url"
"strings"
"unicode"
@@ -87,7 +86,7 @@ func GetBytes(u *url.URL) ([]byte, error) {
if err := resp.Err(); err != nil {
return nil, err
}
- b, err := ioutil.ReadAll(resp.Body)
+ b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading %s: %v", u.Redacted(), err)
}
@@ -130,7 +129,7 @@ func (r *Response) formatErrorDetail() string {
}
// Ensure that r.errorDetail has been populated.
- _, _ = io.Copy(ioutil.Discard, r.Body)
+ _, _ = io.Copy(io.Discard, r.Body)
s := r.errorDetail.buf.String()
if !utf8.ValidString(s) {
diff --git a/src/cmd/go/proxy_test.go b/src/cmd/go/proxy_test.go
index 8b0dbb74b2..3ed42face2 100644
--- a/src/cmd/go/proxy_test.go
+++ b/src/cmd/go/proxy_test.go
@@ -471,13 +471,13 @@ func proxyGoSum(path, vers string) ([]byte, error) {
}
h1, err := dirhash.Hash1(names, func(name string) (io.ReadCloser, error) {
data := files[name]
- return ioutil.NopCloser(bytes.NewReader(data)), nil
+ return io.NopCloser(bytes.NewReader(data)), nil
})
if err != nil {
return nil, err
}
h1mod, err := dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) {
- return ioutil.NopCloser(bytes.NewReader(gomod)), nil
+ return io.NopCloser(bytes.NewReader(gomod)), nil
})
if err != nil {
return nil, err
diff --git a/src/cmd/go/testdata/script/test_cache_inputs.txt b/src/cmd/go/testdata/script/test_cache_inputs.txt
index 57602e91dc..97ae4af51f 100644
--- a/src/cmd/go/testdata/script/test_cache_inputs.txt
+++ b/src/cmd/go/testdata/script/test_cache_inputs.txt
@@ -159,7 +159,7 @@ func TestOddFileContent(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- data, err := ioutil.ReadAll(f)
+ data, err := io.ReadAll(f)
f.Close()
if err != nil {
t.Fatal(err)
diff --git a/src/cmd/gofmt/gofmt.go b/src/cmd/gofmt/gofmt.go
index 48b6ad6f53..dba2411eed 100644
--- a/src/cmd/gofmt/gofmt.go
+++ b/src/cmd/gofmt/gofmt.go
@@ -97,7 +97,7 @@ func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error
perm = fi.Mode().Perm()
}
- src, err := ioutil.ReadAll(in)
+ src, err := io.ReadAll(in)
if err != nil {
return err
}
diff --git a/src/cmd/pprof/pprof.go b/src/cmd/pprof/pprof.go
index c1ddbe372f..11f91cbedb 100644
--- a/src/cmd/pprof/pprof.go
+++ b/src/cmd/pprof/pprof.go
@@ -13,7 +13,7 @@ import (
"crypto/tls"
"debug/dwarf"
"fmt"
- "io/ioutil"
+ "io"
"net/http"
"net/url"
"os"
@@ -94,7 +94,7 @@ func getProfile(source string, timeout time.Duration) (*profile.Profile, error)
func statusCodeError(resp *http.Response) error {
if resp.Header.Get("X-Go-Pprof") != "" && strings.Contains(resp.Header.Get("Content-Type"), "text/plain") {
// error is from pprof endpoint
- if body, err := ioutil.ReadAll(resp.Body); err == nil {
+ if body, err := io.ReadAll(resp.Body); err == nil {
return fmt.Errorf("server response: %s - %s", resp.Status, body)
}
}
diff --git a/src/cmd/trace/trace_test.go b/src/cmd/trace/trace_test.go
index dd12e8cd20..ea0cc6f880 100644
--- a/src/cmd/trace/trace_test.go
+++ b/src/cmd/trace/trace_test.go
@@ -10,7 +10,7 @@ import (
"cmd/internal/traceviewer"
"context"
"internal/trace"
- "io/ioutil"
+ "io"
rtrace "runtime/trace"
"strings"
"sync"
@@ -78,7 +78,7 @@ func TestGoroutineCount(t *testing.T) {
// Use the default viewerDataTraceConsumer but replace
// consumeViewerEvent to intercept the ViewerEvents for testing.
- c := viewerDataTraceConsumer(ioutil.Discard, 0, 1<<63-1)
+ c := viewerDataTraceConsumer(io.Discard, 0, 1<<63-1)
c.consumeViewerEvent = func(ev *traceviewer.Event, _ bool) {
if ev.Name == "Goroutines" {
cnt := ev.Arg.(*goroutineCountersArg)
@@ -131,7 +131,7 @@ func TestGoroutineFilter(t *testing.T) {
gs: map[uint64]bool{10: true},
}
- c := viewerDataTraceConsumer(ioutil.Discard, 0, 1<<63-1)
+ c := viewerDataTraceConsumer(io.Discard, 0, 1<<63-1)
if err := generateTrace(params, c); err != nil {
t.Fatalf("generateTrace failed: %v", err)
}
@@ -163,7 +163,7 @@ func TestPreemptedMarkAssist(t *testing.T) {
endTime: int64(1<<63 - 1),
}
- c := viewerDataTraceConsumer(ioutil.Discard, 0, 1<<63-1)
+ c := viewerDataTraceConsumer(io.Discard, 0, 1<<63-1)
marks := 0
c.consumeViewerEvent = func(ev *traceviewer.Event, _ bool) {
@@ -214,7 +214,7 @@ func TestFoo(t *testing.T) {
tasks: []*taskDesc{task},
}
- c := viewerDataTraceConsumer(ioutil.Discard, 0, 1<<63-1)
+ c := viewerDataTraceConsumer(io.Discard, 0, 1<<63-1)
var logBeforeTaskEnd, logAfterTaskEnd bool
c.consumeViewerEvent = func(ev *traceviewer.Event, _ bool) {
diff --git a/src/cmd/trace/trace_unix_test.go b/src/cmd/trace/trace_unix_test.go
index 645978e0f8..c569b40bb2 100644
--- a/src/cmd/trace/trace_unix_test.go
+++ b/src/cmd/trace/trace_unix_test.go
@@ -10,7 +10,7 @@ import (
"bytes"
"cmd/internal/traceviewer"
traceparser "internal/trace"
- "io/ioutil"
+ "io"
"runtime"
"runtime/trace"
"sync"
@@ -83,7 +83,7 @@ func TestGoroutineInSyscall(t *testing.T) {
// Check only one thread for the pipe read goroutine is
// considered in-syscall.
- c := viewerDataTraceConsumer(ioutil.Discard, 0, 1<<63-1)
+ c := viewerDataTraceConsumer(io.Discard, 0, 1<<63-1)
c.consumeViewerEvent = func(ev *traceviewer.Event, _ bool) {
if ev.Name == "Threads" {
arg := ev.Arg.(*threadCountersArg)
diff --git a/src/compress/bzip2/bzip2_test.go b/src/compress/bzip2/bzip2_test.go
index c432bb5226..98477791b3 100644
--- a/src/compress/bzip2/bzip2_test.go
+++ b/src/compress/bzip2/bzip2_test.go
@@ -133,7 +133,7 @@ func TestReader(t *testing.T) {
for i, v := range vectors {
rd := NewReader(bytes.NewReader(v.input))
- buf, err := ioutil.ReadAll(rd)
+ buf, err := io.ReadAll(rd)
if fail := bool(err != nil); fail != v.fail {
if fail {
@@ -220,7 +220,7 @@ var (
func benchmarkDecode(b *testing.B, compressed []byte) {
// Determine the uncompressed size of testfile.
- uncompressedSize, err := io.Copy(ioutil.Discard, NewReader(bytes.NewReader(compressed)))
+ uncompressedSize, err := io.Copy(io.Discard, NewReader(bytes.NewReader(compressed)))
if err != nil {
b.Fatal(err)
}
@@ -231,7 +231,7 @@ func benchmarkDecode(b *testing.B, compressed []byte) {
for i := 0; i < b.N; i++ {
r := bytes.NewReader(compressed)
- io.Copy(ioutil.Discard, NewReader(r))
+ io.Copy(io.Discard, NewReader(r))
}
}
diff --git a/src/compress/flate/deflate_test.go b/src/compress/flate/deflate_test.go
index b19cbec5a9..6fc5abf4d5 100644
--- a/src/compress/flate/deflate_test.go
+++ b/src/compress/flate/deflate_test.go
@@ -157,7 +157,7 @@ func TestVeryLongSparseChunk(t *testing.T) {
if testing.Short() {
t.Skip("skipping sparse chunk during short test")
}
- w, err := NewWriter(ioutil.Discard, 1)
+ w, err := NewWriter(io.Discard, 1)
if err != nil {
t.Errorf("NewWriter: %v", err)
return
@@ -294,7 +294,7 @@ func testSync(t *testing.T, level int, input []byte, name string) {
// stream should work for ordinary reader too
r = NewReader(buf1)
- out, err = ioutil.ReadAll(r)
+ out, err = io.ReadAll(r)
if err != nil {
t.Errorf("testSync: read: %s", err)
return
@@ -322,7 +322,7 @@ func testToFromWithLevelAndLimit(t *testing.T, level int, input []byte, name str
t.Logf("level: %d, size:%.2f%%, %d b\n", level, float64(buffer.Len()*100)/float64(limit), buffer.Len())
}
r := NewReader(&buffer)
- out, err := ioutil.ReadAll(r)
+ out, err := io.ReadAll(r)
if err != nil {
t.Errorf("read: %s", err)
return
@@ -415,7 +415,7 @@ func TestReaderDict(t *testing.T) {
w.Close()
r := NewReaderDict(&b, []byte(dict))
- data, err := ioutil.ReadAll(r)
+ data, err := io.ReadAll(r)
if err != nil {
t.Fatal(err)
}
@@ -456,7 +456,7 @@ func TestRegression2508(t *testing.T) {
t.Logf("test disabled with -short")
return
}
- w, err := NewWriter(ioutil.Discard, 1)
+ w, err := NewWriter(io.Discard, 1)
if err != nil {
t.Fatalf("NewWriter: %v", err)
}
@@ -475,7 +475,7 @@ func TestWriterReset(t *testing.T) {
if testing.Short() && level > 1 {
break
}
- w, err := NewWriter(ioutil.Discard, level)
+ w, err := NewWriter(io.Discard, level)
if err != nil {
t.Fatalf("NewWriter: %v", err)
}
@@ -487,9 +487,9 @@ func TestWriterReset(t *testing.T) {
for i := 0; i < n; i++ {
w.Write(buf)
}
- w.Reset(ioutil.Discard)
+ w.Reset(io.Discard)
- wref, err := NewWriter(ioutil.Discard, level)
+ wref, err := NewWriter(io.Discard, level)
if err != nil {
t.Fatalf("NewWriter: %v", err)
}
@@ -654,7 +654,7 @@ func TestBestSpeed(t *testing.T) {
}
r := NewReader(buf)
- got, err := ioutil.ReadAll(r)
+ got, err := io.ReadAll(r)
if err != nil {
t.Errorf("i=%d, firstN=%d, flush=%t: ReadAll: %v", i, firstN, flush, err)
continue
@@ -881,7 +881,7 @@ func TestBestSpeedMaxMatchOffset(t *testing.T) {
}
r := NewReader(buf)
- dst, err := ioutil.ReadAll(r)
+ dst, err := io.ReadAll(r)
r.Close()
if err != nil {
report("ReadAll: ", err)
@@ -968,7 +968,7 @@ func TestMaxStackSize(t *testing.T) {
wg.Add(1)
go func(level int) {
defer wg.Done()
- zw, err := NewWriter(ioutil.Discard, level)
+ zw, err := NewWriter(io.Discard, level)
if err != nil {
t.Errorf("level %d, NewWriter() = %v, want nil", level, err)
}
@@ -978,7 +978,7 @@ func TestMaxStackSize(t *testing.T) {
if err := zw.Close(); err != nil {
t.Errorf("level %d, Close() = %v, want nil", level, err)
}
- zw.Reset(ioutil.Discard)
+ zw.Reset(io.Discard)
}(level)
}
}
diff --git a/src/compress/flate/flate_test.go b/src/compress/flate/flate_test.go
index 1e45077bd5..23f4c47b03 100644
--- a/src/compress/flate/flate_test.go
+++ b/src/compress/flate/flate_test.go
@@ -12,7 +12,6 @@ import (
"bytes"
"encoding/hex"
"io"
- "io/ioutil"
"strings"
"testing"
)
@@ -243,7 +242,7 @@ func TestStreams(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- data, err = ioutil.ReadAll(NewReader(bytes.NewReader(data)))
+ data, err = io.ReadAll(NewReader(bytes.NewReader(data)))
if tc.want == "fail" {
if err == nil {
t.Errorf("#%d (%s): got nil error, want non-nil", i, tc.desc)
@@ -266,7 +265,7 @@ func TestTruncatedStreams(t *testing.T) {
for i := 0; i < len(data)-1; i++ {
r := NewReader(strings.NewReader(data[:i]))
- _, err := io.Copy(ioutil.Discard, r)
+ _, err := io.Copy(io.Discard, r)
if err != io.ErrUnexpectedEOF {
t.Errorf("io.Copy(%d) on truncated stream: got %v, want %v", i, err, io.ErrUnexpectedEOF)
}
diff --git a/src/compress/flate/inflate_test.go b/src/compress/flate/inflate_test.go
index 951decd775..9575be1cf2 100644
--- a/src/compress/flate/inflate_test.go
+++ b/src/compress/flate/inflate_test.go
@@ -7,7 +7,6 @@ package flate
import (
"bytes"
"io"
- "io/ioutil"
"strings"
"testing"
)
@@ -57,7 +56,7 @@ func TestReaderTruncated(t *testing.T) {
for i, v := range vectors {
r := strings.NewReader(v.input)
zr := NewReader(r)
- b, err := ioutil.ReadAll(zr)
+ b, err := io.ReadAll(zr)
if err != io.ErrUnexpectedEOF {
t.Errorf("test %d, error mismatch: got %v, want io.ErrUnexpectedEOF", i, err)
}
diff --git a/src/compress/flate/reader_test.go b/src/compress/flate/reader_test.go
index 9d2943a540..eb32c89184 100644
--- a/src/compress/flate/reader_test.go
+++ b/src/compress/flate/reader_test.go
@@ -16,7 +16,7 @@ import (
func TestNlitOutOfRange(t *testing.T) {
// Trying to decode this bogus flate data, which has a Huffman table
// with nlit=288, should not panic.
- io.Copy(ioutil.Discard, NewReader(strings.NewReader(
+ io.Copy(io.Discard, NewReader(strings.NewReader(
"\xfc\xfe\x36\xe7\x5e\x1c\xef\xb3\x55\x58\x77\xb6\x56\xb5\x43\xf4"+
"\x6f\xf2\xd2\xe6\x3d\x99\xa0\x85\x8c\x48\xeb\xf8\xda\x83\x04\x2a"+
"\x75\xc4\xf8\x0f\x12\x11\xb9\xb4\x4b\x09\xa0\xbe\x8b\x91\x4c")))
@@ -54,7 +54,7 @@ func BenchmarkDecode(b *testing.B) {
runtime.GC()
b.StartTimer()
for i := 0; i < b.N; i++ {
- io.Copy(ioutil.Discard, NewReader(bytes.NewReader(buf1)))
+ io.Copy(io.Discard, NewReader(bytes.NewReader(buf1)))
}
})
}
diff --git a/src/compress/flate/writer_test.go b/src/compress/flate/writer_test.go
index 881cb71cc3..c413735cd2 100644
--- a/src/compress/flate/writer_test.go
+++ b/src/compress/flate/writer_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"math/rand"
"runtime"
"testing"
@@ -27,14 +26,14 @@ func BenchmarkEncode(b *testing.B) {
copy(buf1[i:], buf0)
}
buf0 = nil
- w, err := NewWriter(ioutil.Discard, level)
+ w, err := NewWriter(io.Discard, level)
if err != nil {
b.Fatal(err)
}
runtime.GC()
b.StartTimer()
for i := 0; i < b.N; i++ {
- w.Reset(ioutil.Discard)
+ w.Reset(io.Discard)
w.Write(buf1)
w.Close()
}
@@ -96,7 +95,7 @@ func TestWriteError(t *testing.T) {
t.Fatal("Level", l, "Expected an error on close")
}
- w.Reset(ioutil.Discard)
+ w.Reset(io.Discard)
n2, err = w.Write([]byte{1, 2, 3, 4, 5, 6})
if err != nil {
t.Fatal("Level", l, "Got unexpected error after reset:", err)
@@ -206,7 +205,7 @@ func TestDeflateFast_Reset(t *testing.T) {
w.Close()
for ; offset <= 256; offset *= 2 {
- w, err := NewWriter(ioutil.Discard, level)
+ w, err := NewWriter(io.Discard, level)
if err != nil {
t.Fatalf("NewWriter: level %d: %v", level, err)
}
diff --git a/src/compress/gzip/gunzip_test.go b/src/compress/gzip/gunzip_test.go
index 1b01404169..17c23e8a9b 100644
--- a/src/compress/gzip/gunzip_test.go
+++ b/src/compress/gzip/gunzip_test.go
@@ -9,7 +9,6 @@ import (
"compress/flate"
"encoding/base64"
"io"
- "io/ioutil"
"os"
"strings"
"testing"
@@ -430,7 +429,7 @@ func TestIssue6550(t *testing.T) {
defer gzip.Close()
done := make(chan bool, 1)
go func() {
- _, err := io.Copy(ioutil.Discard, gzip)
+ _, err := io.Copy(io.Discard, gzip)
if err == nil {
t.Errorf("Copy succeeded")
} else {
@@ -467,7 +466,7 @@ Found:
const hello = "hello world\n"
r.Multistream(false)
- data, err := ioutil.ReadAll(&r)
+ data, err := io.ReadAll(&r)
if string(data) != hello || err != nil {
t.Fatalf("first stream = %q, %v, want %q, %v", string(data), err, hello, nil)
}
@@ -476,7 +475,7 @@ Found:
t.Fatalf("second reset: %v", err)
}
r.Multistream(false)
- data, err = ioutil.ReadAll(&r)
+ data, err = io.ReadAll(&r)
if string(data) != hello || err != nil {
t.Fatalf("second stream = %q, %v, want %q, %v", string(data), err, hello, nil)
}
@@ -507,7 +506,7 @@ func TestTruncatedStreams(t *testing.T) {
}
continue
}
- _, err = io.Copy(ioutil.Discard, r)
+ _, err = io.Copy(io.Discard, r)
if ferr, ok := err.(*flate.ReadError); ok {
err = ferr.Err
}
diff --git a/src/compress/gzip/gzip_test.go b/src/compress/gzip/gzip_test.go
index f18c5cb454..12c8e18207 100644
--- a/src/compress/gzip/gzip_test.go
+++ b/src/compress/gzip/gzip_test.go
@@ -8,7 +8,6 @@ import (
"bufio"
"bytes"
"io"
- "io/ioutil"
"reflect"
"testing"
"time"
@@ -29,7 +28,7 @@ func TestEmpty(t *testing.T) {
if want := (Header{OS: 255}); !reflect.DeepEqual(r.Header, want) {
t.Errorf("Header mismatch:\ngot %#v\nwant %#v", r.Header, want)
}
- b, err := ioutil.ReadAll(r)
+ b, err := io.ReadAll(r)
if err != nil {
t.Fatalf("ReadAll: %v", err)
}
@@ -62,7 +61,7 @@ func TestRoundTrip(t *testing.T) {
if err != nil {
t.Fatalf("NewReader: %v", err)
}
- b, err := ioutil.ReadAll(r)
+ b, err := io.ReadAll(r)
if err != nil {
t.Fatalf("ReadAll: %v", err)
}
@@ -147,7 +146,7 @@ func TestLatin1RoundTrip(t *testing.T) {
t.Errorf("NewReader: %v", err)
continue
}
- _, err = ioutil.ReadAll(r)
+ _, err = io.ReadAll(r)
if err != nil {
t.Errorf("ReadAll: %v", err)
continue
@@ -217,7 +216,7 @@ func TestConcat(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- data, err := ioutil.ReadAll(r)
+ data, err := io.ReadAll(r)
if string(data) != "hello world\n" || err != nil {
t.Fatalf("ReadAll = %q, %v, want %q, nil", data, err, "hello world")
}
diff --git a/src/compress/lzw/reader_test.go b/src/compress/lzw/reader_test.go
index 98bbfbb763..6d91dd806f 100644
--- a/src/compress/lzw/reader_test.go
+++ b/src/compress/lzw/reader_test.go
@@ -206,7 +206,7 @@ func TestNoLongerSavingPriorExpansions(t *testing.T) {
in = append(in, 0x80, 0xff, 0x0f, 0x08)
r := NewReader(bytes.NewReader(in), LSB, 8)
- nDecoded, err := io.Copy(ioutil.Discard, r)
+ nDecoded, err := io.Copy(io.Discard, r)
if err != nil {
t.Fatalf("Copy: %v", err)
}
@@ -246,7 +246,7 @@ func BenchmarkDecoder(b *testing.B) {
runtime.GC()
b.StartTimer()
for i := 0; i < b.N; i++ {
- io.Copy(ioutil.Discard, NewReader(bytes.NewReader(buf1), LSB, 8))
+ io.Copy(io.Discard, NewReader(bytes.NewReader(buf1), LSB, 8))
}
})
}
diff --git a/src/compress/lzw/writer_test.go b/src/compress/lzw/writer_test.go
index 4979f8b352..33a28bdd3a 100644
--- a/src/compress/lzw/writer_test.go
+++ b/src/compress/lzw/writer_test.go
@@ -67,8 +67,8 @@ func testFile(t *testing.T, fn string, order Order, litWidth int) {
defer lzwr.Close()
// Compare the two.
- b0, err0 := ioutil.ReadAll(golden)
- b1, err1 := ioutil.ReadAll(lzwr)
+ b0, err0 := io.ReadAll(golden)
+ b1, err1 := io.ReadAll(lzwr)
if err0 != nil {
t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err0)
return
@@ -107,7 +107,7 @@ func TestWriter(t *testing.T) {
}
func TestWriterReturnValues(t *testing.T) {
- w := NewWriter(ioutil.Discard, LSB, 8)
+ w := NewWriter(io.Discard, LSB, 8)
n, err := w.Write([]byte("asdf"))
if n != 4 || err != nil {
t.Errorf("got %d, %v, want 4, nil", n, err)
@@ -115,7 +115,7 @@ func TestWriterReturnValues(t *testing.T) {
}
func TestSmallLitWidth(t *testing.T) {
- w := NewWriter(ioutil.Discard, LSB, 2)
+ w := NewWriter(io.Discard, LSB, 2)
if _, err := w.Write([]byte{0x03}); err != nil {
t.Fatalf("write a byte < 1<<2: %v", err)
}
@@ -148,7 +148,7 @@ func BenchmarkEncoder(b *testing.B) {
b.Run(fmt.Sprint("1e", e), func(b *testing.B) {
b.SetBytes(int64(n))
for i := 0; i < b.N; i++ {
- w := NewWriter(ioutil.Discard, LSB, 8)
+ w := NewWriter(io.Discard, LSB, 8)
w.Write(buf1)
w.Close()
}
diff --git a/src/compress/zlib/writer_test.go b/src/compress/zlib/writer_test.go
index d501974078..c518729146 100644
--- a/src/compress/zlib/writer_test.go
+++ b/src/compress/zlib/writer_test.go
@@ -34,7 +34,7 @@ func testFileLevelDict(t *testing.T, fn string, level int, d string) {
return
}
defer golden.Close()
- b0, err0 := ioutil.ReadAll(golden)
+ b0, err0 := io.ReadAll(golden)
if err0 != nil {
t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err0)
return
@@ -74,7 +74,7 @@ func testLevelDict(t *testing.T, fn string, b0 []byte, level int, d string) {
defer zlibr.Close()
// Compare the decompressed data.
- b1, err1 := ioutil.ReadAll(zlibr)
+ b1, err1 := io.ReadAll(zlibr)
if err1 != nil {
t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err1)
return
diff --git a/src/crypto/tls/handshake_test.go b/src/crypto/tls/handshake_test.go
index f55cd16ca8..224edcd5c7 100644
--- a/src/crypto/tls/handshake_test.go
+++ b/src/crypto/tls/handshake_test.go
@@ -403,7 +403,7 @@ func testHandshake(t *testing.T, clientConfig, serverConfig *Config) (serverStat
}
defer cli.Close()
clientState = cli.ConnectionState()
- buf, err := ioutil.ReadAll(cli)
+ buf, err := io.ReadAll(cli)
if err != nil {
t.Errorf("failed to call cli.Read: %v", err)
}
diff --git a/src/crypto/tls/tls_test.go b/src/crypto/tls/tls_test.go
index 4ab8a430ba..9995538871 100644
--- a/src/crypto/tls/tls_test.go
+++ b/src/crypto/tls/tls_test.go
@@ -14,7 +14,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"math"
"net"
"os"
@@ -594,7 +593,7 @@ func TestConnCloseWrite(t *testing.T) {
}
defer srv.Close()
- data, err := ioutil.ReadAll(srv)
+ data, err := io.ReadAll(srv)
if err != nil {
return err
}
@@ -635,7 +634,7 @@ func TestConnCloseWrite(t *testing.T) {
return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
}
- data, err := ioutil.ReadAll(conn)
+ data, err := io.ReadAll(conn)
if err != nil {
return err
}
@@ -698,7 +697,7 @@ func TestWarningAlertFlood(t *testing.T) {
}
defer srv.Close()
- _, err = ioutil.ReadAll(srv)
+ _, err = io.ReadAll(srv)
if err == nil {
return errors.New("unexpected lack of error from server")
}
diff --git a/src/crypto/x509/root_ios_gen.go b/src/crypto/x509/root_ios_gen.go
index 34dd5d5b22..0641c073ea 100644
--- a/src/crypto/x509/root_ios_gen.go
+++ b/src/crypto/x509/root_ios_gen.go
@@ -81,7 +81,7 @@ func main() {
continue
}
- der, err := ioutil.ReadAll(tr)
+ der, err := io.ReadAll(tr)
if err != nil {
log.Fatal(err)
}
diff --git a/src/debug/gosym/pclntab_test.go b/src/debug/gosym/pclntab_test.go
index 33772c7813..f93a5bf5e5 100644
--- a/src/debug/gosym/pclntab_test.go
+++ b/src/debug/gosym/pclntab_test.go
@@ -9,6 +9,7 @@ import (
"compress/gzip"
"debug/elf"
"internal/testenv"
+ "io"
"io/ioutil"
"os"
"os/exec"
@@ -287,7 +288,7 @@ func Test115PclnParsing(t *testing.T) {
t.Fatal(err)
}
var dat []byte
- dat, err = ioutil.ReadAll(gzReader)
+ dat, err = io.ReadAll(gzReader)
if err != nil {
t.Fatal(err)
}
diff --git a/src/encoding/ascii85/ascii85_test.go b/src/encoding/ascii85/ascii85_test.go
index 1a3a87a596..c637103942 100644
--- a/src/encoding/ascii85/ascii85_test.go
+++ b/src/encoding/ascii85/ascii85_test.go
@@ -7,7 +7,6 @@ package ascii85
import (
"bytes"
"io"
- "io/ioutil"
"strings"
"testing"
)
@@ -118,7 +117,7 @@ func TestDecode(t *testing.T) {
func TestDecoder(t *testing.T) {
for _, p := range pairs {
decoder := NewDecoder(strings.NewReader(p.encoded))
- dbuf, err := ioutil.ReadAll(decoder)
+ dbuf, err := io.ReadAll(decoder)
if err != nil {
t.Fatal("Read failed", err)
}
@@ -187,7 +186,7 @@ func TestBig(t *testing.T) {
if err != nil {
t.Fatalf("Encoder.Close() = %v want nil", err)
}
- decoded, err := ioutil.ReadAll(NewDecoder(encoded))
+ decoded, err := io.ReadAll(NewDecoder(encoded))
if err != nil {
t.Fatalf("io.ReadAll(NewDecoder(...)): %v", err)
}
@@ -205,7 +204,7 @@ func TestBig(t *testing.T) {
func TestDecoderInternalWhitespace(t *testing.T) {
s := strings.Repeat(" ", 2048) + "z"
- decoded, err := ioutil.ReadAll(NewDecoder(strings.NewReader(s)))
+ decoded, err := io.ReadAll(NewDecoder(strings.NewReader(s)))
if err != nil {
t.Errorf("Decode gave error %v", err)
}
diff --git a/src/encoding/base32/base32_test.go b/src/encoding/base32/base32_test.go
index 0b611db0b2..8fb22b9078 100644
--- a/src/encoding/base32/base32_test.go
+++ b/src/encoding/base32/base32_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"errors"
"io"
- "io/ioutil"
"strings"
"testing"
)
@@ -361,9 +360,9 @@ func TestBig(t *testing.T) {
if err != nil {
t.Fatalf("Encoder.Close() = %v want nil", err)
}
- decoded, err := ioutil.ReadAll(NewDecoder(StdEncoding, encoded))
+ decoded, err := io.ReadAll(NewDecoder(StdEncoding, encoded))
if err != nil {
- t.Fatalf("ioutil.ReadAll(NewDecoder(...)): %v", err)
+ t.Fatalf("io.ReadAll(NewDecoder(...)): %v", err)
}
if !bytes.Equal(raw, decoded) {
@@ -428,14 +427,14 @@ LNEBUWIIDFON2CA3DBMJXXE5LNFY==
encodedShort := strings.ReplaceAll(encoded, "\n", "")
dec := NewDecoder(StdEncoding, strings.NewReader(encoded))
- res1, err := ioutil.ReadAll(dec)
+ res1, err := io.ReadAll(dec)
if err != nil {
t.Errorf("ReadAll failed: %v", err)
}
dec = NewDecoder(StdEncoding, strings.NewReader(encodedShort))
var res2 []byte
- res2, err = ioutil.ReadAll(dec)
+ res2, err = io.ReadAll(dec)
if err != nil {
t.Errorf("ReadAll failed: %v", err)
}
@@ -619,7 +618,7 @@ func TestBufferedDecodingSameError(t *testing.T) {
}()
decoder := NewDecoder(StdEncoding, pr)
- _, err := ioutil.ReadAll(decoder)
+ _, err := io.ReadAll(decoder)
if err != testcase.expected {
t.Errorf("Expected %v, got %v; case %s %+v", testcase.expected, err, testcase.prefix, chunks)
@@ -718,7 +717,7 @@ func TestDecodeReadAll(t *testing.T) {
encoded = strings.ReplaceAll(encoded, "=", "")
}
- decReader, err := ioutil.ReadAll(NewDecoder(encoding, strings.NewReader(encoded)))
+ decReader, err := io.ReadAll(NewDecoder(encoding, strings.NewReader(encoded)))
if err != nil {
t.Errorf("NewDecoder error: %v", err)
}
diff --git a/src/encoding/base64/base64_test.go b/src/encoding/base64/base64_test.go
index c2c9478a43..51047402bd 100644
--- a/src/encoding/base64/base64_test.go
+++ b/src/encoding/base64/base64_test.go
@@ -9,7 +9,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"reflect"
"runtime/debug"
"strings"
@@ -324,9 +323,9 @@ func TestBig(t *testing.T) {
if err != nil {
t.Fatalf("Encoder.Close() = %v want nil", err)
}
- decoded, err := ioutil.ReadAll(NewDecoder(StdEncoding, encoded))
+ decoded, err := io.ReadAll(NewDecoder(StdEncoding, encoded))
if err != nil {
- t.Fatalf("ioutil.ReadAll(NewDecoder(...)): %v", err)
+ t.Fatalf("io.ReadAll(NewDecoder(...)): %v", err)
}
if !bytes.Equal(raw, decoded) {
@@ -403,7 +402,7 @@ func TestDecoderIssue3577(t *testing.T) {
})
errc := make(chan error, 1)
go func() {
- _, err := ioutil.ReadAll(d)
+ _, err := io.ReadAll(d)
errc <- err
}()
select {
@@ -436,14 +435,14 @@ bqbPb06551Y4
encodedShort := strings.ReplaceAll(encoded, "\n", "")
dec := NewDecoder(StdEncoding, strings.NewReader(encoded))
- res1, err := ioutil.ReadAll(dec)
+ res1, err := io.ReadAll(dec)
if err != nil {
t.Errorf("ReadAll failed: %v", err)
}
dec = NewDecoder(StdEncoding, strings.NewReader(encodedShort))
var res2 []byte
- res2, err = ioutil.ReadAll(dec)
+ res2, err = io.ReadAll(dec)
if err != nil {
t.Errorf("ReadAll failed: %v", err)
}
@@ -517,14 +516,14 @@ func TestDecoderRaw(t *testing.T) {
// Through reader. Used to fail.
r := NewDecoder(RawURLEncoding, bytes.NewReader([]byte(source)))
- dec2, err := ioutil.ReadAll(io.LimitReader(r, 100))
+ dec2, err := io.ReadAll(io.LimitReader(r, 100))
if err != nil || !bytes.Equal(dec2, want) {
t.Errorf("reading NewDecoder(RawURLEncoding, %q) = %x, %v, want %x, nil", source, dec2, err, want)
}
// Should work with padding.
r = NewDecoder(URLEncoding, bytes.NewReader([]byte(source+"==")))
- dec3, err := ioutil.ReadAll(r)
+ dec3, err := io.ReadAll(r)
if err != nil || !bytes.Equal(dec3, want) {
t.Errorf("reading NewDecoder(URLEncoding, %q) = %x, %v, want %x, nil", source+"==", dec3, err, want)
}
diff --git a/src/encoding/binary/binary_test.go b/src/encoding/binary/binary_test.go
index 5971e0966a..83af89e8a7 100644
--- a/src/encoding/binary/binary_test.go
+++ b/src/encoding/binary/binary_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"math"
"reflect"
"strings"
@@ -524,7 +523,7 @@ func BenchmarkWriteStruct(b *testing.B) {
b.SetBytes(int64(Size(&s)))
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Write(ioutil.Discard, BigEndian, &s)
+ Write(io.Discard, BigEndian, &s)
}
}
diff --git a/src/encoding/gob/encoder_test.go b/src/encoding/gob/encoder_test.go
index 825f0d6f03..fe2774948a 100644
--- a/src/encoding/gob/encoder_test.go
+++ b/src/encoding/gob/encoder_test.go
@@ -8,7 +8,7 @@ import (
"bytes"
"encoding/hex"
"fmt"
- "io/ioutil"
+ "io"
"reflect"
"strings"
"testing"
@@ -938,7 +938,7 @@ func encodeAndRecover(value interface{}) (encodeErr, panicErr error) {
}
}()
- encodeErr = NewEncoder(ioutil.Discard).Encode(value)
+ encodeErr = NewEncoder(io.Discard).Encode(value)
return
}
diff --git a/src/encoding/hex/hex_test.go b/src/encoding/hex/hex_test.go
index 31e3f68936..7593e20db5 100644
--- a/src/encoding/hex/hex_test.go
+++ b/src/encoding/hex/hex_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"strings"
"testing"
)
@@ -150,7 +149,7 @@ func TestEncoderDecoder(t *testing.T) {
func TestDecoderErr(t *testing.T) {
for _, tt := range errTests {
dec := NewDecoder(strings.NewReader(tt.in))
- out, err := ioutil.ReadAll(dec)
+ out, err := io.ReadAll(dec)
wantErr := tt.err
// Decoder is reading from stream, so it reports io.ErrUnexpectedEOF instead of ErrLength.
if wantErr == ErrLength {
diff --git a/src/encoding/json/bench_test.go b/src/encoding/json/bench_test.go
index 4a5fe7ec84..73c7b09fb6 100644
--- a/src/encoding/json/bench_test.go
+++ b/src/encoding/json/bench_test.go
@@ -15,7 +15,7 @@ import (
"compress/gzip"
"fmt"
"internal/testenv"
- "io/ioutil"
+ "io"
"os"
"reflect"
"runtime"
@@ -52,7 +52,7 @@ func codeInit() {
if err != nil {
panic(err)
}
- data, err := ioutil.ReadAll(gz)
+ data, err := io.ReadAll(gz)
if err != nil {
panic(err)
}
@@ -89,7 +89,7 @@ func BenchmarkCodeEncoder(b *testing.B) {
b.StartTimer()
}
b.RunParallel(func(pb *testing.PB) {
- enc := NewEncoder(ioutil.Discard)
+ enc := NewEncoder(io.Discard)
for pb.Next() {
if err := enc.Encode(&codeStruct); err != nil {
b.Fatal("Encode:", err)
@@ -399,7 +399,7 @@ func BenchmarkEncodeMarshaler(b *testing.B) {
}{}
b.RunParallel(func(pb *testing.PB) {
- enc := NewEncoder(ioutil.Discard)
+ enc := NewEncoder(io.Discard)
for pb.Next() {
if err := enc.Encode(&m); err != nil {
diff --git a/src/encoding/json/stream_test.go b/src/encoding/json/stream_test.go
index c9e5334337..c284f2d965 100644
--- a/src/encoding/json/stream_test.go
+++ b/src/encoding/json/stream_test.go
@@ -7,7 +7,6 @@ package json
import (
"bytes"
"io"
- "io/ioutil"
"log"
"net"
"net/http"
@@ -215,7 +214,7 @@ func TestDecoderBuffered(t *testing.T) {
if m.Name != "Gopher" {
t.Errorf("Name = %q; want Gopher", m.Name)
}
- rest, err := ioutil.ReadAll(d.Buffered())
+ rest, err := io.ReadAll(d.Buffered())
if err != nil {
t.Fatal(err)
}
@@ -318,7 +317,7 @@ func BenchmarkEncoderEncode(b *testing.B) {
v := &T{"foo", "bar"}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
- if err := NewEncoder(ioutil.Discard).Encode(v); err != nil {
+ if err := NewEncoder(io.Discard).Encode(v); err != nil {
b.Fatal(err)
}
}
diff --git a/src/encoding/pem/pem_test.go b/src/encoding/pem/pem_test.go
index 8515b46498..b2b6b15e73 100644
--- a/src/encoding/pem/pem_test.go
+++ b/src/encoding/pem/pem_test.go
@@ -6,7 +6,7 @@ package pem
import (
"bytes"
- "io/ioutil"
+ "io"
"reflect"
"strings"
"testing"
@@ -271,7 +271,7 @@ func BenchmarkEncode(b *testing.B) {
data := &Block{Bytes: make([]byte, 65536)}
b.SetBytes(int64(len(data.Bytes)))
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, data)
+ Encode(io.Discard, data)
}
}
diff --git a/src/flag/flag_test.go b/src/flag/flag_test.go
index 2793064511..06cab79405 100644
--- a/src/flag/flag_test.go
+++ b/src/flag/flag_test.go
@@ -10,7 +10,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"os"
"os/exec"
"runtime"
@@ -545,7 +544,7 @@ func TestGetters(t *testing.T) {
func TestParseError(t *testing.T) {
for _, typ := range []string{"bool", "int", "int64", "uint", "uint64", "float64", "duration"} {
fs := NewFlagSet("parse error test", ContinueOnError)
- fs.SetOutput(ioutil.Discard)
+ fs.SetOutput(io.Discard)
_ = fs.Bool("bool", false, "")
_ = fs.Int("int", 0, "")
_ = fs.Int64("int64", 0, "")
@@ -576,7 +575,7 @@ func TestRangeError(t *testing.T) {
}
for _, arg := range bad {
fs := NewFlagSet("parse error test", ContinueOnError)
- fs.SetOutput(ioutil.Discard)
+ fs.SetOutput(io.Discard)
_ = fs.Int("int", 0, "")
_ = fs.Int64("int64", 0, "")
_ = fs.Uint("uint", 0, "")
diff --git a/src/go/internal/gccgoimporter/importer.go b/src/go/internal/gccgoimporter/importer.go
index 2494fd7b2a..94f2defd8d 100644
--- a/src/go/internal/gccgoimporter/importer.go
+++ b/src/go/internal/gccgoimporter/importer.go
@@ -221,7 +221,7 @@ func GetImporter(searchpaths []string, initmap map[*types.Package]InitData) Impo
// Excluded for now: Standard gccgo doesn't support this import format currently.
// case goimporterMagic:
// var data []byte
- // data, err = ioutil.ReadAll(reader)
+ // data, err = io.ReadAll(reader)
// if err != nil {
// return
// }
diff --git a/src/go/internal/gcimporter/gcimporter.go b/src/go/internal/gcimporter/gcimporter.go
index fda15eaaae..b74daca246 100644
--- a/src/go/internal/gcimporter/gcimporter.go
+++ b/src/go/internal/gcimporter/gcimporter.go
@@ -12,7 +12,6 @@ import (
"go/token"
"go/types"
"io"
- "io/ioutil"
"os"
"path/filepath"
"strings"
@@ -147,7 +146,7 @@ func Import(fset *token.FileSet, packages map[string]*types.Package, path, srcDi
case "$$B\n":
var data []byte
- data, err = ioutil.ReadAll(buf)
+ data, err = io.ReadAll(buf)
if err != nil {
break
}
diff --git a/src/go/parser/interface.go b/src/go/parser/interface.go
index b2d834fdec..cc7e455c4d 100644
--- a/src/go/parser/interface.go
+++ b/src/go/parser/interface.go
@@ -35,7 +35,7 @@ func readSource(filename string, src interface{}) ([]byte, error) {
return s.Bytes(), nil
}
case io.Reader:
- return ioutil.ReadAll(s)
+ return io.ReadAll(s)
}
return nil, errors.New("invalid source")
}
diff --git a/src/go/printer/performance_test.go b/src/go/printer/performance_test.go
index 2e67154e6b..e23de3fbae 100644
--- a/src/go/printer/performance_test.go
+++ b/src/go/printer/performance_test.go
@@ -53,6 +53,6 @@ func BenchmarkPrint(b *testing.B) {
initialize()
}
for i := 0; i < b.N; i++ {
- testprint(ioutil.Discard, testfile)
+ testprint(io.Discard, testfile)
}
}
diff --git a/src/go/types/gotype.go b/src/go/types/gotype.go
index eacf68f52f..52709df17b 100644
--- a/src/go/types/gotype.go
+++ b/src/go/types/gotype.go
@@ -88,7 +88,7 @@ import (
"go/scanner"
"go/token"
"go/types"
- "io/ioutil"
+ "io"
"os"
"path/filepath"
"sync"
@@ -191,7 +191,7 @@ func parse(filename string, src interface{}) (*ast.File, error) {
}
func parseStdin() (*ast.File, error) {
- src, err := ioutil.ReadAll(os.Stdin)
+ src, err := io.ReadAll(os.Stdin)
if err != nil {
return nil, err
}
diff --git a/src/html/template/clone_test.go b/src/html/template/clone_test.go
index c9c619f0d4..7cb1b9ca06 100644
--- a/src/html/template/clone_test.go
+++ b/src/html/template/clone_test.go
@@ -8,7 +8,7 @@ import (
"bytes"
"errors"
"fmt"
- "io/ioutil"
+ "io"
"strings"
"sync"
"testing"
@@ -171,7 +171,7 @@ func TestCloneThenParse(t *testing.T) {
t.Error("adding a template to a clone added it to the original")
}
// double check that the embedded template isn't available in the original
- err := t0.ExecuteTemplate(ioutil.Discard, "a", nil)
+ err := t0.ExecuteTemplate(io.Discard, "a", nil)
if err == nil {
t.Error("expected 'no such template' error")
}
@@ -185,13 +185,13 @@ func TestFuncMapWorksAfterClone(t *testing.T) {
// get the expected error output (no clone)
uncloned := Must(New("").Funcs(funcs).Parse("{{customFunc}}"))
- wantErr := uncloned.Execute(ioutil.Discard, nil)
+ wantErr := uncloned.Execute(io.Discard, nil)
// toClone must be the same as uncloned. It has to be recreated from scratch,
// since cloning cannot occur after execution.
toClone := Must(New("").Funcs(funcs).Parse("{{customFunc}}"))
cloned := Must(toClone.Clone())
- gotErr := cloned.Execute(ioutil.Discard, nil)
+ gotErr := cloned.Execute(io.Discard, nil)
if wantErr.Error() != gotErr.Error() {
t.Errorf("clone error message mismatch want %q got %q", wantErr, gotErr)
@@ -213,7 +213,7 @@ func TestTemplateCloneExecuteRace(t *testing.T) {
go func() {
defer wg.Done()
for i := 0; i < 100; i++ {
- if err := tmpl.Execute(ioutil.Discard, "data"); err != nil {
+ if err := tmpl.Execute(io.Discard, "data"); err != nil {
panic(err)
}
}
@@ -237,7 +237,7 @@ func TestCloneGrowth(t *testing.T) {
tmpl = Must(tmpl.Clone())
Must(tmpl.Parse(`{{define "B"}}Text{{end}}`))
for i := 0; i < 10; i++ {
- tmpl.Execute(ioutil.Discard, nil)
+ tmpl.Execute(io.Discard, nil)
}
if len(tmpl.DefinedTemplates()) > 200 {
t.Fatalf("too many templates: %v", len(tmpl.DefinedTemplates()))
@@ -257,7 +257,7 @@ func TestCloneRedefinedName(t *testing.T) {
for i := 0; i < 2; i++ {
t2 := Must(t1.Clone())
t2 = Must(t2.New(fmt.Sprintf("%d", i)).Parse(page))
- err := t2.Execute(ioutil.Discard, nil)
+ err := t2.Execute(io.Discard, nil)
if err != nil {
t.Fatal(err)
}
diff --git a/src/html/template/exec_test.go b/src/html/template/exec_test.go
index fc76ee40e5..232945a0bb 100644
--- a/src/html/template/exec_test.go
+++ b/src/html/template/exec_test.go
@@ -11,7 +11,7 @@ import (
"errors"
"flag"
"fmt"
- "io/ioutil"
+ "io"
"reflect"
"strings"
"testing"
@@ -1335,7 +1335,7 @@ func TestExecuteGivesExecError(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- err = tmpl.Execute(ioutil.Discard, 0)
+ err = tmpl.Execute(io.Discard, 0)
if err == nil {
t.Fatal("expected error; got none")
}
@@ -1481,7 +1481,7 @@ func TestEvalFieldErrors(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
tmpl := Must(New("tmpl").Parse(tc.src))
- err := tmpl.Execute(ioutil.Discard, tc.value)
+ err := tmpl.Execute(io.Discard, tc.value)
got := ""
if err != nil {
got = err.Error()
@@ -1498,7 +1498,7 @@ func TestMaxExecDepth(t *testing.T) {
t.Skip("skipping in -short mode")
}
tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))
- err := tmpl.Execute(ioutil.Discard, nil)
+ err := tmpl.Execute(io.Discard, nil)
got := ""
if err != nil {
got = err.Error()
diff --git a/src/image/gif/writer_test.go b/src/image/gif/writer_test.go
index 1e622b3674..af0105c6be 100644
--- a/src/image/gif/writer_test.go
+++ b/src/image/gif/writer_test.go
@@ -11,7 +11,7 @@ import (
"image/color/palette"
"image/draw"
_ "image/png"
- "io/ioutil"
+ "io"
"math/rand"
"os"
"reflect"
@@ -285,7 +285,7 @@ func TestEncodeMismatchDelay(t *testing.T) {
Image: images,
Delay: make([]int, 1),
}
- if err := EncodeAll(ioutil.Discard, g0); err == nil {
+ if err := EncodeAll(io.Discard, g0); err == nil {
t.Error("expected error from mismatched delay and image slice lengths")
}
@@ -297,13 +297,13 @@ func TestEncodeMismatchDelay(t *testing.T) {
for i := range g1.Disposal {
g1.Disposal[i] = DisposalNone
}
- if err := EncodeAll(ioutil.Discard, g1); err == nil {
+ if err := EncodeAll(io.Discard, g1); err == nil {
t.Error("expected error from mismatched disposal and image slice lengths")
}
}
func TestEncodeZeroGIF(t *testing.T) {
- if err := EncodeAll(ioutil.Discard, &GIF{}); err == nil {
+ if err := EncodeAll(io.Discard, &GIF{}); err == nil {
t.Error("expected error from providing empty gif")
}
}
@@ -324,7 +324,7 @@ func TestEncodeAllFramesOutOfBounds(t *testing.T) {
Height: upperBound,
},
}
- err := EncodeAll(ioutil.Discard, g)
+ err := EncodeAll(io.Discard, g)
if upperBound >= 8 {
if err != nil {
t.Errorf("upperBound=%d: %v", upperBound, err)
@@ -430,7 +430,7 @@ func TestEncodeImplicitConfigSize(t *testing.T) {
Image: images,
Delay: make([]int, len(images)),
}
- err := EncodeAll(ioutil.Discard, g)
+ err := EncodeAll(io.Discard, g)
if lowerBound >= 0 {
if err != nil {
t.Errorf("lowerBound=%d: %v", lowerBound, err)
@@ -509,7 +509,7 @@ func TestEncodeBadPalettes(t *testing.T) {
}
}
- err := EncodeAll(ioutil.Discard, &GIF{
+ err := EncodeAll(io.Discard, &GIF{
Image: []*image.Paletted{
image.NewPaletted(image.Rect(0, 0, w, h), pal),
},
@@ -668,7 +668,7 @@ func BenchmarkEncodeRandomPaletted(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, paletted, nil)
+ Encode(io.Discard, paletted, nil)
}
}
@@ -691,7 +691,7 @@ func BenchmarkEncodeRandomRGBA(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, rgba, nil)
+ Encode(io.Discard, rgba, nil)
}
}
@@ -708,7 +708,7 @@ func BenchmarkEncodeRealisticPaletted(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, paletted, nil)
+ Encode(io.Discard, paletted, nil)
}
}
@@ -729,6 +729,6 @@ func BenchmarkEncodeRealisticRGBA(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, rgba, nil)
+ Encode(io.Discard, rgba, nil)
}
}
diff --git a/src/image/jpeg/writer_test.go b/src/image/jpeg/writer_test.go
index 3aff742632..abd5e32333 100644
--- a/src/image/jpeg/writer_test.go
+++ b/src/image/jpeg/writer_test.go
@@ -10,7 +10,7 @@ import (
"image"
"image/color"
"image/png"
- "io/ioutil"
+ "io"
"math/rand"
"os"
"testing"
@@ -261,7 +261,7 @@ func BenchmarkEncodeRGBA(b *testing.B) {
b.ResetTimer()
options := &Options{Quality: 90}
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, img, options)
+ Encode(io.Discard, img, options)
}
}
@@ -283,6 +283,6 @@ func BenchmarkEncodeYCbCr(b *testing.B) {
b.ResetTimer()
options := &Options{Quality: 90}
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, img, options)
+ Encode(io.Discard, img, options)
}
}
diff --git a/src/image/png/writer_test.go b/src/image/png/writer_test.go
index 5d131ff823..47aa861339 100644
--- a/src/image/png/writer_test.go
+++ b/src/image/png/writer_test.go
@@ -12,7 +12,6 @@ import (
"image"
"image/color"
"io"
- "io/ioutil"
"testing"
)
@@ -169,7 +168,7 @@ func TestWriterPaletted(t *testing.T) {
t.Error(err)
return
}
- n, err := io.Copy(ioutil.Discard, r)
+ n, err := io.Copy(io.Discard, r)
if err != nil {
t.Errorf("got error while reading image data: %v", err)
}
@@ -234,7 +233,7 @@ func BenchmarkEncodeGray(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, img)
+ Encode(io.Discard, img)
}
}
@@ -259,7 +258,7 @@ func BenchmarkEncodeGrayWithBufferPool(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- e.Encode(ioutil.Discard, img)
+ e.Encode(io.Discard, img)
}
}
@@ -279,7 +278,7 @@ func BenchmarkEncodeNRGBOpaque(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, img)
+ Encode(io.Discard, img)
}
}
@@ -292,7 +291,7 @@ func BenchmarkEncodeNRGBA(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, img)
+ Encode(io.Discard, img)
}
}
@@ -305,7 +304,7 @@ func BenchmarkEncodePaletted(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, img)
+ Encode(io.Discard, img)
}
}
@@ -325,7 +324,7 @@ func BenchmarkEncodeRGBOpaque(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, img)
+ Encode(io.Discard, img)
}
}
@@ -338,6 +337,6 @@ func BenchmarkEncodeRGBA(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- Encode(ioutil.Discard, img)
+ Encode(io.Discard, img)
}
}
diff --git a/src/internal/obscuretestdata/obscuretestdata.go b/src/internal/obscuretestdata/obscuretestdata.go
index 512f3759b4..06cd1df22c 100644
--- a/src/internal/obscuretestdata/obscuretestdata.go
+++ b/src/internal/obscuretestdata/obscuretestdata.go
@@ -47,5 +47,5 @@ func ReadFile(name string) ([]byte, error) {
return nil, err
}
defer f.Close()
- return ioutil.ReadAll(base64.NewDecoder(base64.StdEncoding, f))
+ return io.ReadAll(base64.NewDecoder(base64.StdEncoding, f))
}
diff --git a/src/internal/profile/profile.go b/src/internal/profile/profile.go
index a6275bc6de..29568aa4b5 100644
--- a/src/internal/profile/profile.go
+++ b/src/internal/profile/profile.go
@@ -12,7 +12,6 @@ import (
"compress/gzip"
"fmt"
"io"
- "io/ioutil"
"regexp"
"strings"
"time"
@@ -125,7 +124,7 @@ type Function struct {
// may be a gzip-compressed encoded protobuf or one of many legacy
// profile formats which may be unsupported in the future.
func Parse(r io.Reader) (*Profile, error) {
- orig, err := ioutil.ReadAll(r)
+ orig, err := io.ReadAll(r)
if err != nil {
return nil, err
}
@@ -136,7 +135,7 @@ func Parse(r io.Reader) (*Profile, error) {
if err != nil {
return nil, fmt.Errorf("decompressing profile: %v", err)
}
- data, err := ioutil.ReadAll(gz)
+ data, err := io.ReadAll(gz)
if err != nil {
return nil, fmt.Errorf("decompressing profile: %v", err)
}
diff --git a/src/io/example_test.go b/src/io/example_test.go
index 4706032429..6d338acd14 100644
--- a/src/io/example_test.go
+++ b/src/io/example_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"log"
"os"
"strings"
@@ -141,7 +140,7 @@ func ExampleTeeReader() {
r = io.TeeReader(r, os.Stdout)
// Everything read from r will be copied to stdout.
- ioutil.ReadAll(r)
+ io.ReadAll(r)
// Output:
// some io.Reader stream to be read
@@ -245,7 +244,7 @@ func ExamplePipe() {
func ExampleReadAll() {
r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
- b, err := ioutil.ReadAll(r)
+ b, err := io.ReadAll(r)
if err != nil {
log.Fatal(err)
}
diff --git a/src/io/io.go b/src/io/io.go
index 269ebf6ed0..ffd3cedc25 100644
--- a/src/io/io.go
+++ b/src/io/io.go
@@ -573,7 +573,7 @@ var Discard Writer = discard{}
type discard struct{}
// discard implements ReaderFrom as an optimization so Copy to
-// ioutil.Discard can avoid doing unnecessary work.
+// io.Discard can avoid doing unnecessary work.
var _ ReaderFrom = discard{}
func (discard) Write(p []byte) (int, error) {
diff --git a/src/io/multi_test.go b/src/io/multi_test.go
index f05d5f74ef..909b6d8be2 100644
--- a/src/io/multi_test.go
+++ b/src/io/multi_test.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
. "io"
- "io/ioutil"
"runtime"
"strings"
"testing"
@@ -142,7 +141,7 @@ func testMultiWriter(t *testing.T, sink interface {
}
}
-// writerFunc is an io.Writer implemented by the underlying func.
+// writerFunc is an Writer implemented by the underlying func.
type writerFunc func(p []byte) (int, error)
func (f writerFunc) Write(p []byte) (int, error) {
@@ -196,7 +195,7 @@ func TestMultiReaderCopy(t *testing.T) {
slice := []Reader{strings.NewReader("hello world")}
r := MultiReader(slice...)
slice[0] = nil
- data, err := ioutil.ReadAll(r)
+ data, err := ReadAll(r)
if err != nil || string(data) != "hello world" {
t.Errorf("ReadAll() = %q, %v, want %q, nil", data, err, "hello world")
}
@@ -217,7 +216,7 @@ func TestMultiWriterCopy(t *testing.T) {
}
}
-// readerFunc is an io.Reader implemented by the underlying func.
+// readerFunc is an Reader implemented by the underlying func.
type readerFunc func(p []byte) (int, error)
func (f readerFunc) Read(p []byte) (int, error) {
@@ -261,7 +260,7 @@ func TestMultiReaderFlatten(t *testing.T) {
}
// byteAndEOFReader is a Reader which reads one byte (the underlying
-// byte) and io.EOF at once in its Read call.
+// byte) and EOF at once in its Read call.
type byteAndEOFReader byte
func (b byteAndEOFReader) Read(p []byte) (n int, err error) {
@@ -276,7 +275,7 @@ func (b byteAndEOFReader) Read(p []byte) (n int, err error) {
// This used to yield bytes forever; issue 16795.
func TestMultiReaderSingleByteWithEOF(t *testing.T) {
- got, err := ioutil.ReadAll(LimitReader(MultiReader(byteAndEOFReader('a'), byteAndEOFReader('b')), 10))
+ got, err := ReadAll(LimitReader(MultiReader(byteAndEOFReader('a'), byteAndEOFReader('b')), 10))
if err != nil {
t.Fatal(err)
}
diff --git a/src/mime/encodedword_test.go b/src/mime/encodedword_test.go
index 6c54e502ad..2a98794380 100644
--- a/src/mime/encodedword_test.go
+++ b/src/mime/encodedword_test.go
@@ -7,7 +7,6 @@ package mime
import (
"errors"
"io"
- "io/ioutil"
"strings"
"testing"
)
@@ -182,7 +181,7 @@ func TestCharsetDecoder(t *testing.T) {
if charset != test.charsets[i] {
t.Errorf("DecodeHeader(%q), got charset %q, want %q", test.src, charset, test.charsets[i])
}
- content, err := ioutil.ReadAll(input)
+ content, err := io.ReadAll(input)
if err != nil {
t.Errorf("DecodeHeader(%q), error in reader: %v", test.src, err)
}
diff --git a/src/mime/example_test.go b/src/mime/example_test.go
index 85795976f0..8a96873e5d 100644
--- a/src/mime/example_test.go
+++ b/src/mime/example_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"mime"
)
@@ -38,7 +37,7 @@ func ExampleWordDecoder_Decode() {
// Fake character set for example.
// Real use would integrate with packages such
// as code.google.com/p/go-charset
- content, err := ioutil.ReadAll(input)
+ content, err := io.ReadAll(input)
if err != nil {
return nil, err
}
@@ -77,7 +76,7 @@ func ExampleWordDecoder_DecodeHeader() {
// Fake character set for example.
// Real use would integrate with packages such
// as code.google.com/p/go-charset
- content, err := ioutil.ReadAll(input)
+ content, err := io.ReadAll(input)
if err != nil {
return nil, err
}
diff --git a/src/mime/multipart/example_test.go b/src/mime/multipart/example_test.go
index 6d6ba81d5e..fe154ac4f6 100644
--- a/src/mime/multipart/example_test.go
+++ b/src/mime/multipart/example_test.go
@@ -7,7 +7,6 @@ package multipart_test
import (
"fmt"
"io"
- "io/ioutil"
"log"
"mime"
"mime/multipart"
@@ -39,7 +38,7 @@ func ExampleNewReader() {
if err != nil {
log.Fatal(err)
}
- slurp, err := ioutil.ReadAll(p)
+ slurp, err := io.ReadAll(p)
if err != nil {
log.Fatal(err)
}
diff --git a/src/mime/multipart/multipart.go b/src/mime/multipart/multipart.go
index 1750300fb5..cb8bf39338 100644
--- a/src/mime/multipart/multipart.go
+++ b/src/mime/multipart/multipart.go
@@ -17,7 +17,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"mime"
"mime/quotedprintable"
"net/textproto"
@@ -278,7 +277,7 @@ func matchAfterPrefix(buf, prefix []byte, readErr error) int {
}
func (p *Part) Close() error {
- io.Copy(ioutil.Discard, p)
+ io.Copy(io.Discard, p)
return nil
}
diff --git a/src/mime/multipart/multipart_test.go b/src/mime/multipart/multipart_test.go
index b60c54a204..741d2304ed 100644
--- a/src/mime/multipart/multipart_test.go
+++ b/src/mime/multipart/multipart_test.go
@@ -9,7 +9,6 @@ import (
"encoding/json"
"fmt"
"io"
- "io/ioutil"
"net/textproto"
"os"
"reflect"
@@ -307,7 +306,7 @@ Oh no, premature EOF!
if err != nil {
t.Fatalf("didn't get a part")
}
- _, err = io.Copy(ioutil.Discard, part)
+ _, err = io.Copy(io.Discard, part)
if err != io.ErrUnexpectedEOF {
t.Fatalf("expected error io.ErrUnexpectedEOF; got %v", err)
}
@@ -372,7 +371,7 @@ Body 2
if !reflect.DeepEqual(part.Header, hdr) {
t.Errorf("Part %d: part.Header = %v, want %v", i, part.Header, hdr)
}
- data, err := ioutil.ReadAll(part)
+ data, err := io.ReadAll(part)
expectEq(t, body, string(data), fmt.Sprintf("Part %d body", i))
if err != nil {
t.Fatalf("Part %d: ReadAll failed: %v", i, err)
@@ -530,14 +529,14 @@ func TestNested(t *testing.T) {
if err != nil {
t.Fatalf("reading text/plain part: %v", err)
}
- if b, err := ioutil.ReadAll(p); string(b) != "*body*\r\n" || err != nil {
+ if b, err := io.ReadAll(p); string(b) != "*body*\r\n" || err != nil {
t.Fatalf("reading text/plain part: got %q, %v", b, err)
}
p, err = mr2.NextPart()
if err != nil {
t.Fatalf("reading text/html part: %v", err)
}
- if b, err := ioutil.ReadAll(p); string(b) != "body\r\n" || err != nil {
+ if b, err := io.ReadAll(p); string(b) != "body\r\n" || err != nil {
t.Fatalf("reading text/html part: got %q, %v", b, err)
}
@@ -850,7 +849,7 @@ Cases:
t.Errorf("in test %q, NextPart: %v", tt.name, err)
continue Cases
}
- pbody, err := ioutil.ReadAll(p)
+ pbody, err := io.ReadAll(p)
if err != nil {
t.Errorf("in test %q, error reading part: %v", tt.name, err)
continue Cases
@@ -882,7 +881,7 @@ func partsFromReader(r *Reader) ([]headerBody, error) {
if err != nil {
return nil, fmt.Errorf("NextPart: %v", err)
}
- pbody, err := ioutil.ReadAll(p)
+ pbody, err := io.ReadAll(p)
if err != nil {
return nil, fmt.Errorf("error reading part: %v", err)
}
diff --git a/src/mime/multipart/writer_test.go b/src/mime/multipart/writer_test.go
index b89b093fff..cfc0f09f37 100644
--- a/src/mime/multipart/writer_test.go
+++ b/src/mime/multipart/writer_test.go
@@ -6,7 +6,7 @@ package multipart
import (
"bytes"
- "io/ioutil"
+ "io"
"mime"
"net/textproto"
"strings"
@@ -51,7 +51,7 @@ func TestWriter(t *testing.T) {
if g, e := part.FormName(), "myfile"; g != e {
t.Errorf("part 1: want form name %q, got %q", e, g)
}
- slurp, err := ioutil.ReadAll(part)
+ slurp, err := io.ReadAll(part)
if err != nil {
t.Fatalf("part 1: ReadAll: %v", err)
}
@@ -66,7 +66,7 @@ func TestWriter(t *testing.T) {
if g, e := part.FormName(), "key"; g != e {
t.Errorf("part 2: want form name %q, got %q", e, g)
}
- slurp, err = ioutil.ReadAll(part)
+ slurp, err = io.ReadAll(part)
if err != nil {
t.Fatalf("part 2: ReadAll: %v", err)
}
@@ -134,7 +134,7 @@ func TestWriterBoundaryGoroutines(t *testing.T) {
// different goroutines. This was previously broken by
// https://codereview.appspot.com/95760043/ and reverted in
// https://codereview.appspot.com/117600043/
- w := NewWriter(ioutil.Discard)
+ w := NewWriter(io.Discard)
done := make(chan int)
go func() {
w.CreateFormField("foo")
diff --git a/src/mime/quotedprintable/example_test.go b/src/mime/quotedprintable/example_test.go
index 5a9ab450a3..e5a479a3a7 100644
--- a/src/mime/quotedprintable/example_test.go
+++ b/src/mime/quotedprintable/example_test.go
@@ -6,7 +6,7 @@ package quotedprintable_test
import (
"fmt"
- "io/ioutil"
+ "io"
"mime/quotedprintable"
"os"
"strings"
@@ -18,7 +18,7 @@ func ExampleNewReader() {
`invalid escape: hello`,
"Hello, Gophers! This symbol will be unescaped: =3D and this will be written in =\r\none line.",
} {
- b, err := ioutil.ReadAll(quotedprintable.NewReader(strings.NewReader(s)))
+ b, err := io.ReadAll(quotedprintable.NewReader(strings.NewReader(s)))
fmt.Printf("%s %v\n", b, err)
}
// Output:
diff --git a/src/mime/quotedprintable/writer_test.go b/src/mime/quotedprintable/writer_test.go
index d494c1e3dc..42de0f3d6e 100644
--- a/src/mime/quotedprintable/writer_test.go
+++ b/src/mime/quotedprintable/writer_test.go
@@ -6,7 +6,7 @@ package quotedprintable
import (
"bytes"
- "io/ioutil"
+ "io"
"strings"
"testing"
)
@@ -128,7 +128,7 @@ func TestRoundTrip(t *testing.T) {
}
r := NewReader(buf)
- gotBytes, err := ioutil.ReadAll(r)
+ gotBytes, err := io.ReadAll(r)
if err != nil {
t.Fatalf("Error while reading from Reader: %v", err)
}
@@ -151,7 +151,7 @@ var testMsg = []byte("Quoted-Printable (QP) est un format d'encodage de données
func BenchmarkWriter(b *testing.B) {
for i := 0; i < b.N; i++ {
- w := NewWriter(ioutil.Discard)
+ w := NewWriter(io.Discard)
w.Write(testMsg)
w.Close()
}
diff --git a/src/net/http/alpn_test.go b/src/net/http/alpn_test.go
index 618bdbe54a..a51038c355 100644
--- a/src/net/http/alpn_test.go
+++ b/src/net/http/alpn_test.go
@@ -11,7 +11,6 @@ import (
"crypto/x509"
"fmt"
"io"
- "io/ioutil"
. "net/http"
"net/http/httptest"
"strings"
@@ -49,7 +48,7 @@ func TestNextProtoUpgrade(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -93,7 +92,7 @@ func TestNextProtoUpgrade(t *testing.T) {
t.Fatal(err)
}
conn.Write([]byte("GET /foo\n"))
- body, err := ioutil.ReadAll(conn)
+ body, err := io.ReadAll(conn)
if err != nil {
t.Fatal(err)
}
diff --git a/src/net/http/cgi/child.go b/src/net/http/cgi/child.go
index 690986335c..0114da377b 100644
--- a/src/net/http/cgi/child.go
+++ b/src/net/http/cgi/child.go
@@ -13,7 +13,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"net"
"net/http"
"net/url"
@@ -32,7 +31,7 @@ func Request() (*http.Request, error) {
return nil, err
}
if r.ContentLength > 0 {
- r.Body = ioutil.NopCloser(io.LimitReader(os.Stdin, r.ContentLength))
+ r.Body = io.NopCloser(io.LimitReader(os.Stdin, r.ContentLength))
}
return r, nil
}
diff --git a/src/net/http/client.go b/src/net/http/client.go
index 6ca0d2e6cf..88e2028bc3 100644
--- a/src/net/http/client.go
+++ b/src/net/http/client.go
@@ -16,7 +16,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"log"
"net/url"
"reflect"
@@ -282,7 +281,7 @@ func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, d
if resp.ContentLength > 0 && req.Method != "HEAD" {
return nil, didTimeout, fmt.Errorf("http: RoundTripper implementation (%T) returned a *Response with content length %d but a nil Body", rt, resp.ContentLength)
}
- resp.Body = ioutil.NopCloser(strings.NewReader(""))
+ resp.Body = io.NopCloser(strings.NewReader(""))
}
if !deadline.IsZero() {
resp.Body = &cancelTimerBody{
@@ -697,7 +696,7 @@ func (c *Client) do(req *Request) (retres *Response, reterr error) {
// fails, the Transport won't reuse it anyway.
const maxBodySlurpSize = 2 << 10
if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
- io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize)
+ io.CopyN(io.Discard, resp.Body, maxBodySlurpSize)
}
resp.Body.Close()
diff --git a/src/net/http/client_test.go b/src/net/http/client_test.go
index 4bd62735e8..d90b4841c6 100644
--- a/src/net/http/client_test.go
+++ b/src/net/http/client_test.go
@@ -14,7 +14,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"log"
"net"
. "net/http"
@@ -35,7 +34,7 @@ var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
})
-// pedanticReadAll works like ioutil.ReadAll but additionally
+// pedanticReadAll works like io.ReadAll but additionally
// verifies that r obeys the documented io.Reader contract.
func pedanticReadAll(r io.Reader) (b []byte, err error) {
var bufa [64]byte
@@ -190,7 +189,7 @@ func TestPostFormRequestFormat(t *testing.T) {
if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
t.Errorf("got ContentLength %d, want %d", g, e)
}
- bodyb, err := ioutil.ReadAll(tr.req.Body)
+ bodyb, err := io.ReadAll(tr.req.Body)
if err != nil {
t.Fatalf("ReadAll on req.Body: %v", err)
}
@@ -421,7 +420,7 @@ func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, wa
var ts *httptest.Server
ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
log.Lock()
- slurp, _ := ioutil.ReadAll(r.Body)
+ slurp, _ := io.ReadAll(r.Body)
fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
@@ -452,7 +451,7 @@ func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, wa
for _, tt := range table {
content := tt.redirectBody
req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
- req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
+ req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(content)), nil }
res, err := c.Do(req)
if err != nil {
@@ -522,7 +521,7 @@ func TestClientRedirectUseResponse(t *testing.T) {
t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
}
defer res.Body.Close()
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -1042,7 +1041,7 @@ func testClientHeadContentLength(t *testing.T, h2 bool) {
if res.ContentLength != tt.want {
t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
}
- bs, err := ioutil.ReadAll(res.Body)
+ bs, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -1257,7 +1256,7 @@ func testClientTimeout(t *testing.T, h2 bool) {
errc := make(chan error, 1)
go func() {
- _, err := ioutil.ReadAll(res.Body)
+ _, err := io.ReadAll(res.Body)
errc <- err
res.Body.Close()
}()
@@ -1348,7 +1347,7 @@ func TestClientTimeoutCancel(t *testing.T) {
t.Fatal(err)
}
cancel()
- _, err = io.Copy(ioutil.Discard, res.Body)
+ _, err = io.Copy(io.Discard, res.Body)
if err != ExportErrRequestCanceled {
t.Fatalf("error = %v; want errRequestCanceled", err)
}
@@ -1372,7 +1371,7 @@ func testClientRedirectEatsBody(t *testing.T, h2 bool) {
if err != nil {
t.Fatal(err)
}
- _, err = ioutil.ReadAll(res.Body)
+ _, err = io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
@@ -1450,7 +1449,7 @@ func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
resp := &Response{
StatusCode: 303,
Header: map[string][]string{"Location": {"http://www.example.com/"}},
- Body: ioutil.NopCloser(strings.NewReader("")),
+ Body: io.NopCloser(strings.NewReader("")),
}
return resp, nil
}
@@ -1591,7 +1590,7 @@ func TestClientCopyHostOnRedirect(t *testing.T) {
if resp.StatusCode != 200 {
t.Fatal(resp.Status)
}
- if got, err := ioutil.ReadAll(resp.Body); err != nil || string(got) != wantBody {
+ if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
t.Errorf("body = %q; want %q", got, wantBody)
}
}
@@ -2020,7 +2019,7 @@ func TestClientPopulatesNilResponseBody(t *testing.T) {
}
}()
- if b, err := ioutil.ReadAll(resp.Body); err != nil {
+ if b, err := io.ReadAll(resp.Body); err != nil {
t.Errorf("read error from substitute Response.Body: %v", err)
} else if len(b) != 0 {
t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
diff --git a/src/net/http/clientserver_test.go b/src/net/http/clientserver_test.go
index 439818bb2f..5e227181ac 100644
--- a/src/net/http/clientserver_test.go
+++ b/src/net/http/clientserver_test.go
@@ -15,7 +15,6 @@ import (
"fmt"
"hash"
"io"
- "io/ioutil"
"log"
"net"
. "net/http"
@@ -53,7 +52,7 @@ func (t *clientServerTest) getURL(u string) string {
t.t.Fatal(err)
}
defer res.Body.Close()
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.t.Fatal(err)
}
@@ -152,7 +151,7 @@ func TestChunkedResponseHeaders_h2(t *testing.T) { testChunkedResponseHeaders(t,
func testChunkedResponseHeaders(t *testing.T, h2 bool) {
defer afterTest(t)
- log.SetOutput(ioutil.Discard) // is noisy otherwise
+ log.SetOutput(io.Discard) // is noisy otherwise
defer log.SetOutput(os.Stderr)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Length", "intentional gibberish") // we check that this is deleted
@@ -266,11 +265,11 @@ func (tt h12Compare) normalizeRes(t *testing.T, res *Response, wantProto string)
} else {
t.Errorf("got %q response; want %q", res.Proto, wantProto)
}
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
res.Body.Close()
res.Body = slurpResult{
- ReadCloser: ioutil.NopCloser(bytes.NewReader(slurp)),
+ ReadCloser: io.NopCloser(bytes.NewReader(slurp)),
body: slurp,
err: err,
}
@@ -477,7 +476,7 @@ func test304Responses(t *testing.T, h2 bool) {
if len(res.TransferEncoding) > 0 {
t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
@@ -564,7 +563,7 @@ func testCancelRequestMidBody(t *testing.T, h2 bool) {
close(cancel)
- rest, err := ioutil.ReadAll(res.Body)
+ rest, err := io.ReadAll(res.Body)
all := string(firstRead) + string(rest)
if all != "Hello" {
t.Errorf("Read %q (%q + %q); want Hello", all, firstRead, rest)
@@ -587,7 +586,7 @@ func testTrailersClientToServer(t *testing.T, h2 bool) {
}
sort.Strings(decl)
- slurp, err := ioutil.ReadAll(r.Body)
+ slurp, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Server reading request body: %v", err)
}
@@ -721,7 +720,7 @@ func testResponseBodyReadAfterClose(t *testing.T, h2 bool) {
t.Fatal(err)
}
res.Body.Close()
- data, err := ioutil.ReadAll(res.Body)
+ data, err := io.ReadAll(res.Body)
if len(data) != 0 || err == nil {
t.Fatalf("ReadAll returned %q, %v; want error", data, err)
}
@@ -740,7 +739,7 @@ func testConcurrentReadWriteReqBody(t *testing.T, h2 bool) {
// Read in one goroutine.
go func() {
defer wg.Done()
- data, err := ioutil.ReadAll(r.Body)
+ data, err := io.ReadAll(r.Body)
if string(data) != reqBody {
t.Errorf("Handler read %q; want %q", data, reqBody)
}
@@ -770,7 +769,7 @@ func testConcurrentReadWriteReqBody(t *testing.T, h2 bool) {
if err != nil {
t.Fatal(err)
}
- data, err := ioutil.ReadAll(res.Body)
+ data, err := io.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
t.Fatal(err)
@@ -887,7 +886,7 @@ func testTransportUserAgent(t *testing.T, h2 bool) {
t.Errorf("%d. RoundTrip = %v", i, err)
continue
}
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Errorf("%d. read body = %v", i, err)
@@ -1019,7 +1018,7 @@ func TestTransportDiscardsUnneededConns(t *testing.T) {
}
}
defer resp.Body.Close()
- slurp, err := ioutil.ReadAll(resp.Body)
+ slurp, err := io.ReadAll(resp.Body)
if err != nil {
t.Error(err)
}
@@ -1064,7 +1063,7 @@ func testTransportGCRequest(t *testing.T, h2, body bool) {
setParallel(t)
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
- ioutil.ReadAll(r.Body)
+ io.ReadAll(r.Body)
if body {
io.WriteString(w, "Hello.")
}
@@ -1080,7 +1079,7 @@ func testTransportGCRequest(t *testing.T, h2, body bool) {
if err != nil {
t.Fatal(err)
}
- if _, err := ioutil.ReadAll(res.Body); err != nil {
+ if _, err := io.ReadAll(res.Body); err != nil {
t.Fatal(err)
}
if err := res.Body.Close(); err != nil {
@@ -1141,7 +1140,7 @@ func testTransportRejectsInvalidHeaders(t *testing.T, h2 bool) {
res, err := cst.c.Do(req)
var body []byte
if err == nil {
- body, _ = ioutil.ReadAll(res.Body)
+ body, _ = io.ReadAll(res.Body)
res.Body.Close()
}
var dialed bool
@@ -1198,7 +1197,7 @@ func testInterruptWithPanic(t *testing.T, h2 bool, panicValue interface{}) {
}
gotHeaders <- true
defer res.Body.Close()
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if string(slurp) != msg {
t.Errorf("client read %q; want %q", slurp, msg)
}
@@ -1363,7 +1362,7 @@ func testServerUndeclaredTrailers(t *testing.T, h2 bool) {
if err != nil {
t.Fatal(err)
}
- if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
+ if _, err := io.Copy(io.Discard, res.Body); err != nil {
t.Fatal(err)
}
res.Body.Close()
@@ -1381,7 +1380,7 @@ func testServerUndeclaredTrailers(t *testing.T, h2 bool) {
func TestBadResponseAfterReadingBody(t *testing.T) {
defer afterTest(t)
cst := newClientServerTest(t, false, HandlerFunc(func(w ResponseWriter, r *Request) {
- _, err := io.Copy(ioutil.Discard, r.Body)
+ _, err := io.Copy(io.Discard, r.Body)
if err != nil {
t.Fatal(err)
}
@@ -1474,7 +1473,7 @@ func testWriteHeaderAfterWrite(t *testing.T, h2, hijack bool) {
t.Fatal(err)
}
defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
diff --git a/src/net/http/doc.go b/src/net/http/doc.go
index 7855feaaa9..ae9b708c69 100644
--- a/src/net/http/doc.go
+++ b/src/net/http/doc.go
@@ -21,7 +21,7 @@ The client must close the response body when finished with it:
// handle error
}
defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
+ body, err := io.ReadAll(resp.Body)
// ...
For control over HTTP client headers, redirect policy, and other
diff --git a/src/net/http/example_test.go b/src/net/http/example_test.go
index a783b46618..c677d52238 100644
--- a/src/net/http/example_test.go
+++ b/src/net/http/example_test.go
@@ -8,7 +8,6 @@ import (
"context"
"fmt"
"io"
- "io/ioutil"
"log"
"net/http"
"os"
@@ -46,7 +45,7 @@ func ExampleGet() {
if err != nil {
log.Fatal(err)
}
- robots, err := ioutil.ReadAll(res.Body)
+ robots, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
diff --git a/src/net/http/fcgi/child.go b/src/net/http/fcgi/child.go
index 34761f32ee..e97b8440e1 100644
--- a/src/net/http/fcgi/child.go
+++ b/src/net/http/fcgi/child.go
@@ -11,7 +11,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"net"
"net/http"
"net/http/cgi"
@@ -186,7 +185,7 @@ func (c *child) serve() {
var errCloseConn = errors.New("fcgi: connection should be closed")
-var emptyBody = ioutil.NopCloser(strings.NewReader(""))
+var emptyBody = io.NopCloser(strings.NewReader(""))
// ErrRequestAborted is returned by Read when a handler attempts to read the
// body of a request that has been aborted by the web server.
@@ -325,7 +324,7 @@ func (c *child) serveRequest(req *request, body io.ReadCloser) {
// some sort of abort request to the host, so the host
// can properly cut off the client sending all the data.
// For now just bound it a little and
- io.CopyN(ioutil.Discard, body, 100<<20)
+ io.CopyN(io.Discard, body, 100<<20)
body.Close()
if !req.keepConn {
diff --git a/src/net/http/fcgi/fcgi_test.go b/src/net/http/fcgi/fcgi_test.go
index 4a27a12c35..d3b704f821 100644
--- a/src/net/http/fcgi/fcgi_test.go
+++ b/src/net/http/fcgi/fcgi_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"errors"
"io"
- "io/ioutil"
"net/http"
"strings"
"testing"
@@ -243,7 +242,7 @@ func TestChildServeCleansUp(t *testing.T) {
r *http.Request,
) {
// block on reading body of request
- _, err := io.Copy(ioutil.Discard, r.Body)
+ _, err := io.Copy(io.Discard, r.Body)
if err != tt.err {
t.Errorf("Expected %#v, got %#v", tt.err, err)
}
@@ -275,7 +274,7 @@ func TestMalformedParams(t *testing.T) {
// end of params
1, 4, 0, 1, 0, 0, 0, 0,
}
- rw := rwNopCloser{bytes.NewReader(input), ioutil.Discard}
+ rw := rwNopCloser{bytes.NewReader(input), io.Discard}
c := newChild(rw, http.DefaultServeMux)
c.serve()
}
diff --git a/src/net/http/filetransport_test.go b/src/net/http/filetransport_test.go
index 2a2f32c769..fdfd44d967 100644
--- a/src/net/http/filetransport_test.go
+++ b/src/net/http/filetransport_test.go
@@ -5,6 +5,7 @@
package http
import (
+ "io"
"io/ioutil"
"os"
"path/filepath"
@@ -48,7 +49,7 @@ func TestFileTransport(t *testing.T) {
if res.Body == nil {
t.Fatalf("for %s, nil Body", urlstr)
}
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
res.Body.Close()
check("ReadAll "+urlstr, err)
if string(slurp) != "Bar" {
diff --git a/src/net/http/fs_test.go b/src/net/http/fs_test.go
index c9f324cff6..2e4751114d 100644
--- a/src/net/http/fs_test.go
+++ b/src/net/http/fs_test.go
@@ -160,7 +160,7 @@ Cases:
if g, w := part.Header.Get("Content-Range"), wantContentRange; g != w {
t.Errorf("range=%q: part Content-Range = %q; want %q", rt.r, g, w)
}
- body, err := ioutil.ReadAll(part)
+ body, err := io.ReadAll(part)
if err != nil {
t.Errorf("range=%q, reading part index %d body: %v", rt.r, ri, err)
continue Cases
@@ -312,7 +312,7 @@ func TestFileServerEscapesNames(t *testing.T) {
if err != nil {
t.Fatalf("test %q: Get: %v", test.name, err)
}
- b, err := ioutil.ReadAll(res.Body)
+ b, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("test %q: read Body: %v", test.name, err)
}
@@ -360,7 +360,7 @@ func TestFileServerSortsNames(t *testing.T) {
}
defer res.Body.Close()
- b, err := ioutil.ReadAll(res.Body)
+ b, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("read Body: %v", err)
}
@@ -394,7 +394,7 @@ func TestFileServerImplicitLeadingSlash(t *testing.T) {
if err != nil {
t.Fatalf("Get %s: %v", suffix, err)
}
- b, err := ioutil.ReadAll(res.Body)
+ b, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("ReadAll %s: %v", suffix, err)
}
@@ -617,7 +617,7 @@ func TestServeIndexHtmlFS(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- b, err := ioutil.ReadAll(res.Body)
+ b, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal("reading Body:", err)
}
@@ -745,7 +745,7 @@ func TestDirectoryIfNotModified(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- b, err := ioutil.ReadAll(res.Body)
+ b, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -1082,7 +1082,7 @@ func TestServeContent(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- io.Copy(ioutil.Discard, res.Body)
+ io.Copy(io.Discard, res.Body)
res.Body.Close()
if res.StatusCode != tt.wantStatus {
t.Errorf("test %q using %q: got status = %d; want %d", testName, method, res.StatusCode, tt.wantStatus)
@@ -1196,7 +1196,7 @@ func TestLinuxSendfile(t *testing.T) {
if err != nil {
t.Fatalf("http client error: %v", err)
}
- _, err = io.Copy(ioutil.Discard, res.Body)
+ _, err = io.Copy(io.Discard, res.Body)
if err != nil {
t.Fatalf("client body read error: %v", err)
}
@@ -1218,7 +1218,7 @@ func getBody(t *testing.T, testName string, req Request, client *Client) (*Respo
if err != nil {
t.Fatalf("%s: for URL %q, send error: %v", testName, req.URL.String(), err)
}
- b, err := ioutil.ReadAll(r.Body)
+ b, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("%s: for URL %q, reading body: %v", testName, req.URL.String(), err)
}
@@ -1401,7 +1401,7 @@ func testServeFileRejectsInvalidSuffixLengths(t *testing.T, h2 bool) {
if g, w := res.StatusCode, tt.wantCode; g != w {
t.Errorf("StatusCode mismatch: got %d want %d", g, w)
}
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
diff --git a/src/net/http/httptest/example_test.go b/src/net/http/httptest/example_test.go
index 54e77dbb84..a6738432eb 100644
--- a/src/net/http/httptest/example_test.go
+++ b/src/net/http/httptest/example_test.go
@@ -7,7 +7,6 @@ package httptest_test
import (
"fmt"
"io"
- "io/ioutil"
"log"
"net/http"
"net/http/httptest"
@@ -23,7 +22,7 @@ func ExampleResponseRecorder() {
handler(w, req)
resp := w.Result()
- body, _ := ioutil.ReadAll(resp.Body)
+ body, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get("Content-Type"))
@@ -45,7 +44,7 @@ func ExampleServer() {
if err != nil {
log.Fatal(err)
}
- greeting, err := ioutil.ReadAll(res.Body)
+ greeting, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
@@ -67,7 +66,7 @@ func ExampleServer_hTTP2() {
if err != nil {
log.Fatal(err)
}
- greeting, err := ioutil.ReadAll(res.Body)
+ greeting, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
@@ -89,7 +88,7 @@ func ExampleNewTLSServer() {
log.Fatal(err)
}
- greeting, err := ioutil.ReadAll(res.Body)
+ greeting, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
diff --git a/src/net/http/httptest/httptest.go b/src/net/http/httptest/httptest.go
index f7202da92f..9bedefd2bc 100644
--- a/src/net/http/httptest/httptest.go
+++ b/src/net/http/httptest/httptest.go
@@ -10,7 +10,6 @@ import (
"bytes"
"crypto/tls"
"io"
- "io/ioutil"
"net/http"
"strings"
)
@@ -66,7 +65,7 @@ func NewRequest(method, target string, body io.Reader) *http.Request {
if rc, ok := body.(io.ReadCloser); ok {
req.Body = rc
} else {
- req.Body = ioutil.NopCloser(body)
+ req.Body = io.NopCloser(body)
}
}
diff --git a/src/net/http/httptest/httptest_test.go b/src/net/http/httptest/httptest_test.go
index ef7d943837..071add67ea 100644
--- a/src/net/http/httptest/httptest_test.go
+++ b/src/net/http/httptest/httptest_test.go
@@ -7,7 +7,6 @@ package httptest
import (
"crypto/tls"
"io"
- "io/ioutil"
"net/http"
"net/url"
"reflect"
@@ -155,7 +154,7 @@ func TestNewRequest(t *testing.T) {
} {
t.Run(tt.name, func(t *testing.T) {
got := NewRequest(tt.method, tt.uri, tt.body)
- slurp, err := ioutil.ReadAll(got.Body)
+ slurp, err := io.ReadAll(got.Body)
if err != nil {
t.Errorf("ReadAll: %v", err)
}
diff --git a/src/net/http/httptest/recorder.go b/src/net/http/httptest/recorder.go
index 66e67e78b3..2428482612 100644
--- a/src/net/http/httptest/recorder.go
+++ b/src/net/http/httptest/recorder.go
@@ -7,7 +7,7 @@ package httptest
import (
"bytes"
"fmt"
- "io/ioutil"
+ "io"
"net/http"
"net/textproto"
"strconv"
@@ -179,7 +179,7 @@ func (rw *ResponseRecorder) Result() *http.Response {
}
res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode))
if rw.Body != nil {
- res.Body = ioutil.NopCloser(bytes.NewReader(rw.Body.Bytes()))
+ res.Body = io.NopCloser(bytes.NewReader(rw.Body.Bytes()))
} else {
res.Body = http.NoBody
}
diff --git a/src/net/http/httptest/recorder_test.go b/src/net/http/httptest/recorder_test.go
index e9534894b6..a865e878b9 100644
--- a/src/net/http/httptest/recorder_test.go
+++ b/src/net/http/httptest/recorder_test.go
@@ -7,7 +7,6 @@ package httptest
import (
"fmt"
"io"
- "io/ioutil"
"net/http"
"testing"
)
@@ -42,7 +41,7 @@ func TestRecorder(t *testing.T) {
}
hasResultContents := func(want string) checkFunc {
return func(rec *ResponseRecorder) error {
- contentBytes, err := ioutil.ReadAll(rec.Result().Body)
+ contentBytes, err := io.ReadAll(rec.Result().Body)
if err != nil {
return err
}
diff --git a/src/net/http/httptest/server_test.go b/src/net/http/httptest/server_test.go
index 0aad15c5ed..39568b358c 100644
--- a/src/net/http/httptest/server_test.go
+++ b/src/net/http/httptest/server_test.go
@@ -6,7 +6,7 @@ package httptest
import (
"bufio"
- "io/ioutil"
+ "io"
"net"
"net/http"
"testing"
@@ -61,7 +61,7 @@ func testServer(t *testing.T, newServer newServerFunc) {
if err != nil {
t.Fatal(err)
}
- got, err := ioutil.ReadAll(res.Body)
+ got, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
@@ -81,7 +81,7 @@ func testGetAfterClose(t *testing.T, newServer newServerFunc) {
if err != nil {
t.Fatal(err)
}
- got, err := ioutil.ReadAll(res.Body)
+ got, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -93,7 +93,7 @@ func testGetAfterClose(t *testing.T, newServer newServerFunc) {
res, err = http.Get(ts.URL)
if err == nil {
- body, _ := ioutil.ReadAll(res.Body)
+ body, _ := io.ReadAll(res.Body)
t.Fatalf("Unexpected response after close: %v, %v, %s", res.Status, res.Header, body)
}
}
@@ -152,7 +152,7 @@ func testServerClient(t *testing.T, newTLSServer newServerFunc) {
if err != nil {
t.Fatal(err)
}
- got, err := ioutil.ReadAll(res.Body)
+ got, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
diff --git a/src/net/http/httputil/dump.go b/src/net/http/httputil/dump.go
index c97be066d7..4c9d28bed8 100644
--- a/src/net/http/httputil/dump.go
+++ b/src/net/http/httputil/dump.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"net"
"net/http"
"net/url"
@@ -35,7 +34,7 @@ func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {
if err = b.Close(); err != nil {
return nil, b, err
}
- return ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil
+ return io.NopCloser(&buf), io.NopCloser(bytes.NewReader(buf.Bytes())), nil
}
// dumpConn is a net.Conn which writes to Writer and reads from Reader
@@ -81,7 +80,7 @@ func DumpRequestOut(req *http.Request, body bool) ([]byte, error) {
if !body {
contentLength := outgoingLength(req)
if contentLength != 0 {
- req.Body = ioutil.NopCloser(io.LimitReader(neverEnding('x'), contentLength))
+ req.Body = io.NopCloser(io.LimitReader(neverEnding('x'), contentLength))
dummyBody = true
}
} else {
@@ -133,7 +132,7 @@ func DumpRequestOut(req *http.Request, body bool) ([]byte, error) {
if err == nil {
// Ensure all the body is read; otherwise
// we'll get a partial dump.
- io.Copy(ioutil.Discard, req.Body)
+ io.Copy(io.Discard, req.Body)
req.Body.Close()
}
select {
@@ -296,7 +295,7 @@ func (failureToReadBody) Read([]byte) (int, error) { return 0, errNoBody }
func (failureToReadBody) Close() error { return nil }
// emptyBody is an instance of empty reader.
-var emptyBody = ioutil.NopCloser(strings.NewReader(""))
+var emptyBody = io.NopCloser(strings.NewReader(""))
// DumpResponse is like DumpRequest but dumps a response.
func DumpResponse(resp *http.Response, body bool) ([]byte, error) {
diff --git a/src/net/http/httputil/dump_test.go b/src/net/http/httputil/dump_test.go
index ead56bc172..7571eb0820 100644
--- a/src/net/http/httputil/dump_test.go
+++ b/src/net/http/httputil/dump_test.go
@@ -9,7 +9,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"net/http"
"net/url"
"runtime"
@@ -268,7 +267,7 @@ func TestDumpRequest(t *testing.T) {
}
switch b := ti.Body.(type) {
case []byte:
- req.Body = ioutil.NopCloser(bytes.NewReader(b))
+ req.Body = io.NopCloser(bytes.NewReader(b))
case func() io.ReadCloser:
req.Body = b()
default:
@@ -363,7 +362,7 @@ var dumpResTests = []struct {
Header: http.Header{
"Foo": []string{"Bar"},
},
- Body: ioutil.NopCloser(strings.NewReader("foo")), // shouldn't be used
+ Body: io.NopCloser(strings.NewReader("foo")), // shouldn't be used
},
body: false, // to verify we see 50, not empty or 3.
want: `HTTP/1.1 200 OK
@@ -379,7 +378,7 @@ Foo: Bar`,
ProtoMajor: 1,
ProtoMinor: 1,
ContentLength: 3,
- Body: ioutil.NopCloser(strings.NewReader("foo")),
+ Body: io.NopCloser(strings.NewReader("foo")),
},
body: true,
want: `HTTP/1.1 200 OK
@@ -396,7 +395,7 @@ foo`,
ProtoMajor: 1,
ProtoMinor: 1,
ContentLength: -1,
- Body: ioutil.NopCloser(strings.NewReader("foo")),
+ Body: io.NopCloser(strings.NewReader("foo")),
TransferEncoding: []string{"chunked"},
},
body: true,
diff --git a/src/net/http/httputil/example_test.go b/src/net/http/httputil/example_test.go
index 6191603674..b77a243ca3 100644
--- a/src/net/http/httputil/example_test.go
+++ b/src/net/http/httputil/example_test.go
@@ -6,7 +6,7 @@ package httputil_test
import (
"fmt"
- "io/ioutil"
+ "io"
"log"
"net/http"
"net/http/httptest"
@@ -39,7 +39,7 @@ func ExampleDumpRequest() {
}
defer resp.Body.Close()
- b, err := ioutil.ReadAll(resp.Body)
+ b, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
@@ -111,7 +111,7 @@ func ExampleReverseProxy() {
log.Fatal(err)
}
- b, err := ioutil.ReadAll(resp.Body)
+ b, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
diff --git a/src/net/http/httputil/reverseproxy_test.go b/src/net/http/httputil/reverseproxy_test.go
index cc05d55d87..3acbd940e4 100644
--- a/src/net/http/httputil/reverseproxy_test.go
+++ b/src/net/http/httputil/reverseproxy_test.go
@@ -13,7 +13,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"log"
"net/http"
"net/http/httptest"
@@ -84,7 +83,7 @@ func TestReverseProxy(t *testing.T) {
t.Fatal(err)
}
proxyHandler := NewSingleHostReverseProxy(backendURL)
- proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
frontend := httptest.NewServer(proxyHandler)
defer frontend.Close()
frontendClient := frontend.Client()
@@ -124,7 +123,7 @@ func TestReverseProxy(t *testing.T) {
if cookie := res.Cookies()[0]; cookie.Name != "flavor" {
t.Errorf("unexpected cookie %q", cookie.Name)
}
- bodyBytes, _ := ioutil.ReadAll(res.Body)
+ bodyBytes, _ := io.ReadAll(res.Body)
if g, e := string(bodyBytes), backendResponse; g != e {
t.Errorf("got body %q; expected %q", g, e)
}
@@ -218,7 +217,7 @@ func TestReverseProxyStripHeadersPresentInConnection(t *testing.T) {
t.Fatalf("Get: %v", err)
}
defer res.Body.Close()
- bodyBytes, err := ioutil.ReadAll(res.Body)
+ bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("reading body: %v", err)
}
@@ -271,7 +270,7 @@ func TestXForwardedFor(t *testing.T) {
if g, e := res.StatusCode, backendStatus; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
- bodyBytes, _ := ioutil.ReadAll(res.Body)
+ bodyBytes, _ := io.ReadAll(res.Body)
if g, e := string(bodyBytes), backendResponse; g != e {
t.Errorf("got body %q; expected %q", g, e)
}
@@ -373,7 +372,7 @@ func TestReverseProxyFlushInterval(t *testing.T) {
t.Fatalf("Get: %v", err)
}
defer res.Body.Close()
- if bodyBytes, _ := ioutil.ReadAll(res.Body); string(bodyBytes) != expected {
+ if bodyBytes, _ := io.ReadAll(res.Body); string(bodyBytes) != expected {
t.Errorf("got body %q; expected %q", bodyBytes, expected)
}
}
@@ -441,7 +440,7 @@ func TestReverseProxyCancellation(t *testing.T) {
defer backend.Close()
- backend.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
+ backend.Config.ErrorLog = log.New(io.Discard, "", 0)
backendURL, err := url.Parse(backend.URL)
if err != nil {
@@ -452,7 +451,7 @@ func TestReverseProxyCancellation(t *testing.T) {
// Discards errors of the form:
// http: proxy error: read tcp 127.0.0.1:44643: use of closed network connection
- proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0)
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0)
frontend := httptest.NewServer(proxyHandler)
defer frontend.Close()
@@ -504,7 +503,7 @@ func TestNilBody(t *testing.T) {
t.Fatal(err)
}
defer res.Body.Close()
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -533,7 +532,7 @@ func TestUserAgentHeader(t *testing.T) {
t.Fatal(err)
}
proxyHandler := NewSingleHostReverseProxy(backendURL)
- proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
frontend := httptest.NewServer(proxyHandler)
defer frontend.Close()
frontendClient := frontend.Client()
@@ -606,7 +605,7 @@ func TestReverseProxyGetPutBuffer(t *testing.T) {
if err != nil {
t.Fatalf("Get: %v", err)
}
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatalf("reading body: %v", err)
@@ -627,7 +626,7 @@ func TestReverseProxy_Post(t *testing.T) {
const backendStatus = 200
var requestBody = bytes.Repeat([]byte("a"), 1<<20)
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- slurp, err := ioutil.ReadAll(r.Body)
+ slurp, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Backend body read = %v", err)
}
@@ -656,7 +655,7 @@ func TestReverseProxy_Post(t *testing.T) {
if g, e := res.StatusCode, backendStatus; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
- bodyBytes, _ := ioutil.ReadAll(res.Body)
+ bodyBytes, _ := io.ReadAll(res.Body)
if g, e := string(bodyBytes), backendResponse; g != e {
t.Errorf("got body %q; expected %q", g, e)
}
@@ -672,7 +671,7 @@ func (fn RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error)
func TestReverseProxy_NilBody(t *testing.T) {
backendURL, _ := url.Parse("http://fake.tld/")
proxyHandler := NewSingleHostReverseProxy(backendURL)
- proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
proxyHandler.Transport = RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
if req.Body != nil {
t.Error("Body != nil; want a nil Body")
@@ -695,8 +694,8 @@ func TestReverseProxy_NilBody(t *testing.T) {
// Issue 33142: always allocate the request headers
func TestReverseProxy_AllocatedHeader(t *testing.T) {
proxyHandler := new(ReverseProxy)
- proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
- proxyHandler.Director = func(*http.Request) {} // noop
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ proxyHandler.Director = func(*http.Request) {} // noop
proxyHandler.Transport = RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
if req.Header == nil {
t.Error("Header == nil; want a non-nil Header")
@@ -722,7 +721,7 @@ func TestReverseProxyModifyResponse(t *testing.T) {
rpURL, _ := url.Parse(backendServer.URL)
rproxy := NewSingleHostReverseProxy(rpURL)
- rproxy.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
+ rproxy.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
rproxy.ModifyResponse = func(resp *http.Response) error {
if resp.Header.Get("X-Hit-Mod") != "true" {
return fmt.Errorf("tried to by-pass proxy")
@@ -821,7 +820,7 @@ func TestReverseProxyErrorHandler(t *testing.T) {
if rproxy.Transport == nil {
rproxy.Transport = failingRoundTripper{}
}
- rproxy.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
+ rproxy.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
if tt.errorHandler != nil {
rproxy.ErrorHandler = tt.errorHandler
}
@@ -896,7 +895,7 @@ func (t *staticTransport) RoundTrip(r *http.Request) (*http.Response, error) {
func BenchmarkServeHTTP(b *testing.B) {
res := &http.Response{
StatusCode: 200,
- Body: ioutil.NopCloser(strings.NewReader("")),
+ Body: io.NopCloser(strings.NewReader("")),
}
proxy := &ReverseProxy{
Director: func(*http.Request) {},
@@ -953,7 +952,7 @@ func TestServeHTTPDeepCopy(t *testing.T) {
// Issue 18327: verify we always do a deep copy of the Request.Header map
// before any mutations.
func TestClonesRequestHeaders(t *testing.T) {
- log.SetOutput(ioutil.Discard)
+ log.SetOutput(io.Discard)
defer log.SetOutput(os.Stderr)
req, _ := http.NewRequest("GET", "http://foo.tld/", nil)
req.RemoteAddr = "1.2.3.4:56789"
@@ -1031,7 +1030,7 @@ func (cc *checkCloser) Read(b []byte) (int, error) {
// Issue 23643: panic on body copy error
func TestReverseProxy_PanicBodyError(t *testing.T) {
- log.SetOutput(ioutil.Discard)
+ log.SetOutput(io.Discard)
defer log.SetOutput(os.Stderr)
backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
out := "this call was relayed by the reverse proxy"
@@ -1148,7 +1147,7 @@ func TestReverseProxyWebSocket(t *testing.T) {
backURL, _ := url.Parse(backendServer.URL)
rproxy := NewSingleHostReverseProxy(backURL)
- rproxy.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
+ rproxy.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
rproxy.ModifyResponse = func(res *http.Response) error {
res.Header.Add("X-Modified", "true")
return nil
@@ -1265,7 +1264,7 @@ func TestReverseProxyWebSocketCancelation(t *testing.T) {
backendURL, _ := url.Parse(cst.URL)
rproxy := NewSingleHostReverseProxy(backendURL)
- rproxy.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
+ rproxy.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
rproxy.ModifyResponse = func(res *http.Response) error {
res.Header.Add("X-Modified", "true")
return nil
@@ -1352,7 +1351,7 @@ func TestUnannouncedTrailer(t *testing.T) {
t.Fatal(err)
}
proxyHandler := NewSingleHostReverseProxy(backendURL)
- proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
frontend := httptest.NewServer(proxyHandler)
defer frontend.Close()
frontendClient := frontend.Client()
@@ -1362,7 +1361,7 @@ func TestUnannouncedTrailer(t *testing.T) {
t.Fatalf("Get: %v", err)
}
- ioutil.ReadAll(res.Body)
+ io.ReadAll(res.Body)
if g, w := res.Trailer.Get("X-Unannounced-Trailer"), "unannounced_trailer_value"; g != w {
t.Errorf("Trailer(X-Unannounced-Trailer) = %q; want %q", g, w)
diff --git a/src/net/http/internal/chunked_test.go b/src/net/http/internal/chunked_test.go
index d06716591a..08152ed1e2 100644
--- a/src/net/http/internal/chunked_test.go
+++ b/src/net/http/internal/chunked_test.go
@@ -9,7 +9,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"strings"
"testing"
)
@@ -29,7 +28,7 @@ func TestChunk(t *testing.T) {
}
r := NewChunkedReader(&b)
- data, err := ioutil.ReadAll(r)
+ data, err := io.ReadAll(r)
if err != nil {
t.Logf(`data: "%s"`, data)
t.Fatalf("ReadAll from reader: %v", err)
@@ -177,7 +176,7 @@ func TestChunkReadingIgnoresExtensions(t *testing.T) {
"17;someext\r\n" + // token without value
"world! 0123456789abcdef\r\n" +
"0;someextension=sometoken\r\n" // token=token
- data, err := ioutil.ReadAll(NewChunkedReader(strings.NewReader(in)))
+ data, err := io.ReadAll(NewChunkedReader(strings.NewReader(in)))
if err != nil {
t.Fatalf("ReadAll = %q, %v", data, err)
}
diff --git a/src/net/http/main_test.go b/src/net/http/main_test.go
index 35cc80977c..6564627998 100644
--- a/src/net/http/main_test.go
+++ b/src/net/http/main_test.go
@@ -6,7 +6,7 @@ package http_test
import (
"fmt"
- "io/ioutil"
+ "io"
"log"
"net/http"
"os"
@@ -17,7 +17,7 @@ import (
"time"
)
-var quietLog = log.New(ioutil.Discard, "", 0)
+var quietLog = log.New(io.Discard, "", 0)
func TestMain(m *testing.M) {
v := m.Run()
diff --git a/src/net/http/pprof/pprof_test.go b/src/net/http/pprof/pprof_test.go
index f6f9ef5b04..84757e401a 100644
--- a/src/net/http/pprof/pprof_test.go
+++ b/src/net/http/pprof/pprof_test.go
@@ -8,7 +8,7 @@ import (
"bytes"
"fmt"
"internal/profile"
- "io/ioutil"
+ "io"
"net/http"
"net/http/httptest"
"runtime"
@@ -63,7 +63,7 @@ func TestHandlers(t *testing.T) {
t.Errorf("status code: got %d; want %d", got, want)
}
- body, err := ioutil.ReadAll(resp.Body)
+ body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("when reading response body, expected non-nil err; got %v", err)
}
@@ -227,7 +227,7 @@ func query(endpoint string) (*profile.Profile, error) {
return nil, fmt.Errorf("failed to fetch %q: %v", url, r.Status)
}
- b, err := ioutil.ReadAll(r.Body)
+ b, err := io.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return nil, fmt.Errorf("failed to read and parse the result from %q: %v", url, err)
diff --git a/src/net/http/readrequest_test.go b/src/net/http/readrequest_test.go
index b227bb6d38..1950f4907a 100644
--- a/src/net/http/readrequest_test.go
+++ b/src/net/http/readrequest_test.go
@@ -9,7 +9,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"net/url"
"reflect"
"strings"
@@ -468,7 +467,7 @@ func TestReadRequest_Bad(t *testing.T) {
for _, tt := range badRequestTests {
got, err := ReadRequest(bufio.NewReader(bytes.NewReader(tt.req)))
if err == nil {
- all, err := ioutil.ReadAll(got.Body)
+ all, err := io.ReadAll(got.Body)
t.Errorf("%s: got unexpected request = %#v\n Body = %q, %v", tt.name, got, all, err)
}
}
diff --git a/src/net/http/request.go b/src/net/http/request.go
index df73d5f62d..adba5406e9 100644
--- a/src/net/http/request.go
+++ b/src/net/http/request.go
@@ -15,7 +15,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"mime"
"mime/multipart"
"net"
@@ -870,7 +869,7 @@ func NewRequestWithContext(ctx context.Context, method, url string, body io.Read
}
rc, ok := body.(io.ReadCloser)
if !ok && body != nil {
- rc = ioutil.NopCloser(body)
+ rc = io.NopCloser(body)
}
// The host's colon:port should be normalized. See Issue 14836.
u.Host = removeEmptyPort(u.Host)
@@ -892,21 +891,21 @@ func NewRequestWithContext(ctx context.Context, method, url string, body io.Read
buf := v.Bytes()
req.GetBody = func() (io.ReadCloser, error) {
r := bytes.NewReader(buf)
- return ioutil.NopCloser(r), nil
+ return io.NopCloser(r), nil
}
case *bytes.Reader:
req.ContentLength = int64(v.Len())
snapshot := *v
req.GetBody = func() (io.ReadCloser, error) {
r := snapshot
- return ioutil.NopCloser(&r), nil
+ return io.NopCloser(&r), nil
}
case *strings.Reader:
req.ContentLength = int64(v.Len())
snapshot := *v
req.GetBody = func() (io.ReadCloser, error) {
r := snapshot
- return ioutil.NopCloser(&r), nil
+ return io.NopCloser(&r), nil
}
default:
// This is where we'd set it to -1 (at least
@@ -1205,7 +1204,7 @@ func parsePostForm(r *Request) (vs url.Values, err error) {
maxFormSize = int64(10 << 20) // 10 MB is a lot of text.
reader = io.LimitReader(r.Body, maxFormSize+1)
}
- b, e := ioutil.ReadAll(reader)
+ b, e := io.ReadAll(reader)
if e != nil {
if err == nil {
err = e
diff --git a/src/net/http/request_test.go b/src/net/http/request_test.go
index 461d66e05d..b4ef472e71 100644
--- a/src/net/http/request_test.go
+++ b/src/net/http/request_test.go
@@ -103,7 +103,7 @@ func TestParseFormUnknownContentType(t *testing.T) {
req := &Request{
Method: "POST",
Header: test.contentType,
- Body: ioutil.NopCloser(strings.NewReader("body")),
+ Body: io.NopCloser(strings.NewReader("body")),
}
err := req.ParseForm()
switch {
@@ -150,7 +150,7 @@ func TestMultipartReader(t *testing.T) {
req := &Request{
Method: "POST",
Header: Header{"Content-Type": {test.contentType}},
- Body: ioutil.NopCloser(new(bytes.Buffer)),
+ Body: io.NopCloser(new(bytes.Buffer)),
}
multipart, err := req.MultipartReader()
if test.shouldError {
@@ -187,7 +187,7 @@ binary data
req := &Request{
Method: "POST",
Header: Header{"Content-Type": {`multipart/form-data; boundary=xxx`}},
- Body: ioutil.NopCloser(strings.NewReader(postData)),
+ Body: io.NopCloser(strings.NewReader(postData)),
}
initialFormItems := map[string]string{
@@ -231,7 +231,7 @@ func TestParseMultipartForm(t *testing.T) {
req := &Request{
Method: "POST",
Header: Header{"Content-Type": {`multipart/form-data; boundary="foo123"`}},
- Body: ioutil.NopCloser(new(bytes.Buffer)),
+ Body: io.NopCloser(new(bytes.Buffer)),
}
err := req.ParseMultipartForm(25)
if err == nil {
@@ -756,10 +756,10 @@ func (dr delayedEOFReader) Read(p []byte) (n int, err error) {
}
func TestIssue10884_MaxBytesEOF(t *testing.T) {
- dst := ioutil.Discard
+ dst := io.Discard
_, err := io.Copy(dst, MaxBytesReader(
responseWriterJustWriter{dst},
- ioutil.NopCloser(delayedEOFReader{strings.NewReader("12345")}),
+ io.NopCloser(delayedEOFReader{strings.NewReader("12345")}),
5))
if err != nil {
t.Fatal(err)
@@ -799,7 +799,7 @@ func TestMaxBytesReaderStickyError(t *testing.T) {
2: {101, 100},
}
for i, tt := range tests {
- rc := MaxBytesReader(nil, ioutil.NopCloser(bytes.NewReader(make([]byte, tt.readable))), tt.limit)
+ rc := MaxBytesReader(nil, io.NopCloser(bytes.NewReader(make([]byte, tt.readable))), tt.limit)
if err := isSticky(rc); err != nil {
t.Errorf("%d. error: %v", i, err)
}
@@ -900,7 +900,7 @@ func TestNewRequestGetBody(t *testing.T) {
t.Errorf("test[%d]: GetBody = nil", i)
continue
}
- slurp1, err := ioutil.ReadAll(req.Body)
+ slurp1, err := io.ReadAll(req.Body)
if err != nil {
t.Errorf("test[%d]: ReadAll(Body) = %v", i, err)
}
@@ -908,7 +908,7 @@ func TestNewRequestGetBody(t *testing.T) {
if err != nil {
t.Errorf("test[%d]: GetBody = %v", i, err)
}
- slurp2, err := ioutil.ReadAll(newBody)
+ slurp2, err := io.ReadAll(newBody)
if err != nil {
t.Errorf("test[%d]: ReadAll(GetBody()) = %v", i, err)
}
@@ -1145,7 +1145,7 @@ func benchmarkFileAndServer(b *testing.B, n int64) {
func runFileAndServerBenchmarks(b *testing.B, tlsOption bool, f *os.File, n int64) {
handler := HandlerFunc(func(rw ResponseWriter, req *Request) {
defer req.Body.Close()
- nc, err := io.Copy(ioutil.Discard, req.Body)
+ nc, err := io.Copy(io.Discard, req.Body)
if err != nil {
panic(err)
}
@@ -1172,7 +1172,7 @@ func runFileAndServerBenchmarks(b *testing.B, tlsOption bool, f *os.File, n int6
}
b.StartTimer()
- req, err := NewRequest("PUT", cst.URL, ioutil.NopCloser(f))
+ req, err := NewRequest("PUT", cst.URL, io.NopCloser(f))
if err != nil {
b.Fatal(err)
}
diff --git a/src/net/http/requestwrite_test.go b/src/net/http/requestwrite_test.go
index 9ac6701cfd..1157bdfff9 100644
--- a/src/net/http/requestwrite_test.go
+++ b/src/net/http/requestwrite_test.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"net"
"net/url"
"strings"
@@ -229,7 +228,7 @@ var reqWriteTests = []reqWriteTest{
ContentLength: 0, // as if unset by user
},
- Body: func() io.ReadCloser { return ioutil.NopCloser(io.LimitReader(strings.NewReader("xx"), 0)) },
+ Body: func() io.ReadCloser { return io.NopCloser(io.LimitReader(strings.NewReader("xx"), 0)) },
WantWrite: "POST / HTTP/1.1\r\n" +
"Host: example.com\r\n" +
@@ -281,7 +280,7 @@ var reqWriteTests = []reqWriteTest{
ContentLength: 0, // as if unset by user
},
- Body: func() io.ReadCloser { return ioutil.NopCloser(io.LimitReader(strings.NewReader("xx"), 1)) },
+ Body: func() io.ReadCloser { return io.NopCloser(io.LimitReader(strings.NewReader("xx"), 1)) },
WantWrite: "POST / HTTP/1.1\r\n" +
"Host: example.com\r\n" +
@@ -351,7 +350,7 @@ var reqWriteTests = []reqWriteTest{
Body: func() io.ReadCloser {
err := errors.New("Custom reader error")
errReader := iotest.ErrReader(err)
- return ioutil.NopCloser(io.MultiReader(strings.NewReader("x"), errReader))
+ return io.NopCloser(io.MultiReader(strings.NewReader("x"), errReader))
},
WantError: errors.New("Custom reader error"),
@@ -371,7 +370,7 @@ var reqWriteTests = []reqWriteTest{
Body: func() io.ReadCloser {
err := errors.New("Custom reader error")
errReader := iotest.ErrReader(err)
- return ioutil.NopCloser(errReader)
+ return io.NopCloser(errReader)
},
WantError: errors.New("Custom reader error"),
@@ -620,7 +619,7 @@ func TestRequestWrite(t *testing.T) {
}
switch b := tt.Body.(type) {
case []byte:
- tt.Req.Body = ioutil.NopCloser(bytes.NewReader(b))
+ tt.Req.Body = io.NopCloser(bytes.NewReader(b))
case func() io.ReadCloser:
tt.Req.Body = b()
}
@@ -716,20 +715,20 @@ func TestRequestWriteTransport(t *testing.T) {
},
{
method: "GET",
- body: ioutil.NopCloser(strings.NewReader("")),
+ body: io.NopCloser(strings.NewReader("")),
want: noContentLengthOrTransferEncoding,
},
{
method: "GET",
clen: -1,
- body: ioutil.NopCloser(strings.NewReader("")),
+ body: io.NopCloser(strings.NewReader("")),
want: noContentLengthOrTransferEncoding,
},
// A GET with a body, with explicit content length:
{
method: "GET",
clen: 7,
- body: ioutil.NopCloser(strings.NewReader("foobody")),
+ body: io.NopCloser(strings.NewReader("foobody")),
want: all(matchSubstr("Content-Length: 7"),
matchSubstr("foobody")),
},
@@ -737,7 +736,7 @@ func TestRequestWriteTransport(t *testing.T) {
{
method: "GET",
clen: -1,
- body: ioutil.NopCloser(strings.NewReader("foobody")),
+ body: io.NopCloser(strings.NewReader("foobody")),
want: all(matchSubstr("Transfer-Encoding: chunked"),
matchSubstr("\r\n1\r\nf\r\n"),
matchSubstr("oobody")),
@@ -747,14 +746,14 @@ func TestRequestWriteTransport(t *testing.T) {
{
method: "POST",
clen: -1,
- body: ioutil.NopCloser(strings.NewReader("foobody")),
+ body: io.NopCloser(strings.NewReader("foobody")),
want: all(matchSubstr("Transfer-Encoding: chunked"),
matchSubstr("foobody")),
},
{
method: "POST",
clen: -1,
- body: ioutil.NopCloser(strings.NewReader("")),
+ body: io.NopCloser(strings.NewReader("")),
want: all(matchSubstr("Transfer-Encoding: chunked")),
},
// Verify that a blocking Request.Body doesn't block forever.
@@ -766,7 +765,7 @@ func TestRequestWriteTransport(t *testing.T) {
tt.afterReqRead = func() {
pw.Close()
}
- tt.body = ioutil.NopCloser(pr)
+ tt.body = io.NopCloser(pr)
},
want: matchSubstr("Transfer-Encoding: chunked"),
},
@@ -937,7 +936,7 @@ func dumpRequestOut(req *Request, onReadHeaders func()) ([]byte, error) {
}
// Ensure all the body is read; otherwise
// we'll get a partial dump.
- io.Copy(ioutil.Discard, req.Body)
+ io.Copy(io.Discard, req.Body)
req.Body.Close()
}
dr.c <- strings.NewReader("HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n")
diff --git a/src/net/http/response_test.go b/src/net/http/response_test.go
index ce872606b1..8eef65474e 100644
--- a/src/net/http/response_test.go
+++ b/src/net/http/response_test.go
@@ -12,7 +12,6 @@ import (
"fmt"
"go/token"
"io"
- "io/ioutil"
"net/http/internal"
"net/url"
"reflect"
@@ -620,7 +619,7 @@ func TestWriteResponse(t *testing.T) {
t.Errorf("#%d: %v", i, err)
continue
}
- err = resp.Write(ioutil.Discard)
+ err = resp.Write(io.Discard)
if err != nil {
t.Errorf("#%d: %v", i, err)
continue
@@ -722,7 +721,7 @@ func TestReadResponseCloseInMiddle(t *testing.T) {
}
resp.Body.Close()
- rest, err := ioutil.ReadAll(bufr)
+ rest, err := io.ReadAll(bufr)
checkErr(err, "ReadAll on remainder")
if e, g := "Next Request Here", string(rest); e != g {
g = regexp.MustCompile(`(xx+)`).ReplaceAllStringFunc(g, func(match string) string {
diff --git a/src/net/http/responsewrite_test.go b/src/net/http/responsewrite_test.go
index d41d89896e..1cc87b942e 100644
--- a/src/net/http/responsewrite_test.go
+++ b/src/net/http/responsewrite_test.go
@@ -6,7 +6,7 @@ package http
import (
"bytes"
- "io/ioutil"
+ "io"
"strings"
"testing"
)
@@ -26,7 +26,7 @@ func TestResponseWrite(t *testing.T) {
ProtoMinor: 0,
Request: dummyReq("GET"),
Header: Header{},
- Body: ioutil.NopCloser(strings.NewReader("abcdef")),
+ Body: io.NopCloser(strings.NewReader("abcdef")),
ContentLength: 6,
},
@@ -42,7 +42,7 @@ func TestResponseWrite(t *testing.T) {
ProtoMinor: 0,
Request: dummyReq("GET"),
Header: Header{},
- Body: ioutil.NopCloser(strings.NewReader("abcdef")),
+ Body: io.NopCloser(strings.NewReader("abcdef")),
ContentLength: -1,
},
"HTTP/1.0 200 OK\r\n" +
@@ -57,7 +57,7 @@ func TestResponseWrite(t *testing.T) {
ProtoMinor: 1,
Request: dummyReq("GET"),
Header: Header{},
- Body: ioutil.NopCloser(strings.NewReader("abcdef")),
+ Body: io.NopCloser(strings.NewReader("abcdef")),
ContentLength: -1,
Close: true,
},
@@ -74,7 +74,7 @@ func TestResponseWrite(t *testing.T) {
ProtoMinor: 1,
Request: dummyReq11("GET"),
Header: Header{},
- Body: ioutil.NopCloser(strings.NewReader("abcdef")),
+ Body: io.NopCloser(strings.NewReader("abcdef")),
ContentLength: -1,
Close: false,
},
@@ -92,7 +92,7 @@ func TestResponseWrite(t *testing.T) {
ProtoMinor: 1,
Request: dummyReq11("GET"),
Header: Header{},
- Body: ioutil.NopCloser(strings.NewReader("abcdef")),
+ Body: io.NopCloser(strings.NewReader("abcdef")),
ContentLength: -1,
TransferEncoding: []string{"chunked"},
Close: false,
@@ -125,7 +125,7 @@ func TestResponseWrite(t *testing.T) {
ProtoMinor: 1,
Request: dummyReq11("GET"),
Header: Header{},
- Body: ioutil.NopCloser(strings.NewReader("")),
+ Body: io.NopCloser(strings.NewReader("")),
ContentLength: 0,
Close: false,
},
@@ -141,7 +141,7 @@ func TestResponseWrite(t *testing.T) {
ProtoMinor: 1,
Request: dummyReq11("GET"),
Header: Header{},
- Body: ioutil.NopCloser(strings.NewReader("foo")),
+ Body: io.NopCloser(strings.NewReader("foo")),
ContentLength: 0,
Close: false,
},
@@ -157,7 +157,7 @@ func TestResponseWrite(t *testing.T) {
ProtoMinor: 1,
Request: dummyReq("GET"),
Header: Header{},
- Body: ioutil.NopCloser(strings.NewReader("abcdef")),
+ Body: io.NopCloser(strings.NewReader("abcdef")),
ContentLength: 6,
TransferEncoding: []string{"chunked"},
Close: true,
@@ -218,7 +218,7 @@ func TestResponseWrite(t *testing.T) {
Request: &Request{Method: "POST"},
Header: Header{},
ContentLength: -1,
- Body: ioutil.NopCloser(strings.NewReader("abcdef")),
+ Body: io.NopCloser(strings.NewReader("abcdef")),
},
"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nabcdef",
},
diff --git a/src/net/http/roundtrip_js.go b/src/net/http/roundtrip_js.go
index b09923c386..c6a221ac62 100644
--- a/src/net/http/roundtrip_js.go
+++ b/src/net/http/roundtrip_js.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"strconv"
"syscall/js"
)
@@ -92,7 +91,7 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) {
// See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
// See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
// and browser support.
- body, err := ioutil.ReadAll(req.Body)
+ body, err := io.ReadAll(req.Body)
if err != nil {
req.Body.Close() // RoundTrip must always close the body, including on errors.
return nil, err
diff --git a/src/net/http/serve_test.go b/src/net/http/serve_test.go
index d84804c2e9..ba54b31a29 100644
--- a/src/net/http/serve_test.go
+++ b/src/net/http/serve_test.go
@@ -18,7 +18,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"log"
"math/rand"
"net"
@@ -529,7 +528,7 @@ func TestServeWithSlashRedirectKeepsQueryString(t *testing.T) {
if err != nil {
continue
}
- slurp, _ := ioutil.ReadAll(res.Body)
+ slurp, _ := io.ReadAll(res.Body)
res.Body.Close()
if !tt.statusOk {
if got, want := res.StatusCode, 404; got != want {
@@ -689,7 +688,7 @@ func testServerTimeouts(timeout time.Duration) error {
if err != nil {
return fmt.Errorf("http Get #1: %v", err)
}
- got, err := ioutil.ReadAll(r.Body)
+ got, err := io.ReadAll(r.Body)
expected := "req=1"
if string(got) != expected || err != nil {
return fmt.Errorf("Unexpected response for request #1; got %q ,%v; expected %q, nil",
@@ -721,7 +720,7 @@ func testServerTimeouts(timeout time.Duration) error {
if err != nil {
return fmt.Errorf("http Get #2: %v", err)
}
- got, err = ioutil.ReadAll(r.Body)
+ got, err = io.ReadAll(r.Body)
r.Body.Close()
expected = "req=2"
if string(got) != expected || err != nil {
@@ -734,7 +733,7 @@ func testServerTimeouts(timeout time.Duration) error {
return fmt.Errorf("long Dial: %v", err)
}
defer conn.Close()
- go io.Copy(ioutil.Discard, conn)
+ go io.Copy(io.Discard, conn)
for i := 0; i < 5; i++ {
_, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"))
if err != nil {
@@ -954,7 +953,7 @@ func TestOnlyWriteTimeout(t *testing.T) {
errc <- err
return
}
- _, err = io.Copy(ioutil.Discard, res.Body)
+ _, err = io.Copy(io.Discard, res.Body)
res.Body.Close()
errc <- err
}()
@@ -1058,7 +1057,7 @@ func TestIdentityResponse(t *testing.T) {
}
// The ReadAll will hang for a failing test.
- got, _ := ioutil.ReadAll(conn)
+ got, _ := io.ReadAll(conn)
expectedSuffix := "\r\n\r\ntoo short"
if !strings.HasSuffix(string(got), expectedSuffix) {
t.Errorf("Expected output to end with %q; got response body %q",
@@ -1099,7 +1098,7 @@ func testTCPConnectionCloses(t *testing.T, req string, h Handler) {
}
}()
- _, err = ioutil.ReadAll(r)
+ _, err = io.ReadAll(r)
if err != nil {
t.Fatal("read error:", err)
}
@@ -1129,7 +1128,7 @@ func testTCPConnectionStaysOpen(t *testing.T, req string, handler Handler) {
if err != nil {
t.Fatalf("res %d: %v", i+1, err)
}
- if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
+ if _, err := io.Copy(io.Discard, res.Body); err != nil {
t.Fatalf("res %d body copy: %v", i+1, err)
}
res.Body.Close()
@@ -1235,7 +1234,7 @@ func testSetsRemoteAddr(t *testing.T, h2 bool) {
if err != nil {
t.Fatalf("Get error: %v", err)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("ReadAll error: %v", err)
}
@@ -1299,7 +1298,7 @@ func TestServerAllowsBlockingRemoteAddr(t *testing.T) {
return
}
defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
+ body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("Request %d: %v", num, err)
response <- ""
@@ -1381,7 +1380,7 @@ func testHeadResponses(t *testing.T, h2 bool) {
if v := res.ContentLength; v != 10 {
t.Errorf("Content-Length: %d; want 10", v)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
@@ -1432,7 +1431,7 @@ func TestTLSServer(t *testing.T) {
}
}
}))
- ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
+ ts.Config.ErrorLog = log.New(io.Discard, "", 0)
defer ts.Close()
// Connect an idle TCP connection to this server before we run
@@ -1540,7 +1539,7 @@ func TestTLSServerRejectHTTPRequests(t *testing.T) {
}
defer conn.Close()
io.WriteString(conn, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n")
- slurp, err := ioutil.ReadAll(conn)
+ slurp, err := io.ReadAll(conn)
if err != nil {
t.Fatal(err)
}
@@ -1734,7 +1733,7 @@ func TestServerExpect(t *testing.T) {
// requests that would read from r.Body, which we only
// conditionally want to do.
if strings.Contains(r.URL.RawQuery, "readbody=true") {
- ioutil.ReadAll(r.Body)
+ io.ReadAll(r.Body)
w.Write([]byte("Hi"))
} else {
w.WriteHeader(StatusUnauthorized)
@@ -1773,7 +1772,7 @@ func TestServerExpect(t *testing.T) {
io.Closer
}{
conn,
- ioutil.NopCloser(nil),
+ io.NopCloser(nil),
}
if test.chunked {
targ = httputil.NewChunkedWriter(conn)
@@ -2072,7 +2071,7 @@ type testHandlerBodyConsumer struct {
var testHandlerBodyConsumers = []testHandlerBodyConsumer{
{"nil", func(io.ReadCloser) {}},
{"close", func(r io.ReadCloser) { r.Close() }},
- {"discard", func(r io.ReadCloser) { io.Copy(ioutil.Discard, r) }},
+ {"discard", func(r io.ReadCloser) { io.Copy(io.Discard, r) }},
}
func TestRequestBodyReadErrorClosesConnection(t *testing.T) {
@@ -2298,7 +2297,7 @@ func testTimeoutHandler(t *testing.T, h2 bool) {
if g, e := res.StatusCode, StatusOK; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
- body, _ := ioutil.ReadAll(res.Body)
+ body, _ := io.ReadAll(res.Body)
if g, e := string(body), "hi"; g != e {
t.Errorf("got body %q; expected %q", g, e)
}
@@ -2315,7 +2314,7 @@ func testTimeoutHandler(t *testing.T, h2 bool) {
if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
- body, _ = ioutil.ReadAll(res.Body)
+ body, _ = io.ReadAll(res.Body)
if !strings.Contains(string(body), "Timeout") {
t.Errorf("expected timeout body; got %q", string(body))
}
@@ -2367,7 +2366,7 @@ func TestTimeoutHandlerRace(t *testing.T) {
defer func() { <-gate }()
res, err := c.Get(fmt.Sprintf("%s/%d", ts.URL, rand.Intn(50)))
if err == nil {
- io.Copy(ioutil.Discard, res.Body)
+ io.Copy(io.Discard, res.Body)
res.Body.Close()
}
}()
@@ -2410,7 +2409,7 @@ func TestTimeoutHandlerRaceHeader(t *testing.T) {
return
}
defer res.Body.Close()
- io.Copy(ioutil.Discard, res.Body)
+ io.Copy(io.Discard, res.Body)
}()
}
wg.Wait()
@@ -2441,7 +2440,7 @@ func TestTimeoutHandlerRaceHeaderTimeout(t *testing.T) {
if g, e := res.StatusCode, StatusOK; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
- body, _ := ioutil.ReadAll(res.Body)
+ body, _ := io.ReadAll(res.Body)
if g, e := string(body), "hi"; g != e {
t.Errorf("got body %q; expected %q", g, e)
}
@@ -2458,7 +2457,7 @@ func TestTimeoutHandlerRaceHeaderTimeout(t *testing.T) {
if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
- body, _ = ioutil.ReadAll(res.Body)
+ body, _ = io.ReadAll(res.Body)
if !strings.Contains(string(body), "Timeout") {
t.Errorf("expected timeout body; got %q", string(body))
}
@@ -2630,7 +2629,7 @@ func TestRedirectContentTypeAndBody(t *testing.T) {
t.Errorf("Redirect(%q, %#v) generated Content-Type header %q; want %q", tt.method, tt.ct, got, want)
}
resp := rec.Result()
- body, err := ioutil.ReadAll(resp.Body)
+ body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
@@ -2657,7 +2656,7 @@ func testZeroLengthPostAndResponse(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, r *Request) {
- all, err := ioutil.ReadAll(r.Body)
+ all, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("handler ReadAll: %v", err)
}
@@ -2683,7 +2682,7 @@ func testZeroLengthPostAndResponse(t *testing.T, h2 bool) {
}
for i := range resp {
- all, err := ioutil.ReadAll(resp[i].Body)
+ all, err := io.ReadAll(resp[i].Body)
if err != nil {
t.Fatalf("req #%d: client ReadAll: %v", i, err)
}
@@ -2710,7 +2709,7 @@ func TestHandlerPanicWithHijack(t *testing.T) {
func testHandlerPanic(t *testing.T, withHijack, h2 bool, wrapper func(Handler) Handler, panicValue interface{}) {
defer afterTest(t)
- // Unlike the other tests that set the log output to ioutil.Discard
+ // Unlike the other tests that set the log output to io.Discard
// to quiet the output, this test uses a pipe. The pipe serves three
// purposes:
//
@@ -2970,7 +2969,7 @@ func testRequestBodyLimit(t *testing.T, h2 bool) {
const limit = 1 << 20
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
r.Body = MaxBytesReader(w, r.Body, limit)
- n, err := io.Copy(ioutil.Discard, r.Body)
+ n, err := io.Copy(io.Discard, r.Body)
if err == nil {
t.Errorf("expected error from io.Copy")
}
@@ -3020,7 +3019,7 @@ func TestClientWriteShutdown(t *testing.T) {
donec := make(chan bool)
go func() {
defer close(donec)
- bs, err := ioutil.ReadAll(conn)
+ bs, err := io.ReadAll(conn)
if err != nil {
t.Errorf("ReadAll: %v", err)
}
@@ -3341,7 +3340,7 @@ func TestHijackBeforeRequestBodyRead(t *testing.T) {
r.Body = nil // to test that server.go doesn't use this value.
gone := w.(CloseNotifier).CloseNotify()
- slurp, err := ioutil.ReadAll(reqBody)
+ slurp, err := io.ReadAll(reqBody)
if err != nil {
t.Errorf("Body read: %v", err)
return
@@ -3643,7 +3642,7 @@ func TestAcceptMaxFds(t *testing.T) {
}}}
server := &Server{
Handler: HandlerFunc(HandlerFunc(func(ResponseWriter, *Request) {})),
- ErrorLog: log.New(ioutil.Discard, "", 0), // noisy otherwise
+ ErrorLog: log.New(io.Discard, "", 0), // noisy otherwise
}
err := server.Serve(ln)
if err != io.EOF {
@@ -3782,7 +3781,7 @@ func testServerReaderFromOrder(t *testing.T, h2 bool) {
close(done)
}()
time.Sleep(25 * time.Millisecond) // give Copy a chance to break things
- n, err := io.Copy(ioutil.Discard, req.Body)
+ n, err := io.Copy(io.Discard, req.Body)
if err != nil {
t.Errorf("handler Copy: %v", err)
return
@@ -3804,7 +3803,7 @@ func testServerReaderFromOrder(t *testing.T, h2 bool) {
if err != nil {
t.Fatal(err)
}
- all, err := ioutil.ReadAll(res.Body)
+ all, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -3929,7 +3928,7 @@ func testTransportAndServerSharedBodyRace(t *testing.T, h2 bool) {
errorf("Proxy outbound request: %v", err)
return
}
- _, err = io.CopyN(ioutil.Discard, bresp.Body, bodySize/2)
+ _, err = io.CopyN(io.Discard, bresp.Body, bodySize/2)
if err != nil {
errorf("Proxy copy error: %v", err)
return
@@ -4136,7 +4135,7 @@ func TestServerConnState(t *testing.T) {
ts.Close()
}()
- ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
+ ts.Config.ErrorLog = log.New(io.Discard, "", 0)
ts.Config.ConnState = func(c net.Conn, state ConnState) {
if c == nil {
t.Errorf("nil conn seen in state %s", state)
@@ -4176,7 +4175,7 @@ func TestServerConnState(t *testing.T) {
t.Errorf("Error fetching %s: %v", url, err)
return
}
- _, err = ioutil.ReadAll(res.Body)
+ _, err = io.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
t.Errorf("Error reading %s: %v", url, err)
@@ -4233,7 +4232,7 @@ func TestServerConnState(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
+ if _, err := io.Copy(io.Discard, res.Body); err != nil {
t.Fatal(err)
}
c.Close()
@@ -4285,7 +4284,7 @@ func testServerEmptyBodyRace(t *testing.T, h2 bool) {
}
}
defer res.Body.Close()
- _, err = io.Copy(ioutil.Discard, res.Body)
+ _, err = io.Copy(io.Discard, res.Body)
if err != nil {
t.Error(err)
return
@@ -4311,7 +4310,7 @@ func TestServerConnStateNew(t *testing.T) {
srv.Serve(&oneConnListener{
conn: &rwTestConn{
Reader: strings.NewReader("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"),
- Writer: ioutil.Discard,
+ Writer: io.Discard,
},
})
if !sawNew { // testing that this read isn't racy
@@ -4367,7 +4366,7 @@ func TestServerFlushAndHijack(t *testing.T) {
t.Fatal(err)
}
defer res.Body.Close()
- all, err := ioutil.ReadAll(res.Body)
+ all, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -4555,7 +4554,7 @@ Host: foo
go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) {
numReq++
if r.URL.Path == "/readbody" {
- ioutil.ReadAll(r.Body)
+ io.ReadAll(r.Body)
}
io.WriteString(w, "Hello world!")
}))
@@ -4608,7 +4607,7 @@ func testHandlerSetsBodyNil(t *testing.T, h2 bool) {
t.Fatal(err)
}
defer res.Body.Close()
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -4724,7 +4723,7 @@ func TestServerHandlersCanHandleH2PRI(t *testing.T) {
}
defer c.Close()
io.WriteString(c, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
- slurp, err := ioutil.ReadAll(c)
+ slurp, err := io.ReadAll(c)
if err != nil {
t.Fatal(err)
}
@@ -4958,7 +4957,7 @@ func BenchmarkClientServer(b *testing.B) {
if err != nil {
b.Fatal("Get:", err)
}
- all, err := ioutil.ReadAll(res.Body)
+ all, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
b.Fatal("ReadAll:", err)
@@ -5009,7 +5008,7 @@ func benchmarkClientServerParallel(b *testing.B, parallelism int, useTLS bool) {
b.Logf("Get: %v", err)
continue
}
- all, err := ioutil.ReadAll(res.Body)
+ all, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
b.Logf("ReadAll: %v", err)
@@ -5044,7 +5043,7 @@ func BenchmarkServer(b *testing.B) {
if err != nil {
log.Panicf("Get: %v", err)
}
- all, err := ioutil.ReadAll(res.Body)
+ all, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Panicf("ReadAll: %v", err)
@@ -5167,7 +5166,7 @@ func BenchmarkClient(b *testing.B) {
if err != nil {
b.Fatalf("Get: %v", err)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
b.Fatalf("ReadAll: %v", err)
@@ -5257,7 +5256,7 @@ Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
conn := &rwTestConn{
Reader: &repeatReader{content: req, count: b.N},
- Writer: ioutil.Discard,
+ Writer: io.Discard,
closec: make(chan bool, 1),
}
handled := 0
@@ -5286,7 +5285,7 @@ Host: golang.org
conn := &rwTestConn{
Reader: &repeatReader{content: req, count: b.N},
- Writer: ioutil.Discard,
+ Writer: io.Discard,
closec: make(chan bool, 1),
}
handled := 0
@@ -5346,7 +5345,7 @@ Host: golang.org
`)
conn := &rwTestConn{
Reader: &repeatReader{content: req, count: b.N},
- Writer: ioutil.Discard,
+ Writer: io.Discard,
closec: make(chan bool, 1),
}
handled := 0
@@ -5375,7 +5374,7 @@ Host: golang.org
conn.Close()
})
conn := &rwTestConn{
- Writer: ioutil.Discard,
+ Writer: io.Discard,
closec: make(chan bool, 1),
}
ln := &oneConnListener{conn: conn}
@@ -5438,7 +5437,7 @@ func TestServerIdleTimeout(t *testing.T) {
setParallel(t)
defer afterTest(t)
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- io.Copy(ioutil.Discard, r.Body)
+ io.Copy(io.Discard, r.Body)
io.WriteString(w, r.RemoteAddr)
}))
ts.Config.ReadHeaderTimeout = 1 * time.Second
@@ -5453,7 +5452,7 @@ func TestServerIdleTimeout(t *testing.T) {
t.Fatal(err)
}
defer res.Body.Close()
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -5478,7 +5477,7 @@ func TestServerIdleTimeout(t *testing.T) {
defer conn.Close()
conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo.com\r\n"))
time.Sleep(2 * time.Second)
- if _, err := io.CopyN(ioutil.Discard, conn, 1); err == nil {
+ if _, err := io.CopyN(io.Discard, conn, 1); err == nil {
t.Fatal("copy byte succeeded; want err")
}
}
@@ -5489,7 +5488,7 @@ func get(t *testing.T, c *Client, url string) string {
t.Fatal(err)
}
defer res.Body.Close()
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -5739,7 +5738,7 @@ func TestServerCancelsReadTimeoutWhenIdle(t *testing.T) {
if err != nil {
return fmt.Errorf("Get: %v", err)
}
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return fmt.Errorf("Body ReadAll: %v", err)
@@ -5802,7 +5801,7 @@ func TestServerDuplicateBackgroundRead(t *testing.T) {
wg.Add(1)
go func() {
defer wg.Done()
- io.Copy(ioutil.Discard, cn)
+ io.Copy(io.Discard, cn)
}()
for j := 0; j < requests; j++ {
@@ -5902,7 +5901,7 @@ func TestServerHijackGetsBackgroundByte_big(t *testing.T) {
return
}
defer conn.Close()
- slurp, err := ioutil.ReadAll(buf.Reader)
+ slurp, err := io.ReadAll(buf.Reader)
if err != nil {
t.Errorf("Copy: %v", err)
}
@@ -6436,13 +6435,13 @@ func fetchWireResponse(host string, http1ReqBody []byte) ([]byte, error) {
if _, err := conn.Write(http1ReqBody); err != nil {
return nil, err
}
- return ioutil.ReadAll(conn)
+ return io.ReadAll(conn)
}
func BenchmarkResponseStatusLine(b *testing.B) {
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
- bw := bufio.NewWriter(ioutil.Discard)
+ bw := bufio.NewWriter(io.Discard)
var buf3 [3]byte
for pb.Next() {
Export_writeStatusLine(bw, true, 200, buf3[:])
diff --git a/src/net/http/server.go b/src/net/http/server.go
index fab229c92a..ba473d14f5 100644
--- a/src/net/http/server.go
+++ b/src/net/http/server.go
@@ -14,7 +14,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"log"
"net"
"net/textproto"
@@ -1368,7 +1367,7 @@ func (cw *chunkWriter) writeHeader(p []byte) {
}
if discard {
- _, err := io.CopyN(ioutil.Discard, w.reqBody, maxPostHandlerReadBytes+1)
+ _, err := io.CopyN(io.Discard, w.reqBody, maxPostHandlerReadBytes+1)
switch err {
case nil:
// There must be even more data left over.
@@ -3407,7 +3406,7 @@ func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
// (or an attack) and we abort and close the connection,
// courtesy of MaxBytesReader's EOF behavior.
mb := MaxBytesReader(w, r.Body, 4<<10)
- io.Copy(ioutil.Discard, mb)
+ io.Copy(io.Discard, mb)
}
}
diff --git a/src/net/http/sniff_test.go b/src/net/http/sniff_test.go
index a1157a0823..8d5350374d 100644
--- a/src/net/http/sniff_test.go
+++ b/src/net/http/sniff_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"log"
. "net/http"
"reflect"
@@ -123,7 +122,7 @@ func testServerContentType(t *testing.T, h2 bool) {
if ct := resp.Header.Get("Content-Type"); ct != wantContentType {
t.Errorf("%v: Content-Type = %q, want %q", tt.desc, ct, wantContentType)
}
- data, err := ioutil.ReadAll(resp.Body)
+ data, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("%v: reading body: %v", tt.desc, err)
} else if !bytes.Equal(data, tt.data) {
@@ -185,7 +184,7 @@ func testContentTypeWithCopy(t *testing.T, h2 bool) {
if ct := resp.Header.Get("Content-Type"); ct != expected {
t.Errorf("Content-Type = %q, want %q", ct, expected)
}
- data, err := ioutil.ReadAll(resp.Body)
+ data, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("reading body: %v", err)
} else if !bytes.Equal(data, []byte(input)) {
@@ -216,7 +215,7 @@ func testSniffWriteSize(t *testing.T, h2 bool) {
if err != nil {
t.Fatalf("size %d: %v", size, err)
}
- if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
+ if _, err := io.Copy(io.Discard, res.Body); err != nil {
t.Fatalf("size %d: io.Copy of body = %v", size, err)
}
if err := res.Body.Close(); err != nil {
diff --git a/src/net/http/transfer.go b/src/net/http/transfer.go
index c3234f30cc..fbb0c39829 100644
--- a/src/net/http/transfer.go
+++ b/src/net/http/transfer.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"net/http/httptrace"
"net/http/internal"
"net/textproto"
@@ -156,7 +155,7 @@ func newTransferWriter(r interface{}) (t *transferWriter, err error) {
// servers. See Issue 18257, as one example.
//
// The only reason we'd send such a request is if the user set the Body to a
-// non-nil value (say, ioutil.NopCloser(bytes.NewReader(nil))) and didn't
+// non-nil value (say, io.NopCloser(bytes.NewReader(nil))) and didn't
// set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
// there's bytes to send.
//
@@ -370,7 +369,7 @@ func (t *transferWriter) writeBody(w io.Writer) (err error) {
return err
}
var nextra int64
- nextra, err = t.doBodyCopy(ioutil.Discard, body)
+ nextra, err = t.doBodyCopy(io.Discard, body)
ncopy += nextra
}
if err != nil {
@@ -992,7 +991,7 @@ func (b *body) Close() error {
var n int64
// Consume the body, or, which will also lead to us reading
// the trailer headers after the body, if present.
- n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
+ n, err = io.CopyN(io.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
if err == io.EOF {
err = nil
}
@@ -1003,7 +1002,7 @@ func (b *body) Close() error {
default:
// Fully consume the body, which will also lead to us reading
// the trailer headers after the body, if present.
- _, err = io.Copy(ioutil.Discard, bodyLocked{b})
+ _, err = io.Copy(io.Discard, bodyLocked{b})
}
b.closed = true
return err
@@ -1075,7 +1074,7 @@ func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
return
}
-var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))
+var nopCloserType = reflect.TypeOf(io.NopCloser(nil))
// isKnownInMemoryReader reports whether r is a type known to not
// block on Read. Its caller uses this as an optional optimization to
diff --git a/src/net/http/transfer_test.go b/src/net/http/transfer_test.go
index 185225fa93..1f3d32526d 100644
--- a/src/net/http/transfer_test.go
+++ b/src/net/http/transfer_test.go
@@ -81,11 +81,11 @@ func TestDetectInMemoryReaders(t *testing.T) {
{bytes.NewBuffer(nil), true},
{strings.NewReader(""), true},
- {ioutil.NopCloser(pr), false},
+ {io.NopCloser(pr), false},
- {ioutil.NopCloser(bytes.NewReader(nil)), true},
- {ioutil.NopCloser(bytes.NewBuffer(nil)), true},
- {ioutil.NopCloser(strings.NewReader("")), true},
+ {io.NopCloser(bytes.NewReader(nil)), true},
+ {io.NopCloser(bytes.NewBuffer(nil)), true},
+ {io.NopCloser(strings.NewReader("")), true},
}
for i, tt := range tests {
got := isKnownInMemoryReader(tt.r)
@@ -104,12 +104,12 @@ var _ io.ReaderFrom = (*mockTransferWriter)(nil)
func (w *mockTransferWriter) ReadFrom(r io.Reader) (int64, error) {
w.CalledReader = r
- return io.Copy(ioutil.Discard, r)
+ return io.Copy(io.Discard, r)
}
func (w *mockTransferWriter) Write(p []byte) (int, error) {
w.WriteCalled = true
- return ioutil.Discard.Write(p)
+ return io.Discard.Write(p)
}
func TestTransferWriterWriteBodyReaderTypes(t *testing.T) {
@@ -166,7 +166,7 @@ func TestTransferWriterWriteBodyReaderTypes(t *testing.T) {
method: "PUT",
bodyFunc: func() (io.Reader, func(), error) {
r, cleanup, err := newFileFunc()
- return ioutil.NopCloser(r), cleanup, err
+ return io.NopCloser(r), cleanup, err
},
contentLength: nBytes,
limitedReader: true,
@@ -206,7 +206,7 @@ func TestTransferWriterWriteBodyReaderTypes(t *testing.T) {
method: "PUT",
bodyFunc: func() (io.Reader, func(), error) {
r, cleanup, err := newBufferFunc()
- return ioutil.NopCloser(r), cleanup, err
+ return io.NopCloser(r), cleanup, err
},
contentLength: nBytes,
limitedReader: true,
diff --git a/src/net/http/transport_internal_test.go b/src/net/http/transport_internal_test.go
index 92729e65b2..1097ffd173 100644
--- a/src/net/http/transport_internal_test.go
+++ b/src/net/http/transport_internal_test.go
@@ -11,7 +11,6 @@ import (
"crypto/tls"
"errors"
"io"
- "io/ioutil"
"net"
"net/http/internal"
"strings"
@@ -226,7 +225,7 @@ func TestTransportBodyAltRewind(t *testing.T) {
TLSNextProto: map[string]func(string, *tls.Conn) RoundTripper{
"foo": func(authority string, c *tls.Conn) RoundTripper {
return roundTripFunc(func(r *Request) (*Response, error) {
- n, _ := io.Copy(ioutil.Discard, r.Body)
+ n, _ := io.Copy(io.Discard, r.Body)
if n == 0 {
t.Error("body length is zero")
}
diff --git a/src/net/http/transport_test.go b/src/net/http/transport_test.go
index b152007282..58f0d9db98 100644
--- a/src/net/http/transport_test.go
+++ b/src/net/http/transport_test.go
@@ -173,7 +173,7 @@ func TestTransportKeepAlives(t *testing.T) {
if err != nil {
t.Fatalf("error in disableKeepAlive=%v, req #%d, GET: %v", disableKeepAlive, n, err)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("error in disableKeepAlive=%v, req #%d, ReadAll: %v", disableKeepAlive, n, err)
}
@@ -220,7 +220,7 @@ func TestTransportConnectionCloseOnResponse(t *testing.T) {
t.Fatalf("error in connectionClose=%v, req #%d, Do: %v", connectionClose, n, err)
}
defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("error in connectionClose=%v, req #%d, ReadAll: %v", connectionClose, n, err)
}
@@ -273,7 +273,7 @@ func TestTransportConnectionCloseOnRequest(t *testing.T) {
t.Errorf("For connectionClose = %v; handler's X-Saw-Close was %v; want %v",
connectionClose, got, !connectionClose)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("error in connectionClose=%v, req #%d, ReadAll: %v", connectionClose, n, err)
}
@@ -382,7 +382,7 @@ func TestTransportIdleCacheKeys(t *testing.T) {
if err != nil {
t.Error(err)
}
- ioutil.ReadAll(resp.Body)
+ io.ReadAll(resp.Body)
keys := tr.IdleConnKeysForTesting()
if e, g := 1, len(keys); e != g {
@@ -495,7 +495,7 @@ func TestTransportMaxPerHostIdleConns(t *testing.T) {
t.Error(err)
return
}
- if _, err := ioutil.ReadAll(resp.Body); err != nil {
+ if _, err := io.ReadAll(resp.Body); err != nil {
t.Errorf("ReadAll: %v", err)
return
}
@@ -575,7 +575,7 @@ func TestTransportMaxConnsPerHostIncludeDialInProgress(t *testing.T) {
if err != nil {
t.Errorf("unexpected error for request %s: %v", reqId, err)
}
- _, err = ioutil.ReadAll(resp.Body)
+ _, err = io.ReadAll(resp.Body)
if err != nil {
t.Errorf("unexpected error for request %s: %v", reqId, err)
}
@@ -655,7 +655,7 @@ func TestTransportMaxConnsPerHost(t *testing.T) {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
- _, err = ioutil.ReadAll(resp.Body)
+ _, err = io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body failed: %v", err)
}
@@ -733,7 +733,7 @@ func TestTransportRemovesDeadIdleConnections(t *testing.T) {
t.Fatalf("%s: %v", name, res.Status)
}
defer res.Body.Close()
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("%s: %v", name, err)
}
@@ -783,7 +783,7 @@ func TestTransportServerClosingUnexpectedly(t *testing.T) {
condFatalf("error in req #%d, GET: %v", n, err)
continue
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
condFatalf("error in req #%d, ReadAll: %v", n, err)
continue
@@ -903,7 +903,7 @@ func TestTransportHeadResponses(t *testing.T) {
if e, g := int64(123), res.ContentLength; e != g {
t.Errorf("loop %d: expected res.ContentLength of %v, got %v", i, e, g)
}
- if all, err := ioutil.ReadAll(res.Body); err != nil {
+ if all, err := io.ReadAll(res.Body); err != nil {
t.Errorf("loop %d: Body ReadAll: %v", i, err)
} else if len(all) != 0 {
t.Errorf("Bogus body %q", all)
@@ -1006,10 +1006,10 @@ func TestRoundTripGzip(t *testing.T) {
t.Errorf("%d. gzip NewReader: %v", i, err)
continue
}
- body, err = ioutil.ReadAll(r)
+ body, err = io.ReadAll(r)
res.Body.Close()
} else {
- body, err = ioutil.ReadAll(res.Body)
+ body, err = io.ReadAll(res.Body)
}
if err != nil {
t.Errorf("%d. Error: %q", i, err)
@@ -1090,7 +1090,7 @@ func TestTransportGzip(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -1133,7 +1133,7 @@ func TestTransportExpect100Continue(t *testing.T) {
switch req.URL.Path {
case "/100":
// This endpoint implicitly responds 100 Continue and reads body.
- if _, err := io.Copy(ioutil.Discard, req.Body); err != nil {
+ if _, err := io.Copy(io.Discard, req.Body); err != nil {
t.Error("Failed to read Body", err)
}
rw.WriteHeader(StatusOK)
@@ -1159,7 +1159,7 @@ func TestTransportExpect100Continue(t *testing.T) {
if err != nil {
log.Fatal(err)
}
- if _, err := io.CopyN(ioutil.Discard, bufrw, req.ContentLength); err != nil {
+ if _, err := io.CopyN(io.Discard, bufrw, req.ContentLength); err != nil {
t.Error("Failed to read Body", err)
}
bufrw.WriteString("HTTP/1.1 200 OK\r\n\r\n")
@@ -1625,7 +1625,7 @@ func TestTransportGzipRecursive(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -1654,7 +1654,7 @@ func TestTransportGzipShort(t *testing.T) {
t.Fatal(err)
}
defer res.Body.Close()
- _, err = ioutil.ReadAll(res.Body)
+ _, err = io.ReadAll(res.Body)
if err == nil {
t.Fatal("Expect an error from reading a body.")
}
@@ -1999,7 +1999,7 @@ func TestIssue3644(t *testing.T) {
t.Fatal(err)
}
defer res.Body.Close()
- bs, err := ioutil.ReadAll(res.Body)
+ bs, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -2024,7 +2024,7 @@ func TestIssue3595(t *testing.T) {
t.Errorf("Post: %v", err)
return
}
- got, err := ioutil.ReadAll(res.Body)
+ got, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("Body ReadAll: %v", err)
}
@@ -2096,7 +2096,7 @@ func TestTransportConcurrency(t *testing.T) {
wg.Done()
continue
}
- all, err := ioutil.ReadAll(res.Body)
+ all, err := io.ReadAll(res.Body)
if err != nil {
t.Errorf("read error on req %s: %v", req, err)
wg.Done()
@@ -2163,7 +2163,7 @@ func TestIssue4191_InfiniteGetTimeout(t *testing.T) {
t.Errorf("Error issuing GET: %v", err)
break
}
- _, err = io.Copy(ioutil.Discard, sres.Body)
+ _, err = io.Copy(io.Discard, sres.Body)
if err == nil {
t.Errorf("Unexpected successful copy")
break
@@ -2184,7 +2184,7 @@ func TestIssue4191_InfiniteGetToPutTimeout(t *testing.T) {
})
mux.HandleFunc("/put", func(w ResponseWriter, r *Request) {
defer r.Body.Close()
- io.Copy(ioutil.Discard, r.Body)
+ io.Copy(io.Discard, r.Body)
})
ts := httptest.NewServer(mux)
timeout := 100 * time.Millisecond
@@ -2338,7 +2338,7 @@ func TestTransportCancelRequest(t *testing.T) {
tr.CancelRequest(req)
}()
t0 := time.Now()
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
d := time.Since(t0)
if err != ExportErrRequestCanceled {
@@ -2497,7 +2497,7 @@ func TestCancelRequestWithChannel(t *testing.T) {
close(ch)
}()
t0 := time.Now()
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
d := time.Since(t0)
if err != ExportErrRequestCanceled {
@@ -2678,7 +2678,7 @@ func (fooProto) RoundTrip(req *Request) (*Response, error) {
Status: "200 OK",
StatusCode: 200,
Header: make(Header),
- Body: ioutil.NopCloser(strings.NewReader("You wanted " + req.URL.String())),
+ Body: io.NopCloser(strings.NewReader("You wanted " + req.URL.String())),
}
return res, nil
}
@@ -2692,7 +2692,7 @@ func TestTransportAltProto(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- bodyb, err := ioutil.ReadAll(res.Body)
+ bodyb, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -2769,7 +2769,7 @@ func TestTransportSocketLateBinding(t *testing.T) {
// let the foo response finish so we can use its
// connection for /bar
fooGate <- true
- io.Copy(ioutil.Discard, fooRes.Body)
+ io.Copy(io.Discard, fooRes.Body)
fooRes.Body.Close()
})
@@ -2808,7 +2808,7 @@ func TestTransportReading100Continue(t *testing.T) {
t.Error(err)
return
}
- slurp, err := ioutil.ReadAll(req.Body)
+ slurp, err := io.ReadAll(req.Body)
if err != nil {
t.Errorf("Server request body slurp: %v", err)
return
@@ -2872,7 +2872,7 @@ Content-Length: %d
if id, idBack := req.Header.Get("Request-Id"), res.Header.Get("Echo-Request-Id"); id != "" && id != idBack {
t.Errorf("%s: response id %q != request id %q", name, idBack, id)
}
- _, err = ioutil.ReadAll(res.Body)
+ _, err = io.ReadAll(res.Body)
if err != nil {
t.Fatalf("%s: Slurp error: %v", name, err)
}
@@ -3151,7 +3151,7 @@ func TestIdleConnChannelLeak(t *testing.T) {
func TestTransportClosesRequestBody(t *testing.T) {
defer afterTest(t)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- io.Copy(ioutil.Discard, r.Body)
+ io.Copy(io.Discard, r.Body)
}))
defer ts.Close()
@@ -3258,7 +3258,7 @@ func TestTLSServerClosesConnection(t *testing.T) {
t.Fatal(err)
}
<-closedc
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -3273,7 +3273,7 @@ func TestTLSServerClosesConnection(t *testing.T) {
errs = append(errs, err)
continue
}
- slurp, err = ioutil.ReadAll(res.Body)
+ slurp, err = io.ReadAll(res.Body)
if err != nil {
errs = append(errs, err)
continue
@@ -3344,7 +3344,7 @@ func TestTransportNoReuseAfterEarlyResponse(t *testing.T) {
sconn.c = conn
sconn.Unlock()
conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nfoo")) // keep-alive
- go io.Copy(ioutil.Discard, conn)
+ go io.Copy(io.Discard, conn)
}))
defer ts.Close()
c := ts.Client()
@@ -3593,7 +3593,7 @@ func TestTransportClosesBodyOnError(t *testing.T) {
defer afterTest(t)
readBody := make(chan error, 1)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- _, err := ioutil.ReadAll(r.Body)
+ _, err := io.ReadAll(r.Body)
readBody <- err
}))
defer ts.Close()
@@ -3941,7 +3941,7 @@ func TestTransportResponseCancelRace(t *testing.T) {
// If we do an early close, Transport just throws the connection away and
// doesn't reuse it. In order to trigger the bug, it has to reuse the connection
// so read the body
- if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
+ if _, err := io.Copy(io.Discard, res.Body); err != nil {
t.Fatal(err)
}
@@ -3978,7 +3978,7 @@ func TestTransportContentEncodingCaseInsensitive(t *testing.T) {
t.Fatal(err)
}
- body, err := ioutil.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
@@ -4085,7 +4085,7 @@ func TestTransportFlushesBodyChunks(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- io.Copy(ioutil.Discard, req.Body)
+ io.Copy(io.Discard, req.Body)
// Unblock the transport's roundTrip goroutine.
resBody <- strings.NewReader("HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n")
@@ -4466,7 +4466,7 @@ func testTransportEventTrace(t *testing.T, h2 bool, noHooks bool) {
// Do nothing for the second request.
return
}
- if _, err := ioutil.ReadAll(r.Body); err != nil {
+ if _, err := io.ReadAll(r.Body); err != nil {
t.Error(err)
}
if !noHooks {
@@ -4554,7 +4554,7 @@ func testTransportEventTrace(t *testing.T, h2 bool, noHooks bool) {
t.Fatal(err)
}
logf("got roundtrip.response")
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -5236,7 +5236,7 @@ func wantBody(res *Response, err error, want string) error {
if err != nil {
return err
}
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("error reading body: %v", err)
}
@@ -5335,7 +5335,7 @@ func TestMissingStatusNoPanic(t *testing.T) {
conn, _ := ln.Accept()
if conn != nil {
io.WriteString(conn, raw)
- ioutil.ReadAll(conn)
+ io.ReadAll(conn)
conn.Close()
}
}()
@@ -5353,7 +5353,7 @@ func TestMissingStatusNoPanic(t *testing.T) {
t.Error("panicked, expecting an error")
}
if res != nil && res.Body != nil {
- io.Copy(ioutil.Discard, res.Body)
+ io.Copy(io.Discard, res.Body)
res.Body.Close()
}
@@ -5539,7 +5539,7 @@ func TestClientTimeoutKillsConn_AfterHeaders(t *testing.T) {
}
close(cancel)
- got, err := ioutil.ReadAll(res.Body)
+ got, err := io.ReadAll(res.Body)
if err == nil {
t.Fatalf("unexpected success; read %q, nil", got)
}
@@ -5678,7 +5678,7 @@ func TestTransportCONNECTBidi(t *testing.T) {
}
func TestTransportRequestReplayable(t *testing.T) {
- someBody := ioutil.NopCloser(strings.NewReader(""))
+ someBody := io.NopCloser(strings.NewReader(""))
tests := []struct {
name string
req *Request
@@ -5839,7 +5839,7 @@ func TestTransportRequestWriteRoundTrip(t *testing.T) {
t,
h1Mode,
HandlerFunc(func(w ResponseWriter, r *Request) {
- io.Copy(ioutil.Discard, r.Body)
+ io.Copy(io.Discard, r.Body)
r.Body.Close()
w.WriteHeader(200)
}),
@@ -5975,7 +5975,7 @@ func TestTransportIgnores408(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- slurp, err := ioutil.ReadAll(res.Body)
+ slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
@@ -6237,7 +6237,7 @@ func TestTransportDecrementConnWhenIdleConnRemoved(t *testing.T) {
return
}
defer resp.Body.Close()
- _, err = ioutil.ReadAll(resp.Body)
+ _, err = io.ReadAll(resp.Body)
if err != nil {
errCh <- fmt.Errorf("read body failed: %v", err)
}
@@ -6299,7 +6299,7 @@ func (f roundTripFunc) RoundTrip(r *Request) (*Response, error) { return f(r) }
func TestIssue32441(t *testing.T) {
defer afterTest(t)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- if n, _ := io.Copy(ioutil.Discard, r.Body); n == 0 {
+ if n, _ := io.Copy(io.Discard, r.Body); n == 0 {
t.Error("body length is zero")
}
}))
@@ -6307,7 +6307,7 @@ func TestIssue32441(t *testing.T) {
c := ts.Client()
c.Transport.(*Transport).RegisterProtocol("http", roundTripFunc(func(r *Request) (*Response, error) {
// Draining body to trigger failure condition on actual request to server.
- if n, _ := io.Copy(ioutil.Discard, r.Body); n == 0 {
+ if n, _ := io.Copy(io.Discard, r.Body); n == 0 {
t.Error("body length is zero during round trip")
}
return nil, ErrSkipAltProtocol
@@ -6389,7 +6389,7 @@ func testTransportRace(req *Request) {
if err == nil {
// Ensure all the body is read; otherwise
// we'll get a partial dump.
- io.Copy(ioutil.Discard, req.Body)
+ io.Copy(io.Discard, req.Body)
req.Body.Close()
}
select {
diff --git a/src/net/mail/example_test.go b/src/net/mail/example_test.go
index c3365642aa..d325dc791f 100644
--- a/src/net/mail/example_test.go
+++ b/src/net/mail/example_test.go
@@ -6,7 +6,7 @@ package mail_test
import (
"fmt"
- "io/ioutil"
+ "io"
"log"
"net/mail"
"strings"
@@ -62,7 +62,7 @@ Message body
fmt.Println("To:", header.Get("To"))
fmt.Println("Subject:", header.Get("Subject"))
- body, err := ioutil.ReadAll(m.Body)
+ body, err := io.ReadAll(m.Body)
if err != nil {
log.Fatal(err)
}
diff --git a/src/net/mail/message_test.go b/src/net/mail/message_test.go
index 67e3643aeb..188d0bf766 100644
--- a/src/net/mail/message_test.go
+++ b/src/net/mail/message_test.go
@@ -7,7 +7,6 @@ package mail
import (
"bytes"
"io"
- "io/ioutil"
"mime"
"reflect"
"strings"
@@ -53,7 +52,7 @@ func TestParsing(t *testing.T) {
t.Errorf("test #%d: Incorrectly parsed message header.\nGot:\n%+v\nWant:\n%+v",
i, msg.Header, test.header)
}
- body, err := ioutil.ReadAll(msg.Body)
+ body, err := io.ReadAll(msg.Body)
if err != nil {
t.Errorf("test #%d: Failed reading body: %v", i, err)
continue
@@ -842,7 +841,7 @@ func TestAddressParser(t *testing.T) {
ap := AddressParser{WordDecoder: &mime.WordDecoder{
CharsetReader: func(charset string, input io.Reader) (io.Reader, error) {
- in, err := ioutil.ReadAll(input)
+ in, err := io.ReadAll(input)
if err != nil {
return nil, err
}
diff --git a/src/net/rpc/jsonrpc/all_test.go b/src/net/rpc/jsonrpc/all_test.go
index 4e73edc70b..667f839f58 100644
--- a/src/net/rpc/jsonrpc/all_test.go
+++ b/src/net/rpc/jsonrpc/all_test.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"net"
"net/rpc"
"reflect"
@@ -249,7 +248,7 @@ func TestMalformedInput(t *testing.T) {
func TestMalformedOutput(t *testing.T) {
cli, srv := net.Pipe()
go srv.Write([]byte(`{"id":0,"result":null,"error":null}`))
- go ioutil.ReadAll(srv)
+ go io.ReadAll(srv)
client := NewClient(cli)
defer client.Close()
@@ -271,7 +270,7 @@ func TestServerErrorHasNullResult(t *testing.T) {
}{
Reader: strings.NewReader(`{"method": "Arith.Add", "id": "123", "params": []}`),
Writer: &out,
- Closer: ioutil.NopCloser(nil),
+ Closer: io.NopCloser(nil),
})
r := new(rpc.Request)
if err := sc.ReadRequestHeader(r); err != nil {
diff --git a/src/net/sendfile_test.go b/src/net/sendfile_test.go
index 13842a1261..657a36599f 100644
--- a/src/net/sendfile_test.go
+++ b/src/net/sendfile_test.go
@@ -12,7 +12,6 @@ import (
"encoding/hex"
"fmt"
"io"
- "io/ioutil"
"os"
"runtime"
"sync"
@@ -282,7 +281,7 @@ func TestSendfilePipe(t *testing.T) {
return
}
defer conn.Close()
- io.Copy(ioutil.Discard, conn)
+ io.Copy(io.Discard, conn)
}()
// Wait for the byte to be copied, meaning that sendfile has
diff --git a/src/net/splice_test.go b/src/net/splice_test.go
index 0ba2f164c2..8a0cda6564 100644
--- a/src/net/splice_test.go
+++ b/src/net/splice_test.go
@@ -8,7 +8,6 @@ package net
import (
"io"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -202,7 +201,7 @@ func testSpliceIssue25985(t *testing.T, upNet, downNet string) {
}
defer fromProxy.Close()
- _, err = ioutil.ReadAll(fromProxy)
+ _, err = io.ReadAll(fromProxy)
if err != nil {
t.Fatal(err)
}
diff --git a/src/net/textproto/reader.go b/src/net/textproto/reader.go
index a00fd2395f..5c3084f8a7 100644
--- a/src/net/textproto/reader.go
+++ b/src/net/textproto/reader.go
@@ -9,7 +9,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"strconv"
"strings"
"sync"
@@ -426,7 +425,7 @@ func (r *Reader) closeDot() {
//
// See the documentation for the DotReader method for details about dot-encoding.
func (r *Reader) ReadDotBytes() ([]byte, error) {
- return ioutil.ReadAll(r.DotReader())
+ return io.ReadAll(r.DotReader())
}
// ReadDotLines reads a dot-encoding and returns a slice
diff --git a/src/net/timeout_test.go b/src/net/timeout_test.go
index ad14cd79ac..205aaa430b 100644
--- a/src/net/timeout_test.go
+++ b/src/net/timeout_test.go
@@ -11,7 +11,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"net/internal/socktest"
"os"
"runtime"
@@ -874,7 +873,7 @@ func testVariousDeadlines(t *testing.T) {
if err := c.SetDeadline(t0.Add(timeout)); err != nil {
t.Error(err)
}
- n, err := io.Copy(ioutil.Discard, c)
+ n, err := io.Copy(io.Discard, c)
dt := time.Since(t0)
c.Close()
ch <- result{n, err, dt}
diff --git a/src/net/writev_test.go b/src/net/writev_test.go
index a6b3285e57..d603b7f70a 100644
--- a/src/net/writev_test.go
+++ b/src/net/writev_test.go
@@ -11,7 +11,6 @@ import (
"fmt"
"internal/poll"
"io"
- "io/ioutil"
"reflect"
"runtime"
"sync"
@@ -28,7 +27,7 @@ func TestBuffers_read(t *testing.T) {
[]byte("in "),
[]byte("Gopherland ... "),
}
- got, err := ioutil.ReadAll(&buffers)
+ got, err := io.ReadAll(&buffers)
if err != nil {
t.Fatal(err)
}
@@ -141,7 +140,7 @@ func testBuffer_writeTo(t *testing.T, chunks int, useCopy bool) {
}
return nil
}, func(c *TCPConn) error {
- all, err := ioutil.ReadAll(c)
+ all, err := io.ReadAll(c)
if !bytes.Equal(all, want.Bytes()) || err != nil {
return fmt.Errorf("client read %q, %v; want %q, nil", all, err, want.Bytes())
}
diff --git a/src/os/exec/example_test.go b/src/os/exec/example_test.go
index 62866fa710..a66890be69 100644
--- a/src/os/exec/example_test.go
+++ b/src/os/exec/example_test.go
@@ -10,7 +10,6 @@ import (
"encoding/json"
"fmt"
"io"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -128,7 +127,7 @@ func ExampleCmd_StderrPipe() {
log.Fatal(err)
}
- slurp, _ := ioutil.ReadAll(stderr)
+ slurp, _ := io.ReadAll(stderr)
fmt.Printf("%s\n", slurp)
if err := cmd.Wait(); err != nil {
diff --git a/src/os/exec/exec_test.go b/src/os/exec/exec_test.go
index 9746722980..cd3d759ebc 100644
--- a/src/os/exec/exec_test.go
+++ b/src/os/exec/exec_test.go
@@ -637,7 +637,7 @@ func TestExtraFiles(t *testing.T) {
// cgo), to make sure none of that potential C code leaks fds.
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
// quiet expected TLS handshake error "remote error: bad certificate"
- ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
+ ts.Config.ErrorLog = log.New(io.Discard, "", 0)
ts.StartTLS()
defer ts.Close()
_, err = http.Get(ts.URL)
@@ -830,7 +830,7 @@ func TestHelperProcess(*testing.T) {
}
}
case "stdinClose":
- b, err := ioutil.ReadAll(os.Stdin)
+ b, err := io.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
diff --git a/src/os/exec/read3.go b/src/os/exec/read3.go
index 25d732a991..8852023e77 100644
--- a/src/os/exec/read3.go
+++ b/src/os/exec/read3.go
@@ -15,7 +15,7 @@ package main
import (
"fmt"
"internal/poll"
- "io/ioutil"
+ "io"
"os"
"os/exec"
"runtime"
@@ -24,7 +24,7 @@ import (
func main() {
fd3 := os.NewFile(3, "fd3")
- bs, err := ioutil.ReadAll(fd3)
+ bs, err := io.ReadAll(fd3)
if err != nil {
fmt.Printf("ReadAll from fd 3: %v\n", err)
os.Exit(1)
diff --git a/src/os/timeout_test.go b/src/os/timeout_test.go
index 99b94c2e4c..d848e41642 100644
--- a/src/os/timeout_test.go
+++ b/src/os/timeout_test.go
@@ -429,7 +429,7 @@ func testVariousDeadlines(t *testing.T) {
if err := r.SetDeadline(t0.Add(timeout)); err != nil {
t.Error(err)
}
- n, err := io.Copy(ioutil.Discard, r)
+ n, err := io.Copy(io.Discard, r)
dt := time.Since(t0)
r.Close()
actvch <- result{n, err, dt}
@@ -565,7 +565,7 @@ func TestRacyWrite(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
- go io.Copy(ioutil.Discard, r)
+ go io.Copy(io.Discard, r)
w.SetWriteDeadline(time.Now().Add(time.Millisecond))
for i := 0; i < 10; i++ {
diff --git a/src/runtime/crash_unix_test.go b/src/runtime/crash_unix_test.go
index 8ef52aba48..fc87f37408 100644
--- a/src/runtime/crash_unix_test.go
+++ b/src/runtime/crash_unix_test.go
@@ -241,7 +241,7 @@ func TestPanicSystemstack(t *testing.T) {
}
// Get traceback.
- tb, err := ioutil.ReadAll(pr)
+ tb, err := io.ReadAll(pr)
if err != nil {
t.Fatal("reading traceback from pipe: ", err)
}
diff --git a/src/runtime/testdata/testprogcgo/eintr.go b/src/runtime/testdata/testprogcgo/eintr.go
index 791ff1bedc..1722a75eb9 100644
--- a/src/runtime/testdata/testprogcgo/eintr.go
+++ b/src/runtime/testdata/testprogcgo/eintr.go
@@ -32,7 +32,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"log"
"net"
"os"
@@ -242,5 +241,5 @@ func testExec(wg *sync.WaitGroup) {
// Block blocks until stdin is closed.
func Block() {
- io.Copy(ioutil.Discard, os.Stdin)
+ io.Copy(io.Discard, os.Stdin)
}
diff --git a/src/strings/reader_test.go b/src/strings/reader_test.go
index a4c211d699..5adea6f7ab 100644
--- a/src/strings/reader_test.go
+++ b/src/strings/reader_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"strings"
"sync"
"testing"
@@ -162,7 +161,7 @@ func TestWriteTo(t *testing.T) {
// tests that Len is affected by reads, but Size is not.
func TestReaderLenSize(t *testing.T) {
r := strings.NewReader("abc")
- io.CopyN(ioutil.Discard, r, 1)
+ io.CopyN(io.Discard, r, 1)
if r.Len() != 2 {
t.Errorf("Len = %d; want 2", r.Len())
}
@@ -182,7 +181,7 @@ func TestReaderReset(t *testing.T) {
if err := r.UnreadRune(); err == nil {
t.Errorf("UnreadRune: expected error, got nil")
}
- buf, err := ioutil.ReadAll(r)
+ buf, err := io.ReadAll(r)
if err != nil {
t.Errorf("ReadAll: unexpected error: %v", err)
}
@@ -228,7 +227,7 @@ func TestReaderZero(t *testing.T) {
t.Errorf("UnreadRune: got nil, want error")
}
- if n, err := (&strings.Reader{}).WriteTo(ioutil.Discard); n != 0 || err != nil {
+ if n, err := (&strings.Reader{}).WriteTo(io.Discard); n != 0 || err != nil {
t.Errorf("WriteTo: got %d, %v; want 0, nil", n, err)
}
}
diff --git a/src/syscall/mkpost.go b/src/syscall/mkpost.go
index d5f5c8d6d6..ef89128310 100644
--- a/src/syscall/mkpost.go
+++ b/src/syscall/mkpost.go
@@ -14,7 +14,7 @@ package main
import (
"fmt"
"go/format"
- "io/ioutil"
+ "io"
"log"
"os"
"regexp"
@@ -22,7 +22,7 @@ import (
)
func main() {
- b, err := ioutil.ReadAll(os.Stdin)
+ b, err := io.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
diff --git a/src/syscall/syscall_unix_test.go b/src/syscall/syscall_unix_test.go
index d754c075f1..1c34ed2c27 100644
--- a/src/syscall/syscall_unix_test.go
+++ b/src/syscall/syscall_unix_test.go
@@ -225,7 +225,7 @@ func TestPassFD(t *testing.T) {
f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
defer f.Close()
- got, err := ioutil.ReadAll(f)
+ got, err := io.ReadAll(f)
want := "Hello from child process!\n"
if string(got) != want {
t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
diff --git a/src/testing/iotest/reader.go b/src/testing/iotest/reader.go
index 33b782dcb6..770d87f26b 100644
--- a/src/testing/iotest/reader.go
+++ b/src/testing/iotest/reader.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
)
// OneByteReader returns a Reader that implements
@@ -142,7 +141,7 @@ func TestReader(r io.Reader, content []byte) error {
}
}
- data, err := ioutil.ReadAll(&smallByteReader{r: r})
+ data, err := io.ReadAll(&smallByteReader{r: r})
if err != nil {
return err
}
@@ -181,7 +180,7 @@ func TestReader(r io.Reader, content []byte) error {
}
// Reading forward should return the last part of the file.
- data, err := ioutil.ReadAll(&smallByteReader{r: r})
+ data, err := io.ReadAll(&smallByteReader{r: r})
if err != nil {
return fmt.Errorf("ReadAll from offset %d: %v", middle, err)
}
@@ -198,7 +197,7 @@ func TestReader(r io.Reader, content []byte) error {
}
// Reading forward should return the last part of the file (again).
- data, err = ioutil.ReadAll(&smallByteReader{r: r})
+ data, err = io.ReadAll(&smallByteReader{r: r})
if err != nil {
return fmt.Errorf("ReadAll from offset %d: %v", middle, err)
}
@@ -210,7 +209,7 @@ func TestReader(r io.Reader, content []byte) error {
if off, err := r.Seek(int64(middle/2), 0); off != int64(middle/2) || err != nil {
return fmt.Errorf("Seek(%d, 0) from EOF = %d, %v, want %d, nil", middle/2, off, err, middle/2)
}
- data, err = ioutil.ReadAll(r)
+ data, err = io.ReadAll(r)
if err != nil {
return fmt.Errorf("ReadAll from offset %d: %v", middle/2, err)
}
diff --git a/src/text/tabwriter/tabwriter_test.go b/src/text/tabwriter/tabwriter_test.go
index 6a97d4c427..a51358dbed 100644
--- a/src/text/tabwriter/tabwriter_test.go
+++ b/src/text/tabwriter/tabwriter_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"testing"
. "text/tabwriter"
)
@@ -664,7 +663,7 @@ func BenchmarkTable(b *testing.B) {
b.Run("new", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
- w := NewWriter(ioutil.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
+ w := NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
// Write the line h times.
for j := 0; j < h; j++ {
w.Write(line)
@@ -675,7 +674,7 @@ func BenchmarkTable(b *testing.B) {
b.Run("reuse", func(b *testing.B) {
b.ReportAllocs()
- w := NewWriter(ioutil.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
+ w := NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
for i := 0; i < b.N; i++ {
// Write the line h times.
for j := 0; j < h; j++ {
@@ -696,7 +695,7 @@ func BenchmarkPyramid(b *testing.B) {
b.Run(fmt.Sprintf("%d", x), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
- w := NewWriter(ioutil.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
+ w := NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
// Write increasing prefixes of that line.
for j := 0; j < x; j++ {
w.Write(line[:j*2])
@@ -718,7 +717,7 @@ func BenchmarkRagged(b *testing.B) {
b.Run(fmt.Sprintf("%d", h), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
- w := NewWriter(ioutil.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
+ w := NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
// Write the lines in turn h times.
for j := 0; j < h; j++ {
w.Write(lines[j%len(lines)])
@@ -746,7 +745,7 @@ lines
func BenchmarkCode(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
- w := NewWriter(ioutil.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
+ w := NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings
// The code is small, so it's reasonable for the tabwriter user
// to write it all at once, or buffer the writes.
w.Write([]byte(codeSnippet))
diff --git a/src/text/template/exec_test.go b/src/text/template/exec_test.go
index 3309b33e3e..1611ee054f 100644
--- a/src/text/template/exec_test.go
+++ b/src/text/template/exec_test.go
@@ -9,7 +9,7 @@ import (
"errors"
"flag"
"fmt"
- "io/ioutil"
+ "io"
"reflect"
"strings"
"testing"
@@ -1328,7 +1328,7 @@ func TestExecuteGivesExecError(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- err = tmpl.Execute(ioutil.Discard, 0)
+ err = tmpl.Execute(io.Discard, 0)
if err == nil {
t.Fatal("expected error; got none")
}
@@ -1474,7 +1474,7 @@ func TestEvalFieldErrors(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
tmpl := Must(New("tmpl").Parse(tc.src))
- err := tmpl.Execute(ioutil.Discard, tc.value)
+ err := tmpl.Execute(io.Discard, tc.value)
got := ""
if err != nil {
got = err.Error()
@@ -1491,7 +1491,7 @@ func TestMaxExecDepth(t *testing.T) {
t.Skip("skipping in -short mode")
}
tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))
- err := tmpl.Execute(ioutil.Discard, nil)
+ err := tmpl.Execute(io.Discard, nil)
got := ""
if err != nil {
got = err.Error()
diff --git a/src/time/genzabbrs.go b/src/time/genzabbrs.go
index 38397f91b7..1d59ba73ce 100644
--- a/src/time/genzabbrs.go
+++ b/src/time/genzabbrs.go
@@ -17,6 +17,7 @@ import (
"encoding/xml"
"flag"
"go/format"
+ "io"
"io/ioutil"
"log"
"net/http"
@@ -71,7 +72,7 @@ func readWindowsZones() ([]*zone, error) {
}
defer r.Body.Close()
- data, err := ioutil.ReadAll(r.Body)
+ data, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
--
cgit v1.3
From b7a2d413a3f710f14accedf185c93bfb63d24fd0 Mon Sep 17 00:00:00 2001
From: Martin Möhrmann
Date: Tue, 20 Oct 2020 09:56:14 +0200
Subject: testing: print cpu type as label for benchmarks
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Supports 386 and amd64 architectures on all operating systems.
Example output:
$ go test -bench=.*
goos: darwin
goarch: amd64
pkg: strconv
cpu: Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz
BenchmarkAtof64Decimal-4 24431032 46.8 ns/op
...
As the displayed CPU information is only used for information
purposes it is lazily initialized when needed using the new
internal/sysinfo package.
This allows internal/cpu to stay without dependencies and avoid
initialization costs when the CPU information is not needed as
the new code to query the CPU name in internal/cpu can be
dead code eliminated if not used.
Fixes #39214
Change-Id: I77ae5c5d2fed6b28fa78dd45075f9f0a6a7f1bfd
Reviewed-on: https://go-review.googlesource.com/c/go/+/263804
Trust: Martin Möhrmann
Reviewed-by: Keith Randall
---
src/go/build/deps_test.go | 6 ++++-
src/internal/cpu/cpu_no_name.go | 19 ++++++++++++++++
src/internal/cpu/cpu_x86.go | 49 +++++++++++++++++++++++++++++++++++++++++
src/internal/sysinfo/sysinfo.go | 31 ++++++++++++++++++++++++++
src/testing/benchmark.go | 7 ++++++
5 files changed, 111 insertions(+), 1 deletion(-)
create mode 100644 src/internal/cpu/cpu_no_name.go
create mode 100644 src/internal/sysinfo/sysinfo.go
(limited to 'src/testing')
diff --git a/src/go/build/deps_test.go b/src/go/build/deps_test.go
index 4d866c87b6..ba7a76318f 100644
--- a/src/go/build/deps_test.go
+++ b/src/go/build/deps_test.go
@@ -467,6 +467,10 @@ var depsRules = `
< net/rpc
< net/rpc/jsonrpc;
+ # System Information
+ internal/cpu, sync
+ < internal/sysinfo;
+
# Test-only
log
< testing/iotest
@@ -475,7 +479,7 @@ var depsRules = `
FMT, flag, math/rand
< testing/quick;
- FMT, flag, runtime/debug, runtime/trace
+ FMT, flag, runtime/debug, runtime/trace, internal/sysinfo
< testing;
internal/testlog, runtime/pprof, regexp
diff --git a/src/internal/cpu/cpu_no_name.go b/src/internal/cpu/cpu_no_name.go
new file mode 100644
index 0000000000..ce1c37a3c7
--- /dev/null
+++ b/src/internal/cpu/cpu_no_name.go
@@ -0,0 +1,19 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !386
+// +build !amd64
+
+package cpu
+
+// Name returns the CPU name given by the vendor
+// if it can be read directly from memory or by CPU instructions.
+// If the CPU name can not be determined an empty string is returned.
+//
+// Implementations that use the Operating System (e.g. sysctl or /sys/)
+// to gather CPU information for display should be placed in internal/sysinfo.
+func Name() string {
+ // "A CPU has no name".
+ return ""
+}
diff --git a/src/internal/cpu/cpu_x86.go b/src/internal/cpu/cpu_x86.go
index da6cf67258..fb414adaf8 100644
--- a/src/internal/cpu/cpu_x86.go
+++ b/src/internal/cpu/cpu_x86.go
@@ -38,6 +38,8 @@ const (
cpuid_ADX = 1 << 19
)
+var maxExtendedFunctionInformation uint32
+
func doinit() {
options = []option{
{Name: "adx", Feature: &X86.HasADX},
@@ -65,6 +67,8 @@ func doinit() {
return
}
+ maxExtendedFunctionInformation, _, _, _ = cpuid(0x80000000, 0)
+
_, _, ecx1, edx1 := cpuid(1, 0)
X86.HasSSE2 = isSet(edx1, cpuid_SSE2)
@@ -103,3 +107,48 @@ func doinit() {
func isSet(hwc uint32, value uint32) bool {
return hwc&value != 0
}
+
+// Name returns the CPU name given by the vendor.
+// If the CPU name can not be determined an
+// empty string is returned.
+func Name() string {
+ if maxExtendedFunctionInformation < 0x80000004 {
+ return ""
+ }
+
+ data := make([]byte, 0, 3*4*4)
+
+ var eax, ebx, ecx, edx uint32
+ eax, ebx, ecx, edx = cpuid(0x80000002, 0)
+ data = appendBytes(data, eax, ebx, ecx, edx)
+ eax, ebx, ecx, edx = cpuid(0x80000003, 0)
+ data = appendBytes(data, eax, ebx, ecx, edx)
+ eax, ebx, ecx, edx = cpuid(0x80000004, 0)
+ data = appendBytes(data, eax, ebx, ecx, edx)
+
+ // Trim leading spaces.
+ for len(data) > 0 && data[0] == ' ' {
+ data = data[1:]
+ }
+
+ // Trim tail after and including the first null byte.
+ for i, c := range data {
+ if c == '\x00' {
+ data = data[:i]
+ break
+ }
+ }
+
+ return string(data)
+}
+
+func appendBytes(b []byte, args ...uint32) []byte {
+ for _, arg := range args {
+ b = append(b,
+ byte((arg >> 0)),
+ byte((arg >> 8)),
+ byte((arg >> 16)),
+ byte((arg >> 24)))
+ }
+ return b
+}
diff --git a/src/internal/sysinfo/sysinfo.go b/src/internal/sysinfo/sysinfo.go
new file mode 100644
index 0000000000..961be7abae
--- /dev/null
+++ b/src/internal/sysinfo/sysinfo.go
@@ -0,0 +1,31 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package sysinfo implements high level hardware information gathering
+// that can be used for debugging or information purposes.
+package sysinfo
+
+import (
+ internalcpu "internal/cpu"
+ "sync"
+)
+
+type cpuInfo struct {
+ once sync.Once
+ name string
+}
+
+var CPU cpuInfo
+
+func (cpu *cpuInfo) Name() string {
+ cpu.once.Do(func() {
+ // Try to get the information from internal/cpu.
+ if name := internalcpu.Name(); name != "" {
+ cpu.name = name
+ return
+ }
+ // TODO(martisch): use /proc/cpuinfo and /sys/devices/system/cpu/ on Linux as fallback.
+ })
+ return cpu.name
+}
diff --git a/src/testing/benchmark.go b/src/testing/benchmark.go
index e9687bf26d..1b81ec3a2d 100644
--- a/src/testing/benchmark.go
+++ b/src/testing/benchmark.go
@@ -8,6 +8,7 @@ import (
"flag"
"fmt"
"internal/race"
+ "internal/sysinfo"
"io"
"math"
"os"
@@ -262,6 +263,9 @@ func (b *B) run() {
if b.importPath != "" {
fmt.Fprintf(b.w, "pkg: %s\n", b.importPath)
}
+ if cpu := sysinfo.CPU.Name(); cpu != "" {
+ fmt.Fprintf(b.w, "cpu: %s\n", cpu)
+ }
})
if b.context != nil {
// Running go test --test.bench
@@ -648,6 +652,9 @@ func (b *B) Run(name string, f func(b *B)) bool {
if b.importPath != "" {
fmt.Printf("pkg: %s\n", b.importPath)
}
+ if cpu := sysinfo.CPU.Name(); cpu != "" {
+ fmt.Printf("cpu: %s\n", cpu)
+ }
})
fmt.Println(benchName)
--
cgit v1.3
From b5ddc42b465dd5b9532ee336d98343d81a6d35b2 Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Thu, 22 Oct 2020 12:11:29 -0400
Subject: io/fs, path, path/filepath, testing/fstest: validate patterns in
Match, Glob
According to #28614, proposal review agreed in December 2018 that
Match should return an error for failed matches where the unmatched
part of the pattern has a syntax error. (The failed match has to date
caused the scan of the pattern to stop early.)
This change implements that behavior: the match loop continues
scanning to the end of the pattern, even after a confirmed mismatch,
to check whether the pattern is even well-formed.
The change applies to both path.Match and filepath.Match.
Then filepath.Glob and fs.Glob make a single validity-checking
call to Match before beginning their usual processing.
Also update fstest.TestFS to check for correct validation in custom
Glob implementations.
Fixes #28614.
Change-Id: Ic1d35a4bb9c3565184ae83dbefc425c5c96318e7
Reviewed-on: https://go-review.googlesource.com/c/go/+/264397
Trust: Russ Cox
Reviewed-by: Rob Pike
---
src/io/fs/glob.go | 4 +++
src/io/fs/glob_test.go | 10 +++++--
src/path/filepath/match.go | 61 +++++++++++++++++++++++++----------------
src/path/filepath/match_test.go | 12 +++++---
src/path/match.go | 60 +++++++++++++++++++++++++++-------------
src/path/match_test.go | 4 ++-
src/testing/fstest/testfs.go | 6 ++++
7 files changed, 106 insertions(+), 51 deletions(-)
(limited to 'src/testing')
diff --git a/src/io/fs/glob.go b/src/io/fs/glob.go
index 77f6ebbaaf..cde6c49f3d 100644
--- a/src/io/fs/glob.go
+++ b/src/io/fs/glob.go
@@ -36,6 +36,10 @@ func Glob(fsys FS, pattern string) (matches []string, err error) {
return fsys.Glob(pattern)
}
+ // Check pattern is well-formed.
+ if _, err := path.Match(pattern, ""); err != nil {
+ return nil, err
+ }
if !hasMeta(pattern) {
if _, err = Stat(fsys, pattern); err != nil {
return nil, nil
diff --git a/src/io/fs/glob_test.go b/src/io/fs/glob_test.go
index 0183a49b6c..5c8ac3fbf3 100644
--- a/src/io/fs/glob_test.go
+++ b/src/io/fs/glob_test.go
@@ -7,6 +7,7 @@ package fs_test
import (
. "io/fs"
"os"
+ "path"
"testing"
)
@@ -44,9 +45,12 @@ func TestGlob(t *testing.T) {
}
func TestGlobError(t *testing.T) {
- _, err := Glob(os.DirFS("."), "[]")
- if err == nil {
- t.Error("expected error for bad pattern; got none")
+ bad := []string{`[]`, `nonexist/[]`}
+ for _, pattern := range bad {
+ _, err := Glob(os.DirFS("."), pattern)
+ if err != path.ErrBadPattern {
+ t.Errorf("Glob(fs, %#q) returned err=%v, want path.ErrBadPattern", pattern, err)
+ }
}
}
diff --git a/src/path/filepath/match.go b/src/path/filepath/match.go
index 20a334805b..c77a26952a 100644
--- a/src/path/filepath/match.go
+++ b/src/path/filepath/match.go
@@ -122,25 +122,28 @@ Scan:
// If so, it returns the remainder of s (after the match).
// Chunk is all single-character operators: literals, char classes, and ?.
func matchChunk(chunk, s string) (rest string, ok bool, err error) {
+ // failed records whether the match has failed.
+ // After the match fails, the loop continues on processing chunk,
+ // checking that the pattern is well-formed but no longer reading s.
+ failed := false
for len(chunk) > 0 {
- if len(s) == 0 {
- return
+ if !failed && len(s) == 0 {
+ failed = true
}
switch chunk[0] {
case '[':
// character class
- r, n := utf8.DecodeRuneInString(s)
- s = s[n:]
- chunk = chunk[1:]
- // We can't end right after '[', we're expecting at least
- // a closing bracket and possibly a caret.
- if len(chunk) == 0 {
- err = ErrBadPattern
- return
+ var r rune
+ if !failed {
+ var n int
+ r, n = utf8.DecodeRuneInString(s)
+ s = s[n:]
}
+ chunk = chunk[1:]
// possibly negated
- negated := chunk[0] == '^'
- if negated {
+ negated := false
+ if len(chunk) > 0 && chunk[0] == '^' {
+ negated = true
chunk = chunk[1:]
}
// parse all ranges
@@ -153,12 +156,12 @@ func matchChunk(chunk, s string) (rest string, ok bool, err error) {
}
var lo, hi rune
if lo, chunk, err = getEsc(chunk); err != nil {
- return
+ return "", false, err
}
hi = lo
if chunk[0] == '-' {
if hi, chunk, err = getEsc(chunk[1:]); err != nil {
- return
+ return "", false, err
}
}
if lo <= r && r <= hi {
@@ -167,35 +170,41 @@ func matchChunk(chunk, s string) (rest string, ok bool, err error) {
nrange++
}
if match == negated {
- return
+ failed = true
}
case '?':
- if s[0] == Separator {
- return
+ if !failed {
+ if s[0] == Separator {
+ failed = true
+ }
+ _, n := utf8.DecodeRuneInString(s)
+ s = s[n:]
}
- _, n := utf8.DecodeRuneInString(s)
- s = s[n:]
chunk = chunk[1:]
case '\\':
if runtime.GOOS != "windows" {
chunk = chunk[1:]
if len(chunk) == 0 {
- err = ErrBadPattern
- return
+ return "", false, ErrBadPattern
}
}
fallthrough
default:
- if chunk[0] != s[0] {
- return
+ if !failed {
+ if chunk[0] != s[0] {
+ failed = true
+ }
+ s = s[1:]
}
- s = s[1:]
chunk = chunk[1:]
}
}
+ if failed {
+ return "", false, nil
+ }
return s, true, nil
}
@@ -232,6 +241,10 @@ func getEsc(chunk string) (r rune, nchunk string, err error) {
// The only possible returned error is ErrBadPattern, when pattern
// is malformed.
func Glob(pattern string) (matches []string, err error) {
+ // Check pattern is well-formed.
+ if _, err := Match(pattern, ""); err != nil {
+ return nil, err
+ }
if !hasMeta(pattern) {
if _, err = os.Lstat(pattern); err != nil {
return nil, nil
diff --git a/src/path/filepath/match_test.go b/src/path/filepath/match_test.go
index b8657626bc..1c3b567fa3 100644
--- a/src/path/filepath/match_test.go
+++ b/src/path/filepath/match_test.go
@@ -75,8 +75,10 @@ var matchTests = []MatchTest{
{"[", "a", false, ErrBadPattern},
{"[^", "a", false, ErrBadPattern},
{"[^bc", "a", false, ErrBadPattern},
- {"a[", "a", false, nil},
+ {"a[", "a", false, ErrBadPattern},
{"a[", "ab", false, ErrBadPattern},
+ {"a[", "x", false, ErrBadPattern},
+ {"a/b[", "x", false, ErrBadPattern},
{"*x", "xxx", true, nil},
}
@@ -155,9 +157,11 @@ func TestGlob(t *testing.T) {
}
func TestGlobError(t *testing.T) {
- _, err := Glob("[]")
- if err == nil {
- t.Error("expected error for bad pattern; got none")
+ bad := []string{`[]`, `nonexist/[]`}
+ for _, pattern := range bad {
+ if _, err := Glob(pattern); err != ErrBadPattern {
+ t.Errorf("Glob(%#q) returned err=%v, want ErrBadPattern", pattern, err)
+ }
}
}
diff --git a/src/path/match.go b/src/path/match.go
index 837eb8bb8b..918624c60e 100644
--- a/src/path/match.go
+++ b/src/path/match.go
@@ -75,6 +75,14 @@ Pattern:
}
}
}
+ // Before returning false with no error,
+ // check that the remainder of the pattern is syntactically valid.
+ for len(pattern) > 0 {
+ _, chunk, pattern = scanChunk(pattern)
+ if _, _, err := matchChunk(chunk, ""); err != nil {
+ return false, err
+ }
+ }
return false, nil
}
return len(name) == 0, nil
@@ -114,20 +122,28 @@ Scan:
// If so, it returns the remainder of s (after the match).
// Chunk is all single-character operators: literals, char classes, and ?.
func matchChunk(chunk, s string) (rest string, ok bool, err error) {
+ // failed records whether the match has failed.
+ // After the match fails, the loop continues on processing chunk,
+ // checking that the pattern is well-formed but no longer reading s.
+ failed := false
for len(chunk) > 0 {
- if len(s) == 0 {
- return
+ if !failed && len(s) == 0 {
+ failed = true
}
switch chunk[0] {
case '[':
// character class
- r, n := utf8.DecodeRuneInString(s)
- s = s[n:]
+ var r rune
+ if !failed {
+ var n int
+ r, n = utf8.DecodeRuneInString(s)
+ s = s[n:]
+ }
chunk = chunk[1:]
// possibly negated
- notNegated := true
+ negated := false
if len(chunk) > 0 && chunk[0] == '^' {
- notNegated = false
+ negated = true
chunk = chunk[1:]
}
// parse all ranges
@@ -140,12 +156,12 @@ func matchChunk(chunk, s string) (rest string, ok bool, err error) {
}
var lo, hi rune
if lo, chunk, err = getEsc(chunk); err != nil {
- return
+ return "", false, err
}
hi = lo
if chunk[0] == '-' {
if hi, chunk, err = getEsc(chunk[1:]); err != nil {
- return
+ return "", false, err
}
}
if lo <= r && r <= hi {
@@ -153,34 +169,40 @@ func matchChunk(chunk, s string) (rest string, ok bool, err error) {
}
nrange++
}
- if match != notNegated {
- return
+ if match == negated {
+ failed = true
}
case '?':
- if s[0] == '/' {
- return
+ if !failed {
+ if s[0] == '/' {
+ failed = true
+ }
+ _, n := utf8.DecodeRuneInString(s)
+ s = s[n:]
}
- _, n := utf8.DecodeRuneInString(s)
- s = s[n:]
chunk = chunk[1:]
case '\\':
chunk = chunk[1:]
if len(chunk) == 0 {
- err = ErrBadPattern
- return
+ return "", false, ErrBadPattern
}
fallthrough
default:
- if chunk[0] != s[0] {
- return
+ if !failed {
+ if chunk[0] != s[0] {
+ failed = true
+ }
+ s = s[1:]
}
- s = s[1:]
chunk = chunk[1:]
}
}
+ if failed {
+ return "", false, nil
+ }
return s, true, nil
}
diff --git a/src/path/match_test.go b/src/path/match_test.go
index 3e027e1f68..996bd691eb 100644
--- a/src/path/match_test.go
+++ b/src/path/match_test.go
@@ -67,8 +67,10 @@ var matchTests = []MatchTest{
{"[", "a", false, ErrBadPattern},
{"[^", "a", false, ErrBadPattern},
{"[^bc", "a", false, ErrBadPattern},
- {"a[", "a", false, nil},
+ {"a[", "a", false, ErrBadPattern},
{"a[", "ab", false, ErrBadPattern},
+ {"a[", "x", false, ErrBadPattern},
+ {"a/b[", "x", false, ErrBadPattern},
{"*x", "xxx", true, nil},
}
diff --git a/src/testing/fstest/testfs.go b/src/testing/fstest/testfs.go
index 21cd00e5b6..4912a271b2 100644
--- a/src/testing/fstest/testfs.go
+++ b/src/testing/fstest/testfs.go
@@ -282,6 +282,12 @@ func (t *fsTester) checkGlob(dir string, list []fs.DirEntry) {
glob = strings.Join(elem, "/") + "/"
}
+ // Test that malformed patterns are detected.
+ // The error is likely path.ErrBadPattern but need not be.
+ if _, err := t.fsys.(fs.GlobFS).Glob(glob + "nonexist/[]"); err == nil {
+ t.errorf("%s: Glob(%#q): bad pattern not detected", dir, glob+"nonexist/[]")
+ }
+
// Try to find a letter that appears in only some of the final names.
c := rune('a')
for ; c <= 'z'; c++ {
--
cgit v1.3
From afe7c8d0b25f26f0abd749ca52c7e1e7dfdee8cb Mon Sep 17 00:00:00 2001
From: Austin Clements
Date: Mon, 2 Nov 2020 08:48:23 -0500
Subject: testing: increase benchmark output to four significant figures
Currently, the benchmark output from the testing package prints small
values with three significant figures. This means it can only
distinguish 1 part in 100, or a 1% error, which can be enough to throw
off further analysis of the output. This CL increases it to four
significant figures. For time values, at least, anything beyond four
significant figures is almost certainly noise.
Fixes #34626.
Change-Id: I3bcf305427130026276e6a4c78167989319f280c
Reviewed-on: https://go-review.googlesource.com/c/go/+/267102
Trust: Austin Clements
Run-TryBot: Austin Clements
TryBot-Result: Go Bot
Reviewed-by: Michael Pratt
---
src/testing/benchmark.go | 20 ++++++++++++--------
src/testing/benchmark_test.go | 21 +++++++++++----------
2 files changed, 23 insertions(+), 18 deletions(-)
(limited to 'src/testing')
diff --git a/src/testing/benchmark.go b/src/testing/benchmark.go
index 1b81ec3a2d..a8f75e9712 100644
--- a/src/testing/benchmark.go
+++ b/src/testing/benchmark.go
@@ -451,23 +451,27 @@ func (r BenchmarkResult) String() string {
func prettyPrint(w io.Writer, x float64, unit string) {
// Print all numbers with 10 places before the decimal point
- // and small numbers with three sig figs.
+ // and small numbers with four sig figs. Field widths are
+ // chosen to fit the whole part in 10 places while aligning
+ // the decimal point of all fractional formats.
var format string
switch y := math.Abs(x); {
- case y == 0 || y >= 99.95:
+ case y == 0 || y >= 999.95:
format = "%10.0f %s"
- case y >= 9.995:
+ case y >= 99.995:
format = "%12.1f %s"
- case y >= 0.9995:
+ case y >= 9.9995:
format = "%13.2f %s"
- case y >= 0.09995:
+ case y >= 0.99995:
format = "%14.3f %s"
- case y >= 0.009995:
+ case y >= 0.099995:
format = "%15.4f %s"
- case y >= 0.0009995:
+ case y >= 0.0099995:
format = "%16.5f %s"
- default:
+ case y >= 0.00099995:
format = "%17.6f %s"
+ default:
+ format = "%18.7f %s"
}
fmt.Fprintf(w, format, x, unit)
}
diff --git a/src/testing/benchmark_test.go b/src/testing/benchmark_test.go
index 1434c2613f..4c1cbd1933 100644
--- a/src/testing/benchmark_test.go
+++ b/src/testing/benchmark_test.go
@@ -22,13 +22,14 @@ var prettyPrintTests = []struct {
{0, " 0 x"},
{1234.1, " 1234 x"},
{-1234.1, " -1234 x"},
- {99.950001, " 100 x"},
- {99.949999, " 99.9 x"},
- {9.9950001, " 10.0 x"},
- {9.9949999, " 9.99 x"},
- {-9.9949999, " -9.99 x"},
- {0.0099950001, " 0.0100 x"},
- {0.0099949999, " 0.00999 x"},
+ {999.950001, " 1000 x"},
+ {999.949999, " 999.9 x"},
+ {99.9950001, " 100.0 x"},
+ {99.9949999, " 99.99 x"},
+ {-99.9949999, " -99.99 x"},
+ {0.000999950001, " 0.001000 x"},
+ {0.000999949999, " 0.0009999 x"}, // smallest case
+ {0.0000999949999, " 0.0001000 x"},
}
func TestPrettyPrint(t *testing.T) {
@@ -50,13 +51,13 @@ func TestResultString(t *testing.T) {
if r.NsPerOp() != 2 {
t.Errorf("NsPerOp: expected 2, actual %v", r.NsPerOp())
}
- if want, got := " 100\t 2.40 ns/op", r.String(); want != got {
+ if want, got := " 100\t 2.400 ns/op", r.String(); want != got {
t.Errorf("String: expected %q, actual %q", want, got)
}
// Test sub-1 ns/op (issue #31005)
r.T = 40 * time.Nanosecond
- if want, got := " 100\t 0.400 ns/op", r.String(); want != got {
+ if want, got := " 100\t 0.4000 ns/op", r.String(); want != got {
t.Errorf("String: expected %q, actual %q", want, got)
}
@@ -130,7 +131,7 @@ func TestReportMetric(t *testing.T) {
}
// Test stringing.
res.N = 1 // Make the output stable
- want := " 1\t 12345 ns/op\t 0.200 frobs/op"
+ want := " 1\t 12345 ns/op\t 0.2000 frobs/op"
if want != res.String() {
t.Errorf("expected %q, actual %q", want, res.String())
}
--
cgit v1.3
From 4c174a7ba66724f8f9a1915c8f4868a8b3aaf219 Mon Sep 17 00:00:00 2001
From: Bryan Boreham
Date: Wed, 11 Nov 2020 13:59:59 +0000
Subject: testing: reduce memory allocation in Helper
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Store the PC instead of the string name of the function, and defer
that conversion until we need it.
Helper is still relatively expensive in CPU time (few hundred ns),
but memory allocation is now constant for a test rather than linear in
the number of times Helper is called.
benchstat:
name old time/op new time/op delta
TBHelper-4 1.30µs ±27% 0.53µs ± 1% -59.03% (p=0.008 n=5+5)
name old alloc/op new alloc/op delta
TBHelper-4 216B ± 0% 0B -100.00% (p=0.008 n=5+5)
name old allocs/op new allocs/op delta
TBHelper-4 2.00 ± 0% 0.00 -100.00% (p=0.008 n=5+5)
Change-Id: I6565feb491513815e1058637d086b0374fa94e19
GitHub-Last-Rev: c2329cf225dab6de7309af3583daa011bafb9a62
GitHub-Pull-Request: golang/go#38834
Reviewed-on: https://go-review.googlesource.com/c/go/+/231717
Run-TryBot: Ian Lance Taylor
TryBot-Result: Go Bot
Reviewed-by: Ian Lance Taylor
Reviewed-by: Emmanuel Odeke
Trust: Emmanuel Odeke
---
src/testing/testing.go | 56 +++++++++++++++++++++++++++++++++++---------------
1 file changed, 39 insertions(+), 17 deletions(-)
(limited to 'src/testing')
diff --git a/src/testing/testing.go b/src/testing/testing.go
index a44c0a0749..d4b108a183 100644
--- a/src/testing/testing.go
+++ b/src/testing/testing.go
@@ -384,17 +384,18 @@ const maxStackLen = 50
// common holds the elements common between T and B and
// captures common methods such as Errorf.
type common struct {
- mu sync.RWMutex // guards this group of fields
- output []byte // Output generated by test or benchmark.
- w io.Writer // For flushToParent.
- ran bool // Test or benchmark (or one of its subtests) was executed.
- failed bool // Test or benchmark has failed.
- skipped bool // Test of benchmark has been skipped.
- done bool // Test is finished and all subtests have completed.
- helpers map[string]struct{} // functions to be skipped when writing file/line info
- cleanups []func() // optional functions to be called at the end of the test
- cleanupName string // Name of the cleanup function.
- cleanupPc []uintptr // The stack trace at the point where Cleanup was called.
+ mu sync.RWMutex // guards this group of fields
+ output []byte // Output generated by test or benchmark.
+ w io.Writer // For flushToParent.
+ ran bool // Test or benchmark (or one of its subtests) was executed.
+ failed bool // Test or benchmark has failed.
+ skipped bool // Test of benchmark has been skipped.
+ done bool // Test is finished and all subtests have completed.
+ helperPCs map[uintptr]struct{} // functions to be skipped when writing file/line info
+ helperNames map[string]struct{} // helperPCs converted to function names
+ cleanups []func() // optional functions to be called at the end of the test
+ cleanupName string // Name of the cleanup function.
+ cleanupPc []uintptr // The stack trace at the point where Cleanup was called.
chatty *chattyPrinter // A copy of chattyPrinter, if the chatty flag is set.
bench bool // Whether the current test is a benchmark.
@@ -509,7 +510,7 @@ func (c *common) frameSkip(skip int) runtime.Frame {
}
return prevFrame
}
- if _, ok := c.helpers[frame.Function]; !ok {
+ if _, ok := c.helperNames[frame.Function]; !ok {
// Found a frame that wasn't inside a helper function.
return frame
}
@@ -521,6 +522,14 @@ func (c *common) frameSkip(skip int) runtime.Frame {
// and inserts the final newline if needed and indentation spaces for formatting.
// This function must be called with c.mu held.
func (c *common) decorate(s string, skip int) string {
+ // If more helper PCs have been added since we last did the conversion
+ if c.helperNames == nil {
+ c.helperNames = make(map[string]struct{})
+ for pc := range c.helperPCs {
+ c.helperNames[pcToName(pc)] = struct{}{}
+ }
+ }
+
frame := c.frameSkip(skip)
file := frame.File
line := frame.Line
@@ -853,10 +862,19 @@ func (c *common) Skipped() bool {
func (c *common) Helper() {
c.mu.Lock()
defer c.mu.Unlock()
- if c.helpers == nil {
- c.helpers = make(map[string]struct{})
+ if c.helperPCs == nil {
+ c.helperPCs = make(map[uintptr]struct{})
+ }
+ // repeating code from callerName here to save walking a stack frame
+ var pc [1]uintptr
+ n := runtime.Callers(2, pc[:]) // skip runtime.Callers + Helper
+ if n == 0 {
+ panic("testing: zero callers found")
+ }
+ if _, found := c.helperPCs[pc[0]]; !found {
+ c.helperPCs[pc[0]] = struct{}{}
+ c.helperNames = nil // map will be recreated next time it is needed
}
- c.helpers[callerName(1)] = struct{}{}
}
// Cleanup registers a function to be called when the test and all its
@@ -995,13 +1013,17 @@ func (c *common) runCleanup(ph panicHandling) (panicVal interface{}) {
// callerName gives the function name (qualified with a package path)
// for the caller after skip frames (where 0 means the current function).
func callerName(skip int) string {
- // Make room for the skip PC.
var pc [1]uintptr
n := runtime.Callers(skip+2, pc[:]) // skip + runtime.Callers + callerName
if n == 0 {
panic("testing: zero callers found")
}
- frames := runtime.CallersFrames(pc[:n])
+ return pcToName(pc[0])
+}
+
+func pcToName(pc uintptr) string {
+ pcs := []uintptr{pc}
+ frames := runtime.CallersFrames(pcs)
frame, _ := frames.Next()
return frame.Function
}
--
cgit v1.3
From 478bde3a4388997924a02ee9296864866d8ba3ba Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Wed, 2 Dec 2020 12:49:20 -0500
Subject: io/fs: add Sub
Sub provides a convenient way to refer to a subdirectory
automatically in future operations, like Unix's chdir(2).
The CL also includes updates to fstest to check Sub implementations.
As part of updating fstest, I changed the meaning of TestFS's
expected list to introduce a special case: if you list no expected files,
that means the FS must be empty. In general it's OK not to list all
the expected files, but if you list none, that's almost certainly a
mistake - if your FS were broken and empty, you wouldn't find out.
Making no expected files mean "must be empty" makes the mistake
less likely - if your file system ever worked, then your test will keep
it working.
That change found a testing bug: embedtest was making exactly
that mistake.
Fixes #42322.
Change-Id: I63fd4aa866b30061a0e51ca9a1927e576d6ec41e
Reviewed-on: https://go-review.googlesource.com/c/go/+/274856
Trust: Russ Cox
Run-TryBot: Russ Cox
TryBot-Result: Go Bot
Reviewed-by: Ian Lance Taylor
---
doc/go1.16.html | 2 +-
src/embed/internal/embedtest/embed_test.go | 2 +-
src/io/fs/readdir_test.go | 12 ++-
src/io/fs/readfile_test.go | 16 ++++
src/io/fs/sub.go | 127 +++++++++++++++++++++++++++++
src/io/fs/sub_test.go | 57 +++++++++++++
src/os/file.go | 7 ++
src/testing/fstest/mapfs.go | 10 +++
src/testing/fstest/testfs.go | 42 ++++++++++
9 files changed, 271 insertions(+), 4 deletions(-)
create mode 100644 src/io/fs/sub.go
create mode 100644 src/io/fs/sub_test.go
(limited to 'src/testing')
diff --git a/doc/go1.16.html b/doc/go1.16.html
index 4d4b459009..62d9b97db8 100644
--- a/doc/go1.16.html
+++ b/doc/go1.16.html
@@ -384,7 +384,7 @@ Do not send CLs removing the interior tags from such phrases.
the new embed.FS type
implements fs.FS, as does
zip.Reader.
- The new os.Dir function
+ The new os.DirFS function
provides an implementation of fs.FS backed by a tree
of operating system files.
diff --git a/src/embed/internal/embedtest/embed_test.go b/src/embed/internal/embedtest/embed_test.go
index b1707a4c04..c6a7bea7a3 100644
--- a/src/embed/internal/embedtest/embed_test.go
+++ b/src/embed/internal/embedtest/embed_test.go
@@ -65,7 +65,7 @@ func TestGlobal(t *testing.T) {
testFiles(t, global, "testdata/hello.txt", "hello, world\n")
testFiles(t, global, "testdata/glass.txt", "I can eat glass and it doesn't hurt me.\n")
- if err := fstest.TestFS(global); err != nil {
+ if err := fstest.TestFS(global, "concurrency.txt", "testdata/hello.txt"); err != nil {
t.Fatal(err)
}
diff --git a/src/io/fs/readdir_test.go b/src/io/fs/readdir_test.go
index 46a4bc2788..405bfa67ca 100644
--- a/src/io/fs/readdir_test.go
+++ b/src/io/fs/readdir_test.go
@@ -16,12 +16,12 @@ func (readDirOnly) Open(name string) (File, error) { return nil, ErrNotExist }
func TestReadDir(t *testing.T) {
check := func(desc string, dirs []DirEntry, err error) {
t.Helper()
- if err != nil || len(dirs) != 1 || dirs[0].Name() != "hello.txt" {
+ if err != nil || len(dirs) != 2 || dirs[0].Name() != "hello.txt" || dirs[1].Name() != "sub" {
var names []string
for _, d := range dirs {
names = append(names, d.Name())
}
- t.Errorf("ReadDir(%s) = %v, %v, want %v, nil", desc, names, err, []string{"hello.txt"})
+ t.Errorf("ReadDir(%s) = %v, %v, want %v, nil", desc, names, err, []string{"hello.txt", "sub"})
}
}
@@ -32,4 +32,12 @@ func TestReadDir(t *testing.T) {
// Test that ReadDir uses Open when the method is not present.
dirs, err = ReadDir(openOnly{testFsys}, ".")
check("openOnly", dirs, err)
+
+ // Test that ReadDir on Sub of . works (sub_test checks non-trivial subs).
+ sub, err := Sub(testFsys, ".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ dirs, err = ReadDir(sub, ".")
+ check("sub(.)", dirs, err)
}
diff --git a/src/io/fs/readfile_test.go b/src/io/fs/readfile_test.go
index 0afa334ace..07219c1445 100644
--- a/src/io/fs/readfile_test.go
+++ b/src/io/fs/readfile_test.go
@@ -18,6 +18,12 @@ var testFsys = fstest.MapFS{
ModTime: time.Now(),
Sys: &sysValue,
},
+ "sub/goodbye.txt": {
+ Data: []byte("goodbye, world"),
+ Mode: 0456,
+ ModTime: time.Now(),
+ Sys: &sysValue,
+ },
}
var sysValue int
@@ -40,4 +46,14 @@ func TestReadFile(t *testing.T) {
if string(data) != "hello, world" || err != nil {
t.Fatalf(`ReadFile(openOnly, "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
}
+
+ // Test that ReadFile on Sub of . works (sub_test checks non-trivial subs).
+ sub, err := Sub(testFsys, ".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err = ReadFile(sub, "hello.txt")
+ if string(data) != "hello, world" || err != nil {
+ t.Fatalf(`ReadFile(sub(.), "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
+ }
}
diff --git a/src/io/fs/sub.go b/src/io/fs/sub.go
new file mode 100644
index 0000000000..381f409504
--- /dev/null
+++ b/src/io/fs/sub.go
@@ -0,0 +1,127 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs
+
+import (
+ "errors"
+ "path"
+)
+
+// A SubFS is a file system with a Sub method.
+type SubFS interface {
+ FS
+
+ // Sub returns an FS corresponding to the subtree rooted at dir.
+ Sub(dir string) (FS, error)
+}
+
+// Sub returns an FS corresponding to the subtree rooted at fsys's dir.
+//
+// If fs implements SubFS, Sub calls returns fsys.Sub(dir).
+// Otherwise, if dir is ".", Sub returns fsys unchanged.
+// Otherwise, Sub returns a new FS implementation sub that,
+// in effect, implements sub.Open(dir) as fsys.Open(path.Join(dir, name)).
+// The implementation also translates calls to ReadDir, ReadFile, and Glob appropriately.
+//
+// Note that Sub(os.DirFS("/"), "prefix") is equivalent to os.DirFS("/prefix")
+// and that neither of them guarantees to avoid operating system
+// accesses outside "/prefix", because the implementation of os.DirFS
+// does not check for symbolic links inside "/prefix" that point to
+// other directories. That is, os.DirFS is not a general substitute for a
+// chroot-style security mechanism, and Sub does not change that fact.
+func Sub(fsys FS, dir string) (FS, error) {
+ if !ValidPath(dir) {
+ return nil, &PathError{Op: "sub", Path: dir, Err: errors.New("invalid name")}
+ }
+ if dir == "." {
+ return fsys, nil
+ }
+ if fsys, ok := fsys.(SubFS); ok {
+ return fsys.Sub(dir)
+ }
+ return &subFS{fsys, dir}, nil
+}
+
+type subFS struct {
+ fsys FS
+ dir string
+}
+
+// fullName maps name to the fully-qualified name dir/name.
+func (f *subFS) fullName(op string, name string) (string, error) {
+ if !ValidPath(name) {
+ return "", &PathError{Op: op, Path: name, Err: errors.New("invalid name")}
+ }
+ return path.Join(f.dir, name), nil
+}
+
+// shorten maps name, which should start with f.dir, back to the suffix after f.dir.
+func (f *subFS) shorten(name string) (rel string, ok bool) {
+ if name == f.dir {
+ return ".", true
+ }
+ if len(name) >= len(f.dir)+2 && name[len(f.dir)] == '/' && name[:len(f.dir)] == f.dir {
+ return name[len(f.dir)+1:], true
+ }
+ return "", false
+}
+
+// fixErr shortens any reported names in PathErrors by stripping dir.
+func (f *subFS) fixErr(err error) error {
+ if e, ok := err.(*PathError); ok {
+ if short, ok := f.shorten(e.Path); ok {
+ e.Path = short
+ }
+ }
+ return err
+}
+
+func (f *subFS) Open(name string) (File, error) {
+ full, err := f.fullName("open", name)
+ if err != nil {
+ return nil, err
+ }
+ file, err := f.fsys.Open(full)
+ return file, f.fixErr(err)
+}
+
+func (f *subFS) ReadDir(name string) ([]DirEntry, error) {
+ full, err := f.fullName("open", name)
+ if err != nil {
+ return nil, err
+ }
+ dir, err := ReadDir(f.fsys, full)
+ return dir, f.fixErr(err)
+}
+
+func (f *subFS) ReadFile(name string) ([]byte, error) {
+ full, err := f.fullName("open", name)
+ if err != nil {
+ return nil, err
+ }
+ data, err := ReadFile(f.fsys, full)
+ return data, f.fixErr(err)
+}
+
+func (f *subFS) Glob(pattern string) ([]string, error) {
+ // Check pattern is well-formed.
+ if _, err := path.Match(pattern, ""); err != nil {
+ return nil, err
+ }
+ if pattern == "." {
+ return []string{"."}, nil
+ }
+
+ full := f.dir + "/" + pattern
+ list, err := Glob(f.fsys, full)
+ for i, name := range list {
+ name, ok := f.shorten(name)
+ if !ok {
+ return nil, errors.New("invalid result from inner fsys Glob: " + name + " not in " + f.dir) // can't use fmt in this package
+ }
+ list[i] = name
+ }
+ return list, f.fixErr(err)
+}
diff --git a/src/io/fs/sub_test.go b/src/io/fs/sub_test.go
new file mode 100644
index 0000000000..451b0efb02
--- /dev/null
+++ b/src/io/fs/sub_test.go
@@ -0,0 +1,57 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fs_test
+
+import (
+ . "io/fs"
+ "testing"
+)
+
+type subOnly struct{ SubFS }
+
+func (subOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+func TestSub(t *testing.T) {
+ check := func(desc string, sub FS, err error) {
+ t.Helper()
+ if err != nil {
+ t.Errorf("Sub(sub): %v", err)
+ return
+ }
+ data, err := ReadFile(sub, "goodbye.txt")
+ if string(data) != "goodbye, world" || err != nil {
+ t.Errorf(`ReadFile(%s, "goodbye.txt" = %q, %v, want %q, nil`, desc, string(data), err, "goodbye, world")
+ }
+
+ dirs, err := ReadDir(sub, ".")
+ if err != nil || len(dirs) != 1 || dirs[0].Name() != "goodbye.txt" {
+ var names []string
+ for _, d := range dirs {
+ names = append(names, d.Name())
+ }
+ t.Errorf(`ReadDir(%s, ".") = %v, %v, want %v, nil`, desc, names, err, []string{"goodbye.txt"})
+ }
+ }
+
+ // Test that Sub uses the method when present.
+ sub, err := Sub(subOnly{testFsys}, "sub")
+ check("subOnly", sub, err)
+
+ // Test that Sub uses Open when the method is not present.
+ sub, err = Sub(openOnly{testFsys}, "sub")
+ check("openOnly", sub, err)
+
+ _, err = sub.Open("nonexist")
+ if err == nil {
+ t.Fatal("Open(nonexist): succeeded")
+ }
+ pe, ok := err.(*PathError)
+ if !ok {
+ t.Fatalf("Open(nonexist): error is %T, want *PathError", err)
+ }
+ if pe.Path != "nonexist" {
+ t.Fatalf("Open(nonexist): err.Path = %q, want %q", pe.Path, "nonexist")
+ }
+}
diff --git a/src/os/file.go b/src/os/file.go
index 304b055dbe..416bc0efa6 100644
--- a/src/os/file.go
+++ b/src/os/file.go
@@ -609,6 +609,13 @@ func isWindowsNulName(name string) bool {
}
// DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.
+//
+// Note that DirFS("/prefix") only guarantees that the Open calls it makes to the
+// operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the
+// same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside
+// the /prefix tree, then using DirFS does not stop the access any more than using
+// os.Open does. DirFS is therefore not a general substitute for a chroot-style security
+// mechanism when the directory tree contains arbitrary content.
func DirFS(dir string) fs.FS {
return dirFS(dir)
}
diff --git a/src/testing/fstest/mapfs.go b/src/testing/fstest/mapfs.go
index 10e56f5b3c..a5d4a23fac 100644
--- a/src/testing/fstest/mapfs.go
+++ b/src/testing/fstest/mapfs.go
@@ -132,6 +132,16 @@ func (fsys MapFS) Glob(pattern string) ([]string, error) {
return fs.Glob(fsOnly{fsys}, pattern)
}
+type noSub struct {
+ MapFS
+}
+
+func (noSub) Sub() {} // not the fs.SubFS signature
+
+func (fsys MapFS) Sub(dir string) (fs.FS, error) {
+ return fs.Sub(noSub{fsys}, dir)
+}
+
// A mapFileInfo implements fs.FileInfo and fs.DirEntry for a given map file.
type mapFileInfo struct {
name string
diff --git a/src/testing/fstest/testfs.go b/src/testing/fstest/testfs.go
index 4912a271b2..2602bdf0cc 100644
--- a/src/testing/fstest/testfs.go
+++ b/src/testing/fstest/testfs.go
@@ -22,6 +22,8 @@ import (
// It walks the entire tree of files in fsys,
// opening and checking that each file behaves correctly.
// It also checks that the file system contains at least the expected files.
+// As a special case, if no expected files are listed, fsys must be empty.
+// Otherwise, fsys must only contain at least the listed files: it can also contain others.
//
// If TestFS finds any misbehaviors, it returns an error reporting all of them.
// The error text spans multiple lines, one per detected misbehavior.
@@ -33,6 +35,32 @@ import (
// }
//
func TestFS(fsys fs.FS, expected ...string) error {
+ if err := testFS(fsys, expected...); err != nil {
+ return err
+ }
+ for _, name := range expected {
+ if i := strings.Index(name, "/"); i >= 0 {
+ dir, dirSlash := name[:i], name[:i+1]
+ var subExpected []string
+ for _, name := range expected {
+ if strings.HasPrefix(name, dirSlash) {
+ subExpected = append(subExpected, name[len(dirSlash):])
+ }
+ }
+ sub, err := fs.Sub(fsys, dir)
+ if err != nil {
+ return err
+ }
+ if err := testFS(sub, subExpected...); err != nil {
+ return fmt.Errorf("testing fs.Sub(fsys, %s): %v", dir, err)
+ }
+ break // one sub-test is enough
+ }
+ }
+ return nil
+}
+
+func testFS(fsys fs.FS, expected ...string) error {
t := fsTester{fsys: fsys}
t.checkDir(".")
t.checkOpen(".")
@@ -43,6 +71,20 @@ func TestFS(fsys fs.FS, expected ...string) error {
for _, file := range t.files {
found[file] = true
}
+ delete(found, ".")
+ if len(expected) == 0 && len(found) > 0 {
+ var list []string
+ for k := range found {
+ if k != "." {
+ list = append(list, k)
+ }
+ }
+ sort.Strings(list)
+ if len(list) > 15 {
+ list = append(list[:10], "...")
+ }
+ t.errorf("expected empty file system but found files:\n%s", strings.Join(list, "\n"))
+ }
for _, name := range expected {
if !found[name] {
t.errorf("expected but not found: %s", name)
--
cgit v1.3
From 4f1b0a44cb46f3df28f5ef82e5769ebeac1bc493 Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Thu, 29 Oct 2020 14:17:47 -0400
Subject: all: update to use os.ReadFile, os.WriteFile, os.CreateTemp,
os.MkdirTemp
As part of #42026, these helpers from io/ioutil were moved to os.
(ioutil.TempFile and TempDir became os.CreateTemp and MkdirTemp.)
Update the Go tree to use the preferred names.
As usual, code compiled with the Go 1.4 bootstrap toolchain
and code vendored from other sources is excluded.
ReadDir changes are in a separate CL, because they are not a
simple search and replace.
For #42026.
Change-Id: If318df0216d57e95ea0c4093b89f65e5b0ababb3
Reviewed-on: https://go-review.googlesource.com/c/go/+/266365
Trust: Russ Cox
Run-TryBot: Russ Cox
TryBot-Result: Go Bot
Reviewed-by: Ian Lance Taylor
---
src/archive/tar/reader_test.go | 3 +-
src/archive/tar/tar_test.go | 3 +-
src/archive/tar/writer_test.go | 3 +-
src/archive/zip/reader_test.go | 11 +++---
src/archive/zip/writer_test.go | 4 +--
src/cmd/addr2line/addr2line_test.go | 7 ++--
src/cmd/api/goapi.go | 3 +-
src/cmd/api/goapi_test.go | 3 +-
src/cmd/cover/cover.go | 3 +-
src/cmd/cover/cover_test.go | 31 ++++++++--------
src/cmd/cover/html.go | 5 ++-
src/cmd/fix/main.go | 3 +-
src/cmd/fix/typecheck.go | 7 ++--
src/cmd/go/go_test.go | 19 +++++-----
src/cmd/go/go_windows_test.go | 5 ++-
src/cmd/go/help_test.go | 4 +--
src/cmd/go/internal/auth/netrc.go | 3 +-
src/cmd/go/internal/bug/bug.go | 5 ++-
src/cmd/go/internal/cache/cache.go | 5 ++-
src/cmd/go/internal/cache/cache_test.go | 13 ++++---
src/cmd/go/internal/cache/default.go | 3 +-
src/cmd/go/internal/cache/hash_test.go | 3 +-
src/cmd/go/internal/cfg/cfg.go | 3 +-
src/cmd/go/internal/envcmd/env.go | 7 ++--
src/cmd/go/internal/fsys/fsys.go | 2 +-
src/cmd/go/internal/fsys/fsys_test.go | 3 +-
src/cmd/go/internal/generate/generate.go | 3 +-
src/cmd/go/internal/imports/scan_test.go | 5 +--
src/cmd/go/internal/load/pkg.go | 4 +--
.../lockedfile/internal/filelock/filelock_test.go | 5 ++-
src/cmd/go/internal/lockedfile/lockedfile_test.go | 9 +++--
src/cmd/go/internal/modcmd/vendor.go | 2 +-
src/cmd/go/internal/modcmd/verify.go | 3 +-
src/cmd/go/internal/modconv/convert_test.go | 5 ++-
src/cmd/go/internal/modconv/modconv_test.go | 6 ++--
src/cmd/go/internal/modfetch/cache_test.go | 3 +-
src/cmd/go/internal/modfetch/codehost/codehost.go | 5 ++-
src/cmd/go/internal/modfetch/codehost/git_test.go | 3 +-
src/cmd/go/internal/modfetch/codehost/shell.go | 3 +-
src/cmd/go/internal/modfetch/codehost/vcs.go | 3 +-
src/cmd/go/internal/modfetch/coderepo.go | 3 +-
src/cmd/go/internal/modfetch/coderepo_test.go | 13 ++++---
src/cmd/go/internal/modfetch/fetch.go | 5 ++-
.../internal/modfetch/zip_sum_test/zip_sum_test.go | 3 +-
src/cmd/go/internal/modload/init.go | 8 ++---
src/cmd/go/internal/modload/query_test.go | 3 +-
src/cmd/go/internal/modload/vendor.go | 4 +--
src/cmd/go/internal/renameio/renameio.go | 4 +--
src/cmd/go/internal/renameio/renameio_test.go | 3 +-
src/cmd/go/internal/renameio/umask_test.go | 3 +-
src/cmd/go/internal/robustio/robustio.go | 2 +-
src/cmd/go/internal/robustio/robustio_flaky.go | 5 ++-
src/cmd/go/internal/robustio/robustio_other.go | 3 +-
src/cmd/go/internal/test/test.go | 4 +--
src/cmd/go/internal/txtar/archive.go | 4 +--
src/cmd/go/internal/vcs/vcs_test.go | 3 +-
src/cmd/go/internal/web/file_test.go | 3 +-
src/cmd/go/internal/work/action.go | 3 +-
src/cmd/go/internal/work/build_test.go | 9 +++--
src/cmd/go/internal/work/buildid.go | 3 +-
src/cmd/go/internal/work/exec.go | 17 +++++----
src/cmd/go/internal/work/gc.go | 7 ++--
src/cmd/go/internal/work/gccgo.go | 3 +-
src/cmd/go/script_test.go | 23 ++++++------
src/cmd/go/testdata/addmod.go | 13 ++++---
src/cmd/go/testdata/savedir.go | 3 +-
src/cmd/go/testdata/script/build_issue6480.txt | 5 ++-
src/cmd/go/testdata/script/build_trimpath.txt | 3 +-
src/cmd/go/testdata/script/cover_error.txt | 5 ++-
src/cmd/go/testdata/script/gopath_moved_repo.txt | 5 ++-
.../script/mod_download_concurrent_read.txt | 3 +-
src/cmd/go/testdata/script/mod_modinfo.txt | 3 +-
src/cmd/go/testdata/script/mod_test_cached.txt | 7 ++--
.../go/testdata/script/test_compile_tempfile.txt | 2 +-
src/cmd/go/testdata/script/test_generated_main.txt | 3 +-
.../go/testdata/script/test_race_install_cgo.txt | 8 ++---
src/cmd/gofmt/gofmt.go | 5 ++-
src/cmd/gofmt/gofmt_test.go | 13 ++++---
src/cmd/nm/nm_test.go | 9 +++--
src/cmd/objdump/objdump_test.go | 5 ++-
src/cmd/pack/pack_test.go | 13 ++++---
src/cmd/trace/annotations_test.go | 4 +--
src/cmd/trace/pprof.go | 3 +-
src/cmd/vet/vet_test.go | 5 ++-
src/compress/bzip2/bzip2_test.go | 4 +--
src/compress/flate/deflate_test.go | 6 ++--
src/compress/flate/huffman_bit_writer_test.go | 29 ++++++++-------
src/compress/flate/reader_test.go | 4 +--
src/compress/lzw/reader_test.go | 4 +--
src/compress/lzw/writer_test.go | 3 +-
src/compress/zlib/writer_test.go | 3 +-
src/crypto/md5/gen.go | 4 +--
src/crypto/tls/handshake_test.go | 3 +-
src/crypto/tls/link_test.go | 3 +-
src/crypto/tls/tls.go | 6 ++--
src/crypto/x509/name_constraints_test.go | 3 +-
src/crypto/x509/root_ios_gen.go | 4 +--
src/crypto/x509/root_plan9.go | 3 +-
src/crypto/x509/root_unix.go | 4 +--
src/crypto/x509/root_unix_test.go | 5 ++-
src/debug/dwarf/dwarf5ranges_test.go | 4 +--
src/debug/gosym/pclntab_test.go | 5 ++-
src/debug/pe/file_test.go | 13 ++++---
src/embed/internal/embedtest/embedx_test.go | 4 +--
src/go/build/build_test.go | 11 +++---
src/go/doc/doc_test.go | 6 ++--
src/go/format/benchmark_test.go | 4 +--
src/go/format/format_test.go | 6 ++--
src/go/importer/importer_test.go | 3 +-
src/go/internal/gccgoimporter/importer_test.go | 5 ++-
src/go/internal/gcimporter/gcimporter_test.go | 6 ++--
src/go/internal/srcimporter/srcimporter.go | 3 +-
src/go/parser/interface.go | 3 +-
src/go/parser/performance_test.go | 4 +--
src/go/printer/performance_test.go | 4 +--
src/go/printer/printer_test.go | 12 +++----
src/go/scanner/scanner_test.go | 3 +-
src/go/types/check_test.go | 3 +-
src/go/types/hilbert_test.go | 4 +--
src/hash/crc32/gen_const_ppc64le.go | 4 +--
src/html/template/examplefiles_test.go | 3 +-
src/html/template/template.go | 4 +--
src/image/color/palette/gen.go | 4 +--
src/image/gif/reader_test.go | 4 +--
src/image/internal/imageutil/gen.go | 3 +-
src/image/jpeg/reader_test.go | 7 ++--
src/image/png/reader_test.go | 3 +-
src/index/suffixarray/gen.go | 6 ++--
src/index/suffixarray/suffixarray_test.go | 6 ++--
src/internal/cpu/cpu_s390x_test.go | 4 +--
src/internal/obscuretestdata/obscuretestdata.go | 3 +-
src/internal/poll/read_test.go | 3 +-
src/internal/testenv/testenv_windows.go | 3 +-
src/internal/trace/gc_test.go | 6 ++--
src/internal/trace/parser_test.go | 2 +-
src/log/syslog/syslog_test.go | 5 ++-
src/math/big/link_test.go | 4 +--
src/math/bits/make_examples.go | 4 +--
src/math/bits/make_tables.go | 4 +--
src/mime/multipart/formdata.go | 3 +-
src/net/dnsclient_unix_test.go | 3 +-
src/net/error_test.go | 3 +-
src/net/http/filetransport_test.go | 5 ++-
src/net/http/fs_test.go | 8 ++---
src/net/http/request_test.go | 3 +-
src/net/http/transfer_test.go | 3 +-
src/net/http/transport_test.go | 3 +-
src/net/mockserver_test.go | 5 ++-
src/net/net_windows_test.go | 7 ++--
src/net/unixsock_test.go | 3 +-
src/os/error_test.go | 9 +++--
src/os/exec/exec_test.go | 2 +-
src/os/exec/lp_unix_test.go | 3 +-
src/os/exec/lp_windows_test.go | 7 ++--
src/os/fifo_test.go | 3 +-
src/os/os_test.go | 42 +++++++++++-----------
src/os/os_unix_test.go | 4 +--
src/os/os_windows_test.go | 29 ++++++++-------
src/os/path_test.go | 4 +--
src/os/path_windows_test.go | 3 +-
src/os/pipe_test.go | 3 +-
src/os/readfrom_linux_test.go | 4 +--
src/os/removeall_test.go | 20 +++++------
src/os/signal/signal_test.go | 3 +-
src/os/signal/signal_windows_test.go | 3 +-
src/os/stat_test.go | 9 +++--
src/os/timeout_test.go | 3 +-
src/os/user/lookup_plan9.go | 3 +-
src/path/filepath/example_unix_walk_test.go | 3 +-
src/path/filepath/match_test.go | 7 ++--
src/path/filepath/path_test.go | 33 +++++++++--------
src/path/filepath/path_windows_test.go | 19 +++++-----
src/runtime/crash_test.go | 3 +-
src/runtime/crash_unix_test.go | 5 ++-
src/runtime/debug/heapdump_test.go | 5 ++-
src/runtime/debug_test.go | 4 +--
src/runtime/env_plan9.go | 4 +--
src/runtime/internal/sys/gengoos.go | 8 ++---
src/runtime/memmove_linux_amd64_test.go | 3 +-
src/runtime/mkduff.go | 4 +--
src/runtime/mkfastlog2table.go | 4 +--
src/runtime/mksizeclasses.go | 3 +-
src/runtime/pprof/pprof_test.go | 5 ++-
src/runtime/pprof/proto.go | 4 +--
src/runtime/pprof/proto_test.go | 3 +-
src/runtime/race/output_test.go | 5 ++-
src/runtime/race/testdata/io_test.go | 3 +-
src/runtime/runtime-gdb_test.go | 25 +++++++------
src/runtime/runtime-lldb_test.go | 9 +++--
src/runtime/signal_windows_test.go | 5 ++-
src/runtime/syscall_windows_test.go | 25 +++++++------
src/runtime/testdata/testprog/memprof.go | 3 +-
src/runtime/testdata/testprog/syscalls_linux.go | 3 +-
src/runtime/testdata/testprog/timeprof.go | 3 +-
src/runtime/testdata/testprog/vdso.go | 3 +-
src/runtime/testdata/testprogcgo/pprof.go | 3 +-
src/runtime/testdata/testprogcgo/threadpprof.go | 3 +-
src/runtime/trace/trace_test.go | 3 +-
src/runtime/wincallback.go | 7 ++--
src/sort/genzfunc.go | 4 +--
src/strconv/makeisprint.go | 4 +--
src/syscall/dirent_test.go | 9 +++--
src/syscall/exec_linux_test.go | 15 ++++----
src/syscall/getdirentries_test.go | 5 ++-
src/syscall/mkasm_darwin.go | 9 +++--
src/syscall/syscall_linux_test.go | 11 +++---
src/syscall/syscall_unix_test.go | 7 ++--
src/syscall/syscall_windows_test.go | 3 +-
src/testing/testing.go | 5 ++-
src/text/template/examplefiles_test.go | 3 +-
src/text/template/helper.go | 4 +--
src/text/template/link_test.go | 7 ++--
src/time/genzabbrs.go | 4 +--
src/time/tzdata/generate_zipdata.go | 3 +-
src/time/zoneinfo_read.go | 2 +-
215 files changed, 556 insertions(+), 704 deletions(-)
(limited to 'src/testing')
diff --git a/src/archive/tar/reader_test.go b/src/archive/tar/reader_test.go
index 411d1e0b99..789ddc1bc0 100644
--- a/src/archive/tar/reader_test.go
+++ b/src/archive/tar/reader_test.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io"
- "io/ioutil"
"math"
"os"
"path"
@@ -773,7 +772,7 @@ func TestReadTruncation(t *testing.T) {
"testdata/pax-path-hdr.tar",
"testdata/sparse-formats.tar",
} {
- buf, err := ioutil.ReadFile(p)
+ buf, err := os.ReadFile(p)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
diff --git a/src/archive/tar/tar_test.go b/src/archive/tar/tar_test.go
index d4a3d42312..91b38401b6 100644
--- a/src/archive/tar/tar_test.go
+++ b/src/archive/tar/tar_test.go
@@ -11,7 +11,6 @@ import (
"internal/testenv"
"io"
"io/fs"
- "io/ioutil"
"math"
"os"
"path"
@@ -263,7 +262,7 @@ func TestFileInfoHeaderDir(t *testing.T) {
func TestFileInfoHeaderSymlink(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpdir, err := ioutil.TempDir("", "TestFileInfoHeaderSymlink")
+ tmpdir, err := os.MkdirTemp("", "TestFileInfoHeaderSymlink")
if err != nil {
t.Fatal(err)
}
diff --git a/src/archive/tar/writer_test.go b/src/archive/tar/writer_test.go
index 30556d27d0..a00f02d8fa 100644
--- a/src/archive/tar/writer_test.go
+++ b/src/archive/tar/writer_test.go
@@ -9,7 +9,6 @@ import (
"encoding/hex"
"errors"
"io"
- "io/ioutil"
"os"
"path"
"reflect"
@@ -520,7 +519,7 @@ func TestWriter(t *testing.T) {
}
if v.file != "" {
- want, err := ioutil.ReadFile(v.file)
+ want, err := os.ReadFile(v.file)
if err != nil {
t.Fatalf("ReadFile() = %v, want nil", err)
}
diff --git a/src/archive/zip/reader_test.go b/src/archive/zip/reader_test.go
index b7a7d7a757..34e96f7da4 100644
--- a/src/archive/zip/reader_test.go
+++ b/src/archive/zip/reader_test.go
@@ -11,7 +11,6 @@ import (
"internal/obscuretestdata"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"regexp"
@@ -629,7 +628,7 @@ func readTestFile(t *testing.T, zt ZipTest, ft ZipTestFile, f *File) {
var c []byte
if ft.Content != nil {
c = ft.Content
- } else if c, err = ioutil.ReadFile("testdata/" + ft.File); err != nil {
+ } else if c, err = os.ReadFile("testdata/" + ft.File); err != nil {
t.Error(err)
return
}
@@ -685,7 +684,7 @@ func TestInvalidFiles(t *testing.T) {
}
func messWith(fileName string, corrupter func(b []byte)) (r io.ReaderAt, size int64) {
- data, err := ioutil.ReadFile(filepath.Join("testdata", fileName))
+ data, err := os.ReadFile(filepath.Join("testdata", fileName))
if err != nil {
panic("Error reading " + fileName + ": " + err.Error())
}
@@ -792,17 +791,17 @@ func returnRecursiveZip() (r io.ReaderAt, size int64) {
//
// func main() {
// bigZip := makeZip("big.file", io.LimitReader(zeros{}, 1<<32-1))
-// if err := ioutil.WriteFile("/tmp/big.zip", bigZip, 0666); err != nil {
+// if err := os.WriteFile("/tmp/big.zip", bigZip, 0666); err != nil {
// log.Fatal(err)
// }
//
// biggerZip := makeZip("big.zip", bytes.NewReader(bigZip))
-// if err := ioutil.WriteFile("/tmp/bigger.zip", biggerZip, 0666); err != nil {
+// if err := os.WriteFile("/tmp/bigger.zip", biggerZip, 0666); err != nil {
// log.Fatal(err)
// }
//
// biggestZip := makeZip("bigger.zip", bytes.NewReader(biggerZip))
-// if err := ioutil.WriteFile("/tmp/biggest.zip", biggestZip, 0666); err != nil {
+// if err := os.WriteFile("/tmp/biggest.zip", biggestZip, 0666); err != nil {
// log.Fatal(err)
// }
// }
diff --git a/src/archive/zip/writer_test.go b/src/archive/zip/writer_test.go
index 2c32eaf4a5..5985144e5c 100644
--- a/src/archive/zip/writer_test.go
+++ b/src/archive/zip/writer_test.go
@@ -10,8 +10,8 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"math/rand"
+ "os"
"strings"
"testing"
"time"
@@ -237,7 +237,7 @@ func TestWriterTime(t *testing.T) {
t.Fatalf("unexpected Close error: %v", err)
}
- want, err := ioutil.ReadFile("testdata/time-go.zip")
+ want, err := os.ReadFile("testdata/time-go.zip")
if err != nil {
t.Fatalf("unexpected ReadFile error: %v", err)
}
diff --git a/src/cmd/addr2line/addr2line_test.go b/src/cmd/addr2line/addr2line_test.go
index 7973aa2fe1..992d7ac11e 100644
--- a/src/cmd/addr2line/addr2line_test.go
+++ b/src/cmd/addr2line/addr2line_test.go
@@ -8,7 +8,6 @@ import (
"bufio"
"bytes"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -98,8 +97,8 @@ func testAddr2Line(t *testing.T, exepath, addr string) {
if !os.SameFile(fi1, fi2) {
t.Fatalf("addr2line_test.go and %s are not same file", srcPath)
}
- if srcLineNo != "107" {
- t.Fatalf("line number = %v; want 107", srcLineNo)
+ if srcLineNo != "106" {
+ t.Fatalf("line number = %v; want 106", srcLineNo)
}
}
@@ -107,7 +106,7 @@ func testAddr2Line(t *testing.T, exepath, addr string) {
func TestAddr2Line(t *testing.T) {
testenv.MustHaveGoBuild(t)
- tmpDir, err := ioutil.TempDir("", "TestAddr2Line")
+ tmpDir, err := os.MkdirTemp("", "TestAddr2Line")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
diff --git a/src/cmd/api/goapi.go b/src/cmd/api/goapi.go
index b14d57c236..ba42812fa6 100644
--- a/src/cmd/api/goapi.go
+++ b/src/cmd/api/goapi.go
@@ -17,7 +17,6 @@ import (
"go/token"
"go/types"
"io"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -342,7 +341,7 @@ func fileFeatures(filename string) []string {
if filename == "" {
return nil
}
- bs, err := ioutil.ReadFile(filename)
+ bs, err := os.ReadFile(filename)
if err != nil {
log.Fatalf("Error reading file %s: %v", filename, err)
}
diff --git a/src/cmd/api/goapi_test.go b/src/cmd/api/goapi_test.go
index 24620a94af..16e0058e5e 100644
--- a/src/cmd/api/goapi_test.go
+++ b/src/cmd/api/goapi_test.go
@@ -9,7 +9,6 @@ import (
"flag"
"fmt"
"go/build"
- "io/ioutil"
"os"
"path/filepath"
"sort"
@@ -75,7 +74,7 @@ func TestGolden(t *testing.T) {
f.Close()
}
- bs, err := ioutil.ReadFile(goldenFile)
+ bs, err := os.ReadFile(goldenFile)
if err != nil {
t.Fatalf("opening golden.txt for package %q: %v", fi.Name(), err)
}
diff --git a/src/cmd/cover/cover.go b/src/cmd/cover/cover.go
index 360f9aeb06..7ee000861b 100644
--- a/src/cmd/cover/cover.go
+++ b/src/cmd/cover/cover.go
@@ -12,7 +12,6 @@ import (
"go/parser"
"go/token"
"io"
- "io/ioutil"
"log"
"os"
"sort"
@@ -304,7 +303,7 @@ func (f *File) Visit(node ast.Node) ast.Visitor {
func annotate(name string) {
fset := token.NewFileSet()
- content, err := ioutil.ReadFile(name)
+ content, err := os.ReadFile(name)
if err != nil {
log.Fatalf("cover: %s: %s", name, err)
}
diff --git a/src/cmd/cover/cover_test.go b/src/cmd/cover/cover_test.go
index 1c252e6e45..86c95d15c5 100644
--- a/src/cmd/cover/cover_test.go
+++ b/src/cmd/cover/cover_test.go
@@ -13,7 +13,6 @@ import (
"go/parser"
"go/token"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -81,7 +80,7 @@ var debug = flag.Bool("debug", false, "keep rewritten files for debugging")
// We use TestMain to set up a temporary directory and remove it when
// the tests are done.
func TestMain(m *testing.M) {
- dir, err := ioutil.TempDir("", "go-testcover")
+ dir, err := os.MkdirTemp("", "go-testcover")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
@@ -173,7 +172,7 @@ func TestCover(t *testing.T) {
buildCover(t)
// Read in the test file (testTest) and write it, with LINEs specified, to coverInput.
- file, err := ioutil.ReadFile(testTest)
+ file, err := os.ReadFile(testTest)
if err != nil {
t.Fatal(err)
}
@@ -192,7 +191,7 @@ func TestCover(t *testing.T) {
[]byte("}"))
lines = append(lines, []byte("func unFormatted2(b bool) {if b{}else{}}"))
- if err := ioutil.WriteFile(coverInput, bytes.Join(lines, []byte("\n")), 0666); err != nil {
+ if err := os.WriteFile(coverInput, bytes.Join(lines, []byte("\n")), 0666); err != nil {
t.Fatal(err)
}
@@ -208,11 +207,11 @@ func TestCover(t *testing.T) {
// Copy testmain to testTempDir, so that it is in the same directory
// as coverOutput.
- b, err := ioutil.ReadFile(testMain)
+ b, err := os.ReadFile(testMain)
if err != nil {
t.Fatal(err)
}
- if err := ioutil.WriteFile(tmpTestMain, b, 0444); err != nil {
+ if err := os.WriteFile(tmpTestMain, b, 0444); err != nil {
t.Fatal(err)
}
@@ -220,7 +219,7 @@ func TestCover(t *testing.T) {
cmd = exec.Command(testenv.GoToolPath(t), "run", tmpTestMain, coverOutput)
run(cmd, t)
- file, err = ioutil.ReadFile(coverOutput)
+ file, err = os.ReadFile(coverOutput)
if err != nil {
t.Fatal(err)
}
@@ -251,7 +250,7 @@ func TestDirectives(t *testing.T) {
// Read the source file and find all the directives. We'll keep
// track of whether each one has been seen in the output.
testDirectives := filepath.Join(testdata, "directives.go")
- source, err := ioutil.ReadFile(testDirectives)
+ source, err := os.ReadFile(testDirectives)
if err != nil {
t.Fatal(err)
}
@@ -398,7 +397,7 @@ func TestCoverHTML(t *testing.T) {
// Extract the parts of the HTML with comment markers,
// and compare against a golden file.
- entireHTML, err := ioutil.ReadFile(htmlHTML)
+ entireHTML, err := os.ReadFile(htmlHTML)
if err != nil {
t.Fatal(err)
}
@@ -420,7 +419,7 @@ func TestCoverHTML(t *testing.T) {
if scan.Err() != nil {
t.Error(scan.Err())
}
- golden, err := ioutil.ReadFile(htmlGolden)
+ golden, err := os.ReadFile(htmlGolden)
if err != nil {
t.Fatalf("reading golden file: %v", err)
}
@@ -457,7 +456,7 @@ func TestHtmlUnformatted(t *testing.T) {
t.Fatal(err)
}
- if err := ioutil.WriteFile(filepath.Join(htmlUDir, "go.mod"), []byte("module htmlunformatted\n"), 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(htmlUDir, "go.mod"), []byte("module htmlunformatted\n"), 0666); err != nil {
t.Fatal(err)
}
@@ -474,10 +473,10 @@ lab:
const htmlUTestContents = `package htmlunformatted`
- if err := ioutil.WriteFile(htmlU, []byte(htmlUContents), 0444); err != nil {
+ if err := os.WriteFile(htmlU, []byte(htmlUContents), 0444); err != nil {
t.Fatal(err)
}
- if err := ioutil.WriteFile(htmlUTest, []byte(htmlUTestContents), 0444); err != nil {
+ if err := os.WriteFile(htmlUTest, []byte(htmlUTestContents), 0444); err != nil {
t.Fatal(err)
}
@@ -540,13 +539,13 @@ func TestFuncWithDuplicateLines(t *testing.T) {
t.Fatal(err)
}
- if err := ioutil.WriteFile(filepath.Join(lineDupDir, "go.mod"), []byte("module linedup\n"), 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(lineDupDir, "go.mod"), []byte("module linedup\n"), 0666); err != nil {
t.Fatal(err)
}
- if err := ioutil.WriteFile(lineDupGo, []byte(lineDupContents), 0444); err != nil {
+ if err := os.WriteFile(lineDupGo, []byte(lineDupContents), 0444); err != nil {
t.Fatal(err)
}
- if err := ioutil.WriteFile(lineDupTestGo, []byte(lineDupTestContents), 0444); err != nil {
+ if err := os.WriteFile(lineDupTestGo, []byte(lineDupTestContents), 0444); err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/cover/html.go b/src/cmd/cover/html.go
index f76ea03cf5..b2865c427c 100644
--- a/src/cmd/cover/html.go
+++ b/src/cmd/cover/html.go
@@ -11,7 +11,6 @@ import (
"fmt"
"html/template"
"io"
- "io/ioutil"
"math"
"os"
"path/filepath"
@@ -43,7 +42,7 @@ func htmlOutput(profile, outfile string) error {
if err != nil {
return err
}
- src, err := ioutil.ReadFile(file)
+ src, err := os.ReadFile(file)
if err != nil {
return fmt.Errorf("can't read %q: %v", fn, err)
}
@@ -62,7 +61,7 @@ func htmlOutput(profile, outfile string) error {
var out *os.File
if outfile == "" {
var dir string
- dir, err = ioutil.TempDir("", "cover")
+ dir, err = os.MkdirTemp("", "cover")
if err != nil {
return err
}
diff --git a/src/cmd/fix/main.go b/src/cmd/fix/main.go
index 1cedf992cf..d055929aac 100644
--- a/src/cmd/fix/main.go
+++ b/src/cmd/fix/main.go
@@ -15,7 +15,6 @@ import (
"go/token"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"sort"
@@ -217,7 +216,7 @@ func processFile(filename string, useStdin bool) error {
return nil
}
- return ioutil.WriteFile(f.Name(), newSrc, 0)
+ return os.WriteFile(f.Name(), newSrc, 0)
}
func gofmt(n interface{}) string {
diff --git a/src/cmd/fix/typecheck.go b/src/cmd/fix/typecheck.go
index f45155b06d..40b2287f26 100644
--- a/src/cmd/fix/typecheck.go
+++ b/src/cmd/fix/typecheck.go
@@ -9,7 +9,6 @@ import (
"go/ast"
"go/parser"
"go/token"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -162,12 +161,12 @@ func typecheck(cfg *TypeConfig, f *ast.File) (typeof map[interface{}]string, ass
if err != nil {
return err
}
- dir, err := ioutil.TempDir(os.TempDir(), "fix_cgo_typecheck")
+ dir, err := os.MkdirTemp(os.TempDir(), "fix_cgo_typecheck")
if err != nil {
return err
}
defer os.RemoveAll(dir)
- err = ioutil.WriteFile(filepath.Join(dir, "in.go"), txt, 0600)
+ err = os.WriteFile(filepath.Join(dir, "in.go"), txt, 0600)
if err != nil {
return err
}
@@ -176,7 +175,7 @@ func typecheck(cfg *TypeConfig, f *ast.File) (typeof map[interface{}]string, ass
if err != nil {
return err
}
- out, err := ioutil.ReadFile(filepath.Join(dir, "_cgo_gotypes.go"))
+ out, err := os.ReadFile(filepath.Join(dir, "_cgo_gotypes.go"))
if err != nil {
return err
}
diff --git a/src/cmd/go/go_test.go b/src/cmd/go/go_test.go
index 1b8a21ecfa..19764bfc60 100644
--- a/src/cmd/go/go_test.go
+++ b/src/cmd/go/go_test.go
@@ -17,7 +17,6 @@ import (
"internal/testenv"
"io"
"io/fs"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -100,7 +99,7 @@ func TestMain(m *testing.M) {
// Run with a temporary TMPDIR to check that the tests don't
// leave anything behind.
- topTmpdir, err := ioutil.TempDir("", "cmd-go-test-")
+ topTmpdir, err := os.MkdirTemp("", "cmd-go-test-")
if err != nil {
log.Fatal(err)
}
@@ -109,7 +108,7 @@ func TestMain(m *testing.M) {
}
os.Setenv(tempEnvName(), topTmpdir)
- dir, err := ioutil.TempDir(topTmpdir, "tmpdir")
+ dir, err := os.MkdirTemp(topTmpdir, "tmpdir")
if err != nil {
log.Fatal(err)
}
@@ -616,7 +615,7 @@ func (tg *testgoData) makeTempdir() {
tg.t.Helper()
if tg.tempdir == "" {
var err error
- tg.tempdir, err = ioutil.TempDir("", "gotest")
+ tg.tempdir, err = os.MkdirTemp("", "gotest")
tg.must(err)
}
}
@@ -633,7 +632,7 @@ func (tg *testgoData) tempFile(path, contents string) {
bytes = formatted
}
}
- tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
+ tg.must(os.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
}
// tempDir adds a temporary directory for a run of testgo.
@@ -833,7 +832,7 @@ func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
return err
}
dest := filepath.Join("goroot", copydir, srcrel)
- data, err := ioutil.ReadFile(path)
+ data, err := os.ReadFile(path)
if err != nil {
return err
}
@@ -850,18 +849,18 @@ func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
tg.setenv("GOROOT", tg.path("goroot"))
addVar := func(name string, idx int) (restore func()) {
- data, err := ioutil.ReadFile(name)
+ data, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
}
old := data
data = append(data, fmt.Sprintf("var DummyUnusedVar%d bool\n", idx)...)
- if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
+ if err := os.WriteFile(name, append(data, '\n'), 0666); err != nil {
t.Fatal(err)
}
tg.sleep()
return func() {
- if err := ioutil.WriteFile(name, old, 0666); err != nil {
+ if err := os.WriteFile(name, old, 0666); err != nil {
t.Fatal(err)
}
}
@@ -2674,7 +2673,7 @@ echo $* >>`+tg.path("pkg-config.out"))
tg.setenv("GOPATH", tg.path("."))
tg.setenv("PKG_CONFIG", tg.path("pkg-config.sh"))
tg.run("build", "x")
- out, err := ioutil.ReadFile(tg.path("pkg-config.out"))
+ out, err := os.ReadFile(tg.path("pkg-config.out"))
tg.must(err)
out = bytes.TrimSpace(out)
want := "--cflags --static --static -- a a\n--libs --static --static -- a a"
diff --git a/src/cmd/go/go_windows_test.go b/src/cmd/go/go_windows_test.go
index 02634f19f5..3094212bae 100644
--- a/src/cmd/go/go_windows_test.go
+++ b/src/cmd/go/go_windows_test.go
@@ -5,7 +5,6 @@
package main_test
import (
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -20,14 +19,14 @@ func TestAbsolutePath(t *testing.T) {
defer tg.cleanup()
tg.parallel()
- tmp, err := ioutil.TempDir("", "TestAbsolutePath")
+ tmp, err := os.MkdirTemp("", "TestAbsolutePath")
if err != nil {
t.Fatal(err)
}
defer robustio.RemoveAll(tmp)
file := filepath.Join(tmp, "a.go")
- err = ioutil.WriteFile(file, []byte{}, 0644)
+ err = os.WriteFile(file, []byte{}, 0644)
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/help_test.go b/src/cmd/go/help_test.go
index 78d63ff05e..abfc3db993 100644
--- a/src/cmd/go/help_test.go
+++ b/src/cmd/go/help_test.go
@@ -6,7 +6,7 @@ package main_test
import (
"bytes"
- "io/ioutil"
+ "os"
"testing"
"cmd/go/internal/help"
@@ -23,7 +23,7 @@ func TestDocsUpToDate(t *testing.T) {
buf := new(bytes.Buffer)
// Match the command in mkalldocs.sh that generates alldocs.go.
help.Help(buf, []string{"documentation"})
- data, err := ioutil.ReadFile("alldocs.go")
+ data, err := os.ReadFile("alldocs.go")
if err != nil {
t.Fatalf("error reading alldocs.go: %v", err)
}
diff --git a/src/cmd/go/internal/auth/netrc.go b/src/cmd/go/internal/auth/netrc.go
index 7a9bdbb72c..0107f20d7a 100644
--- a/src/cmd/go/internal/auth/netrc.go
+++ b/src/cmd/go/internal/auth/netrc.go
@@ -5,7 +5,6 @@
package auth
import (
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -99,7 +98,7 @@ func readNetrc() {
return
}
- data, err := ioutil.ReadFile(path)
+ data, err := os.ReadFile(path)
if err != nil {
if !os.IsNotExist(err) {
netrcErr = err
diff --git a/src/cmd/go/internal/bug/bug.go b/src/cmd/go/internal/bug/bug.go
index 07e3516855..1085feaaee 100644
--- a/src/cmd/go/internal/bug/bug.go
+++ b/src/cmd/go/internal/bug/bug.go
@@ -10,7 +10,6 @@ import (
"context"
"fmt"
"io"
- "io/ioutil"
urlpkg "net/url"
"os"
"os/exec"
@@ -117,7 +116,7 @@ func printOSDetails(w io.Writer) {
case "illumos", "solaris":
// Be sure to use the OS-supplied uname, in "/usr/bin":
printCmdOut(w, "uname -srv: ", "/usr/bin/uname", "-srv")
- out, err := ioutil.ReadFile("/etc/release")
+ out, err := os.ReadFile("/etc/release")
if err == nil {
fmt.Fprintf(w, "/etc/release: %s\n", out)
} else {
@@ -177,7 +176,7 @@ func printGlibcVersion(w io.Writer) {
src := []byte(`int main() {}`)
srcfile := filepath.Join(tempdir, "go-bug.c")
outfile := filepath.Join(tempdir, "go-bug")
- err := ioutil.WriteFile(srcfile, src, 0644)
+ err := os.WriteFile(srcfile, src, 0644)
if err != nil {
return
}
diff --git a/src/cmd/go/internal/cache/cache.go b/src/cmd/go/internal/cache/cache.go
index 5464fe5685..41f921641d 100644
--- a/src/cmd/go/internal/cache/cache.go
+++ b/src/cmd/go/internal/cache/cache.go
@@ -13,7 +13,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"strconv"
@@ -239,7 +238,7 @@ func (c *Cache) GetBytes(id ActionID) ([]byte, Entry, error) {
if err != nil {
return nil, entry, err
}
- data, _ := ioutil.ReadFile(c.OutputFile(entry.OutputID))
+ data, _ := os.ReadFile(c.OutputFile(entry.OutputID))
if sha256.Sum256(data) != entry.OutputID {
return nil, entry, &entryNotFoundError{Err: errors.New("bad checksum")}
}
@@ -378,7 +377,7 @@ func (c *Cache) putIndexEntry(id ActionID, out OutputID, size int64, allowVerify
// Truncate the file only *after* writing it.
// (This should be a no-op, but truncate just in case of previous corruption.)
//
- // This differs from ioutil.WriteFile, which truncates to 0 *before* writing
+ // This differs from os.WriteFile, which truncates to 0 *before* writing
// via os.O_TRUNC. Truncating only after writing ensures that a second write
// of the same content to the same file is idempotent, and does not — even
// temporarily! — undo the effect of the first write.
diff --git a/src/cmd/go/internal/cache/cache_test.go b/src/cmd/go/internal/cache/cache_test.go
index 1988c34502..a865b97018 100644
--- a/src/cmd/go/internal/cache/cache_test.go
+++ b/src/cmd/go/internal/cache/cache_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"encoding/binary"
"fmt"
- "io/ioutil"
"os"
"path/filepath"
"testing"
@@ -20,7 +19,7 @@ func init() {
}
func TestBasic(t *testing.T) {
- dir, err := ioutil.TempDir("", "cachetest-")
+ dir, err := os.MkdirTemp("", "cachetest-")
if err != nil {
t.Fatal(err)
}
@@ -65,7 +64,7 @@ func TestBasic(t *testing.T) {
}
func TestGrowth(t *testing.T) {
- dir, err := ioutil.TempDir("", "cachetest-")
+ dir, err := os.MkdirTemp("", "cachetest-")
if err != nil {
t.Fatal(err)
}
@@ -118,7 +117,7 @@ func TestVerifyPanic(t *testing.T) {
t.Fatal("initEnv did not set verify")
}
- dir, err := ioutil.TempDir("", "cachetest-")
+ dir, err := os.MkdirTemp("", "cachetest-")
if err != nil {
t.Fatal(err)
}
@@ -151,7 +150,7 @@ func dummyID(x int) [HashSize]byte {
}
func TestCacheTrim(t *testing.T) {
- dir, err := ioutil.TempDir("", "cachetest-")
+ dir, err := os.MkdirTemp("", "cachetest-")
if err != nil {
t.Fatal(err)
}
@@ -207,7 +206,7 @@ func TestCacheTrim(t *testing.T) {
t.Fatal(err)
}
c.OutputFile(entry.OutputID)
- data, err := ioutil.ReadFile(filepath.Join(dir, "trim.txt"))
+ data, err := os.ReadFile(filepath.Join(dir, "trim.txt"))
if err != nil {
t.Fatal(err)
}
@@ -220,7 +219,7 @@ func TestCacheTrim(t *testing.T) {
t.Fatal(err)
}
c.OutputFile(entry.OutputID)
- data2, err := ioutil.ReadFile(filepath.Join(dir, "trim.txt"))
+ data2, err := os.ReadFile(filepath.Join(dir, "trim.txt"))
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/cache/default.go b/src/cmd/go/internal/cache/default.go
index 9f8dd8af4b..0b1c1e0c20 100644
--- a/src/cmd/go/internal/cache/default.go
+++ b/src/cmd/go/internal/cache/default.go
@@ -6,7 +6,6 @@ package cache
import (
"fmt"
- "io/ioutil"
"os"
"path/filepath"
"sync"
@@ -49,7 +48,7 @@ func initDefaultCache() {
}
if _, err := os.Stat(filepath.Join(dir, "README")); err != nil {
// Best effort.
- ioutil.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666)
+ os.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666)
}
c, err := Open(dir)
diff --git a/src/cmd/go/internal/cache/hash_test.go b/src/cmd/go/internal/cache/hash_test.go
index 3bf7143039..a0356771ca 100644
--- a/src/cmd/go/internal/cache/hash_test.go
+++ b/src/cmd/go/internal/cache/hash_test.go
@@ -6,7 +6,6 @@ package cache
import (
"fmt"
- "io/ioutil"
"os"
"testing"
)
@@ -28,7 +27,7 @@ func TestHash(t *testing.T) {
}
func TestHashFile(t *testing.T) {
- f, err := ioutil.TempFile("", "cmd-go-test-")
+ f, err := os.CreateTemp("", "cmd-go-test-")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/cfg/cfg.go b/src/cmd/go/internal/cfg/cfg.go
index 9bc48132ae..c48904eacc 100644
--- a/src/cmd/go/internal/cfg/cfg.go
+++ b/src/cmd/go/internal/cfg/cfg.go
@@ -12,7 +12,6 @@ import (
"go/build"
"internal/cfg"
"io"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -187,7 +186,7 @@ func initEnvCache() {
if file == "" {
return
}
- data, err := ioutil.ReadFile(file)
+ data, err := os.ReadFile(file)
if err != nil {
return
}
diff --git a/src/cmd/go/internal/envcmd/env.go b/src/cmd/go/internal/envcmd/env.go
index 46af36eb11..6937187522 100644
--- a/src/cmd/go/internal/envcmd/env.go
+++ b/src/cmd/go/internal/envcmd/env.go
@@ -10,7 +10,6 @@ import (
"encoding/json"
"fmt"
"go/build"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -452,7 +451,7 @@ func updateEnvFile(add map[string]string, del map[string]bool) {
if file == "" {
base.Fatalf("go env: cannot find go env config: %v", err)
}
- data, err := ioutil.ReadFile(file)
+ data, err := os.ReadFile(file)
if err != nil && (!os.IsNotExist(err) || len(add) == 0) {
base.Fatalf("go env: reading go env config: %v", err)
}
@@ -506,11 +505,11 @@ func updateEnvFile(add map[string]string, del map[string]bool) {
}
data = []byte(strings.Join(lines, ""))
- err = ioutil.WriteFile(file, data, 0666)
+ err = os.WriteFile(file, data, 0666)
if err != nil {
// Try creating directory.
os.MkdirAll(filepath.Dir(file), 0777)
- err = ioutil.WriteFile(file, data, 0666)
+ err = os.WriteFile(file, data, 0666)
if err != nil {
base.Fatalf("go env: writing go env config: %v", err)
}
diff --git a/src/cmd/go/internal/fsys/fsys.go b/src/cmd/go/internal/fsys/fsys.go
index 0264786e5b..7b06c3c7f3 100644
--- a/src/cmd/go/internal/fsys/fsys.go
+++ b/src/cmd/go/internal/fsys/fsys.go
@@ -86,7 +86,7 @@ func Init(wd string) error {
return nil
}
- b, err := ioutil.ReadFile(OverlayFile)
+ b, err := os.ReadFile(OverlayFile)
if err != nil {
return fmt.Errorf("reading overlay file: %v", err)
}
diff --git a/src/cmd/go/internal/fsys/fsys_test.go b/src/cmd/go/internal/fsys/fsys_test.go
index 90a69de14a..7f175c7031 100644
--- a/src/cmd/go/internal/fsys/fsys_test.go
+++ b/src/cmd/go/internal/fsys/fsys_test.go
@@ -8,7 +8,6 @@ import (
"internal/testenv"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"reflect"
@@ -47,7 +46,7 @@ func initOverlay(t *testing.T, config string) {
if err := os.MkdirAll(filepath.Dir(name), 0777); err != nil {
t.Fatal(err)
}
- if err := ioutil.WriteFile(name, f.Data, 0666); err != nil {
+ if err := os.WriteFile(name, f.Data, 0666); err != nil {
t.Fatal(err)
}
}
diff --git a/src/cmd/go/internal/generate/generate.go b/src/cmd/go/internal/generate/generate.go
index 98c17bba8c..c7401948b8 100644
--- a/src/cmd/go/internal/generate/generate.go
+++ b/src/cmd/go/internal/generate/generate.go
@@ -13,7 +13,6 @@ import (
"go/parser"
"go/token"
"io"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -201,7 +200,7 @@ func runGenerate(ctx context.Context, cmd *base.Command, args []string) {
// generate runs the generation directives for a single file.
func generate(absFile string) bool {
- src, err := ioutil.ReadFile(absFile)
+ src, err := os.ReadFile(absFile)
if err != nil {
log.Fatalf("generate: %s", err)
}
diff --git a/src/cmd/go/internal/imports/scan_test.go b/src/cmd/go/internal/imports/scan_test.go
index e424656cae..5ba3201968 100644
--- a/src/cmd/go/internal/imports/scan_test.go
+++ b/src/cmd/go/internal/imports/scan_test.go
@@ -8,6 +8,7 @@ import (
"bytes"
"internal/testenv"
"io/ioutil"
+ "os"
"path"
"path/filepath"
"runtime"
@@ -66,7 +67,7 @@ func TestScanDir(t *testing.T) {
continue
}
t.Run(dir.Name(), func(t *testing.T) {
- tagsData, err := ioutil.ReadFile(filepath.Join("testdata", dir.Name(), "tags.txt"))
+ tagsData, err := os.ReadFile(filepath.Join("testdata", dir.Name(), "tags.txt"))
if err != nil {
t.Fatalf("error reading tags: %v", err)
}
@@ -75,7 +76,7 @@ func TestScanDir(t *testing.T) {
tags[t] = true
}
- wantData, err := ioutil.ReadFile(filepath.Join("testdata", dir.Name(), "want.txt"))
+ wantData, err := os.ReadFile(filepath.Join("testdata", dir.Name(), "want.txt"))
if err != nil {
t.Fatalf("error reading want: %v", err)
}
diff --git a/src/cmd/go/internal/load/pkg.go b/src/cmd/go/internal/load/pkg.go
index cbc683da2b..da3e0b895c 100644
--- a/src/cmd/go/internal/load/pkg.go
+++ b/src/cmd/go/internal/load/pkg.go
@@ -1147,7 +1147,7 @@ var (
// goModPath returns the module path in the go.mod in dir, if any.
func goModPath(dir string) (path string) {
return goModPathCache.Do(dir, func() interface{} {
- data, err := ioutil.ReadFile(filepath.Join(dir, "go.mod"))
+ data, err := os.ReadFile(filepath.Join(dir, "go.mod"))
if err != nil {
return ""
}
@@ -1728,7 +1728,7 @@ func (p *Package) load(ctx context.Context, path string, stk *ImportStack, impor
// not work for any package that lacks a Target — such as a non-main
// package in module mode. We should probably fix that.
shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
- shlib, err := ioutil.ReadFile(shlibnamefile)
+ shlib, err := os.ReadFile(shlibnamefile)
if err != nil && !os.IsNotExist(err) {
base.Fatalf("reading shlibname: %v", err)
}
diff --git a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_test.go b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_test.go
index 8301fb6b6e..2ac2052b8f 100644
--- a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_test.go
+++ b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_test.go
@@ -9,7 +9,6 @@ package filelock_test
import (
"fmt"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -51,9 +50,9 @@ func mustTempFile(t *testing.T) (f *os.File, remove func()) {
t.Helper()
base := filepath.Base(t.Name())
- f, err := ioutil.TempFile("", base)
+ f, err := os.CreateTemp("", base)
if err != nil {
- t.Fatalf(`ioutil.TempFile("", %q) = %v`, base, err)
+ t.Fatalf(`os.CreateTemp("", %q) = %v`, base, err)
}
t.Logf("fd %d = %s", f.Fd(), f.Name())
diff --git a/src/cmd/go/internal/lockedfile/lockedfile_test.go b/src/cmd/go/internal/lockedfile/lockedfile_test.go
index 416c69d83b..34327dd841 100644
--- a/src/cmd/go/internal/lockedfile/lockedfile_test.go
+++ b/src/cmd/go/internal/lockedfile/lockedfile_test.go
@@ -10,7 +10,6 @@ package lockedfile_test
import (
"fmt"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -23,7 +22,7 @@ import (
func mustTempDir(t *testing.T) (dir string, remove func()) {
t.Helper()
- dir, err := ioutil.TempDir("", filepath.Base(t.Name()))
+ dir, err := os.MkdirTemp("", filepath.Base(t.Name()))
if err != nil {
t.Fatal(err)
}
@@ -155,8 +154,8 @@ func TestCanLockExistingFile(t *testing.T) {
defer remove()
path := filepath.Join(dir, "existing.txt")
- if err := ioutil.WriteFile(path, []byte("ok"), 0777); err != nil {
- t.Fatalf("ioutil.WriteFile: %v", err)
+ if err := os.WriteFile(path, []byte("ok"), 0777); err != nil {
+ t.Fatalf("os.WriteFile: %v", err)
}
f, err := lockedfile.Edit(path)
@@ -201,7 +200,7 @@ func TestSpuriousEDEADLK(t *testing.T) {
}
defer b.Close()
- if err := ioutil.WriteFile(filepath.Join(dir, "locked"), []byte("ok"), 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(dir, "locked"), []byte("ok"), 0666); err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/modcmd/vendor.go b/src/cmd/go/internal/modcmd/vendor.go
index 38c473d36b..390a195547 100644
--- a/src/cmd/go/internal/modcmd/vendor.go
+++ b/src/cmd/go/internal/modcmd/vendor.go
@@ -155,7 +155,7 @@ func runVendor(ctx context.Context, cmd *base.Command, args []string) {
base.Fatalf("go mod vendor: %v", err)
}
- if err := ioutil.WriteFile(filepath.Join(vdir, "modules.txt"), buf.Bytes(), 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(vdir, "modules.txt"), buf.Bytes(), 0666); err != nil {
base.Fatalf("go mod vendor: %v", err)
}
}
diff --git a/src/cmd/go/internal/modcmd/verify.go b/src/cmd/go/internal/modcmd/verify.go
index ce24793929..c83e70076a 100644
--- a/src/cmd/go/internal/modcmd/verify.go
+++ b/src/cmd/go/internal/modcmd/verify.go
@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io/fs"
- "io/ioutil"
"os"
"runtime"
@@ -87,7 +86,7 @@ func verifyMod(mod module.Version) []error {
_, zipErr = os.Stat(zip)
}
dir, dirErr := modfetch.DownloadDir(mod)
- data, err := ioutil.ReadFile(zip + "hash")
+ data, err := os.ReadFile(zip + "hash")
if err != nil {
if zipErr != nil && errors.Is(zipErr, fs.ErrNotExist) &&
dirErr != nil && errors.Is(dirErr, fs.ErrNotExist) {
diff --git a/src/cmd/go/internal/modconv/convert_test.go b/src/cmd/go/internal/modconv/convert_test.go
index faa2b4c606..66b9ff4f38 100644
--- a/src/cmd/go/internal/modconv/convert_test.go
+++ b/src/cmd/go/internal/modconv/convert_test.go
@@ -9,7 +9,6 @@ import (
"context"
"fmt"
"internal/testenv"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -37,7 +36,7 @@ func testMain(m *testing.M) int {
return 0
}
- dir, err := ioutil.TempDir("", "modconv-test-")
+ dir, err := os.MkdirTemp("", "modconv-test-")
if err != nil {
log.Fatal(err)
}
@@ -167,7 +166,7 @@ func TestConvertLegacyConfig(t *testing.T) {
for name := range Converters {
file := filepath.Join(dir, name)
- data, err := ioutil.ReadFile(file)
+ data, err := os.ReadFile(file)
if err == nil {
f := new(modfile.File)
f.AddModuleStmt(tt.path)
diff --git a/src/cmd/go/internal/modconv/modconv_test.go b/src/cmd/go/internal/modconv/modconv_test.go
index ccc4f3d576..750525d404 100644
--- a/src/cmd/go/internal/modconv/modconv_test.go
+++ b/src/cmd/go/internal/modconv/modconv_test.go
@@ -7,7 +7,7 @@ package modconv
import (
"bytes"
"fmt"
- "io/ioutil"
+ "os"
"path/filepath"
"testing"
)
@@ -42,7 +42,7 @@ func Test(t *testing.T) {
if Converters[extMap[ext]] == nil {
t.Fatalf("Converters[%q] == nil", extMap[ext])
}
- data, err := ioutil.ReadFile(test)
+ data, err := os.ReadFile(test)
if err != nil {
t.Fatal(err)
}
@@ -50,7 +50,7 @@ func Test(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- want, err := ioutil.ReadFile(test[:len(test)-len(ext)] + ".out")
+ want, err := os.ReadFile(test[:len(test)-len(ext)] + ".out")
if err != nil {
t.Error(err)
}
diff --git a/src/cmd/go/internal/modfetch/cache_test.go b/src/cmd/go/internal/modfetch/cache_test.go
index 241c800e69..722c984e37 100644
--- a/src/cmd/go/internal/modfetch/cache_test.go
+++ b/src/cmd/go/internal/modfetch/cache_test.go
@@ -5,14 +5,13 @@
package modfetch
import (
- "io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestWriteDiskCache(t *testing.T) {
- tmpdir, err := ioutil.TempDir("", "go-writeCache-test-")
+ tmpdir, err := os.MkdirTemp("", "go-writeCache-test-")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/modfetch/codehost/codehost.go b/src/cmd/go/internal/modfetch/codehost/codehost.go
index 286d3f7220..86c1c14d4a 100644
--- a/src/cmd/go/internal/modfetch/codehost/codehost.go
+++ b/src/cmd/go/internal/modfetch/codehost/codehost.go
@@ -12,7 +12,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -189,7 +188,7 @@ func WorkDir(typ, name string) (dir, lockfile string, err error) {
}
defer unlock()
- data, err := ioutil.ReadFile(dir + ".info")
+ data, err := os.ReadFile(dir + ".info")
info, err2 := os.Stat(dir)
if err == nil && err2 == nil && info.IsDir() {
// Info file and directory both already exist: reuse.
@@ -211,7 +210,7 @@ func WorkDir(typ, name string) (dir, lockfile string, err error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return "", "", err
}
- if err := ioutil.WriteFile(dir+".info", []byte(key), 0666); err != nil {
+ if err := os.WriteFile(dir+".info", []byte(key), 0666); err != nil {
os.RemoveAll(dir)
return "", "", err
}
diff --git a/src/cmd/go/internal/modfetch/codehost/git_test.go b/src/cmd/go/internal/modfetch/codehost/git_test.go
index 981e3fe91f..89a73baad9 100644
--- a/src/cmd/go/internal/modfetch/codehost/git_test.go
+++ b/src/cmd/go/internal/modfetch/codehost/git_test.go
@@ -12,7 +12,6 @@ import (
"internal/testenv"
"io"
"io/fs"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -54,7 +53,7 @@ func testMain(m *testing.M) int {
return 0
}
- dir, err := ioutil.TempDir("", "gitrepo-test-")
+ dir, err := os.MkdirTemp("", "gitrepo-test-")
if err != nil {
log.Fatal(err)
}
diff --git a/src/cmd/go/internal/modfetch/codehost/shell.go b/src/cmd/go/internal/modfetch/codehost/shell.go
index b9525adf5e..ce8b501d53 100644
--- a/src/cmd/go/internal/modfetch/codehost/shell.go
+++ b/src/cmd/go/internal/modfetch/codehost/shell.go
@@ -15,7 +15,6 @@ import (
"flag"
"fmt"
"io"
- "io/ioutil"
"log"
"os"
"strings"
@@ -124,7 +123,7 @@ func main() {
}
if f[3] != "-" {
- if err := ioutil.WriteFile(f[3], data, 0666); err != nil {
+ if err := os.WriteFile(f[3], data, 0666); err != nil {
fmt.Fprintf(os.Stderr, "?%s\n", err)
continue
}
diff --git a/src/cmd/go/internal/modfetch/codehost/vcs.go b/src/cmd/go/internal/modfetch/codehost/vcs.go
index e67ee94ad8..c2cca084e3 100644
--- a/src/cmd/go/internal/modfetch/codehost/vcs.go
+++ b/src/cmd/go/internal/modfetch/codehost/vcs.go
@@ -10,7 +10,6 @@ import (
"internal/lazyregexp"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"sort"
@@ -433,7 +432,7 @@ func (r *vcsRepo) ReadZip(rev, subdir string, maxSize int64) (zip io.ReadCloser,
if rev == "latest" {
rev = r.cmd.latest
}
- f, err := ioutil.TempFile("", "go-readzip-*.zip")
+ f, err := os.CreateTemp("", "go-readzip-*.zip")
if err != nil {
return nil, err
}
diff --git a/src/cmd/go/internal/modfetch/coderepo.go b/src/cmd/go/internal/modfetch/coderepo.go
index b6bcf83f1a..2dcbb99b18 100644
--- a/src/cmd/go/internal/modfetch/coderepo.go
+++ b/src/cmd/go/internal/modfetch/coderepo.go
@@ -11,7 +11,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"os"
"path"
"sort"
@@ -966,7 +965,7 @@ func (r *codeRepo) Zip(dst io.Writer, version string) error {
subdir = strings.Trim(subdir, "/")
// Spool to local file.
- f, err := ioutil.TempFile("", "go-codehost-")
+ f, err := os.CreateTemp("", "go-codehost-")
if err != nil {
dl.Close()
return err
diff --git a/src/cmd/go/internal/modfetch/coderepo_test.go b/src/cmd/go/internal/modfetch/coderepo_test.go
index 53b048dbdf..02e399f352 100644
--- a/src/cmd/go/internal/modfetch/coderepo_test.go
+++ b/src/cmd/go/internal/modfetch/coderepo_test.go
@@ -11,7 +11,6 @@ import (
"hash"
"internal/testenv"
"io"
- "io/ioutil"
"log"
"os"
"reflect"
@@ -38,7 +37,7 @@ func testMain(m *testing.M) int {
// code, bypass the sum database.
cfg.GOSUMDB = "off"
- dir, err := ioutil.TempDir("", "gitrepo-test-")
+ dir, err := os.MkdirTemp("", "gitrepo-test-")
if err != nil {
log.Fatal(err)
}
@@ -424,7 +423,7 @@ var codeRepoTests = []codeRepoTest{
func TestCodeRepo(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
- tmpdir, err := ioutil.TempDir("", "modfetch-test-")
+ tmpdir, err := os.MkdirTemp("", "modfetch-test-")
if err != nil {
t.Fatal(err)
}
@@ -491,9 +490,9 @@ func TestCodeRepo(t *testing.T) {
needHash := !testing.Short() && (tt.zipFileHash != "" || tt.zipSum != "")
if tt.zip != nil || tt.zipErr != "" || needHash {
- f, err := ioutil.TempFile(tmpdir, tt.version+".zip.")
+ f, err := os.CreateTemp(tmpdir, tt.version+".zip.")
if err != nil {
- t.Fatalf("ioutil.TempFile: %v", err)
+ t.Fatalf("os.CreateTemp: %v", err)
}
zipfile := f.Name()
defer func() {
@@ -655,7 +654,7 @@ var codeRepoVersionsTests = []struct {
func TestCodeRepoVersions(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
- tmpdir, err := ioutil.TempDir("", "vgo-modfetch-test-")
+ tmpdir, err := os.MkdirTemp("", "vgo-modfetch-test-")
if err != nil {
t.Fatal(err)
}
@@ -729,7 +728,7 @@ var latestTests = []struct {
func TestLatest(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
- tmpdir, err := ioutil.TempDir("", "vgo-modfetch-test-")
+ tmpdir, err := os.MkdirTemp("", "vgo-modfetch-test-")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/modfetch/fetch.go b/src/cmd/go/internal/modfetch/fetch.go
index 2ee78de5b2..debeb3f319 100644
--- a/src/cmd/go/internal/modfetch/fetch.go
+++ b/src/cmd/go/internal/modfetch/fetch.go
@@ -12,7 +12,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"sort"
@@ -136,7 +135,7 @@ func download(ctx context.Context, mod module.Version) (dir string, err error) {
if err := os.MkdirAll(parentDir, 0777); err != nil {
return "", err
}
- if err := ioutil.WriteFile(partialPath, nil, 0666); err != nil {
+ if err := os.WriteFile(partialPath, nil, 0666); err != nil {
return "", err
}
if err := modzip.Unzip(dir, mod, zipfile); err != nil {
@@ -223,7 +222,7 @@ func downloadZip(ctx context.Context, mod module.Version, zipfile string) (err e
// contents of the file (by hashing it) before we commit it. Because the file
// is zip-compressed, we need an actual file — or at least an io.ReaderAt — to
// validate it: we can't just tee the stream as we write it.
- f, err := ioutil.TempFile(filepath.Dir(zipfile), filepath.Base(renameio.Pattern(zipfile)))
+ f, err := os.CreateTemp(filepath.Dir(zipfile), filepath.Base(renameio.Pattern(zipfile)))
if err != nil {
return err
}
diff --git a/src/cmd/go/internal/modfetch/zip_sum_test/zip_sum_test.go b/src/cmd/go/internal/modfetch/zip_sum_test/zip_sum_test.go
index 82398ebfed..d9ba8ef2da 100644
--- a/src/cmd/go/internal/modfetch/zip_sum_test/zip_sum_test.go
+++ b/src/cmd/go/internal/modfetch/zip_sum_test/zip_sum_test.go
@@ -24,7 +24,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"os"
"path/filepath"
"strings"
@@ -81,7 +80,7 @@ func TestZipSums(t *testing.T) {
if *modCacheDir != "" {
cfg.BuildContext.GOPATH = *modCacheDir
} else {
- tmpDir, err := ioutil.TempDir("", "TestZipSums")
+ tmpDir, err := os.MkdirTemp("", "TestZipSums")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/modload/init.go b/src/cmd/go/internal/modload/init.go
index 1c31a5f90a..6a2cea668d 100644
--- a/src/cmd/go/internal/modload/init.go
+++ b/src/cmd/go/internal/modload/init.go
@@ -632,7 +632,7 @@ func setDefaultBuildMod() {
func convertLegacyConfig(modPath string) (from string, err error) {
for _, name := range altConfigs {
cfg := filepath.Join(modRoot, name)
- data, err := ioutil.ReadFile(cfg)
+ data, err := os.ReadFile(cfg)
if err == nil {
convert := modconv.Converters[name]
if convert == nil {
@@ -753,7 +753,7 @@ func findModulePath(dir string) (string, error) {
}
// Look for Godeps.json declaring import path.
- data, _ := ioutil.ReadFile(filepath.Join(dir, "Godeps/Godeps.json"))
+ data, _ := os.ReadFile(filepath.Join(dir, "Godeps/Godeps.json"))
var cfg1 struct{ ImportPath string }
json.Unmarshal(data, &cfg1)
if cfg1.ImportPath != "" {
@@ -761,7 +761,7 @@ func findModulePath(dir string) (string, error) {
}
// Look for vendor.json declaring import path.
- data, _ = ioutil.ReadFile(filepath.Join(dir, "vendor/vendor.json"))
+ data, _ = os.ReadFile(filepath.Join(dir, "vendor/vendor.json"))
var cfg2 struct{ RootPath string }
json.Unmarshal(data, &cfg2)
if cfg2.RootPath != "" {
@@ -813,7 +813,7 @@ var (
)
func findImportComment(file string) string {
- data, err := ioutil.ReadFile(file)
+ data, err := os.ReadFile(file)
if err != nil {
return ""
}
diff --git a/src/cmd/go/internal/modload/query_test.go b/src/cmd/go/internal/modload/query_test.go
index 777a56b977..e225a0e71e 100644
--- a/src/cmd/go/internal/modload/query_test.go
+++ b/src/cmd/go/internal/modload/query_test.go
@@ -7,7 +7,6 @@ package modload
import (
"context"
"internal/testenv"
- "io/ioutil"
"log"
"os"
"path"
@@ -27,7 +26,7 @@ func TestMain(m *testing.M) {
func testMain(m *testing.M) int {
cfg.GOPROXY = "direct"
- dir, err := ioutil.TempDir("", "modload-test-")
+ dir, err := os.MkdirTemp("", "modload-test-")
if err != nil {
log.Fatal(err)
}
diff --git a/src/cmd/go/internal/modload/vendor.go b/src/cmd/go/internal/modload/vendor.go
index ab29d4d014..80d49053c6 100644
--- a/src/cmd/go/internal/modload/vendor.go
+++ b/src/cmd/go/internal/modload/vendor.go
@@ -8,7 +8,7 @@ import (
"errors"
"fmt"
"io/fs"
- "io/ioutil"
+ "os"
"path/filepath"
"strings"
"sync"
@@ -40,7 +40,7 @@ func readVendorList() {
vendorPkgModule = make(map[string]module.Version)
vendorVersion = make(map[string]string)
vendorMeta = make(map[module.Version]vendorMetadata)
- data, err := ioutil.ReadFile(filepath.Join(ModRoot(), "vendor/modules.txt"))
+ data, err := os.ReadFile(filepath.Join(ModRoot(), "vendor/modules.txt"))
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
base.Fatalf("go: %s", err)
diff --git a/src/cmd/go/internal/renameio/renameio.go b/src/cmd/go/internal/renameio/renameio.go
index 60a7138a76..9788171d6e 100644
--- a/src/cmd/go/internal/renameio/renameio.go
+++ b/src/cmd/go/internal/renameio/renameio.go
@@ -25,7 +25,7 @@ func Pattern(filename string) string {
return filepath.Join(filepath.Dir(filename), filepath.Base(filename)+patternSuffix)
}
-// WriteFile is like ioutil.WriteFile, but first writes data to an arbitrary
+// WriteFile is like os.WriteFile, but first writes data to an arbitrary
// file in the same directory as filename, then renames it atomically to the
// final name.
//
@@ -67,7 +67,7 @@ func WriteToFile(filename string, data io.Reader, perm fs.FileMode) (err error)
return robustio.Rename(f.Name(), filename)
}
-// ReadFile is like ioutil.ReadFile, but on Windows retries spurious errors that
+// ReadFile is like os.ReadFile, but on Windows retries spurious errors that
// may occur if the file is concurrently replaced.
//
// Errors are classified heuristically and retries are bounded, so even this
diff --git a/src/cmd/go/internal/renameio/renameio_test.go b/src/cmd/go/internal/renameio/renameio_test.go
index e6d2025a0e..5b2ed83624 100644
--- a/src/cmd/go/internal/renameio/renameio_test.go
+++ b/src/cmd/go/internal/renameio/renameio_test.go
@@ -10,7 +10,6 @@ import (
"encoding/binary"
"errors"
"internal/testenv"
- "io/ioutil"
"math/rand"
"os"
"path/filepath"
@@ -30,7 +29,7 @@ func TestConcurrentReadsAndWrites(t *testing.T) {
testenv.SkipFlaky(t, 33041)
}
- dir, err := ioutil.TempDir("", "renameio")
+ dir, err := os.MkdirTemp("", "renameio")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/renameio/umask_test.go b/src/cmd/go/internal/renameio/umask_test.go
index 19e217c548..65e4fa587b 100644
--- a/src/cmd/go/internal/renameio/umask_test.go
+++ b/src/cmd/go/internal/renameio/umask_test.go
@@ -8,7 +8,6 @@ package renameio
import (
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"syscall"
@@ -16,7 +15,7 @@ import (
)
func TestWriteFileModeAppliesUmask(t *testing.T) {
- dir, err := ioutil.TempDir("", "renameio")
+ dir, err := os.MkdirTemp("", "renameio")
if err != nil {
t.Fatalf("Failed to create temporary directory: %v", err)
}
diff --git a/src/cmd/go/internal/robustio/robustio.go b/src/cmd/go/internal/robustio/robustio.go
index 76e47ad1ff..ce3dbbde6d 100644
--- a/src/cmd/go/internal/robustio/robustio.go
+++ b/src/cmd/go/internal/robustio/robustio.go
@@ -22,7 +22,7 @@ func Rename(oldpath, newpath string) error {
return rename(oldpath, newpath)
}
-// ReadFile is like ioutil.ReadFile, but on Windows retries errors that may
+// ReadFile is like os.ReadFile, but on Windows retries errors that may
// occur if the file is concurrently replaced.
//
// (See golang.org/issue/31247 and golang.org/issue/32188.)
diff --git a/src/cmd/go/internal/robustio/robustio_flaky.go b/src/cmd/go/internal/robustio/robustio_flaky.go
index d4cb7e6457..5bd44bd345 100644
--- a/src/cmd/go/internal/robustio/robustio_flaky.go
+++ b/src/cmd/go/internal/robustio/robustio_flaky.go
@@ -8,7 +8,6 @@ package robustio
import (
"errors"
- "io/ioutil"
"math/rand"
"os"
"syscall"
@@ -70,11 +69,11 @@ func rename(oldpath, newpath string) (err error) {
})
}
-// readFile is like ioutil.ReadFile, but retries ephemeral errors.
+// readFile is like os.ReadFile, but retries ephemeral errors.
func readFile(filename string) ([]byte, error) {
var b []byte
err := retry(func() (err error, mayRetry bool) {
- b, err = ioutil.ReadFile(filename)
+ b, err = os.ReadFile(filename)
// Unlike in rename, we do not retry errFileNotFound here: it can occur
// as a spurious error, but the file may also genuinely not exist, so the
diff --git a/src/cmd/go/internal/robustio/robustio_other.go b/src/cmd/go/internal/robustio/robustio_other.go
index 907b556858..6fe7b7e4e4 100644
--- a/src/cmd/go/internal/robustio/robustio_other.go
+++ b/src/cmd/go/internal/robustio/robustio_other.go
@@ -7,7 +7,6 @@
package robustio
import (
- "io/ioutil"
"os"
)
@@ -16,7 +15,7 @@ func rename(oldpath, newpath string) error {
}
func readFile(filename string) ([]byte, error) {
- return ioutil.ReadFile(filename)
+ return os.ReadFile(filename)
}
func removeAll(path string) error {
diff --git a/src/cmd/go/internal/test/test.go b/src/cmd/go/internal/test/test.go
index 24601dc061..401b67c260 100644
--- a/src/cmd/go/internal/test/test.go
+++ b/src/cmd/go/internal/test/test.go
@@ -884,7 +884,7 @@ func builderTest(b *work.Builder, ctx context.Context, p *load.Package) (buildAc
if !cfg.BuildN {
// writeTestmain writes _testmain.go,
// using the test description gathered in t.
- if err := ioutil.WriteFile(testDir+"_testmain.go", *pmain.Internal.TestmainGo, 0666); err != nil {
+ if err := os.WriteFile(testDir+"_testmain.go", *pmain.Internal.TestmainGo, 0666); err != nil {
return nil, nil, nil, err
}
}
@@ -1616,7 +1616,7 @@ func (c *runCache) saveOutput(a *work.Action) {
}
// See comment about two-level lookup in tryCacheWithID above.
- testlog, err := ioutil.ReadFile(a.Objdir + "testlog.txt")
+ testlog, err := os.ReadFile(a.Objdir + "testlog.txt")
if err != nil || !bytes.HasPrefix(testlog, testlogMagic) || testlog[len(testlog)-1] != '\n' {
if cache.DebugTest {
if err != nil {
diff --git a/src/cmd/go/internal/txtar/archive.go b/src/cmd/go/internal/txtar/archive.go
index c384f33bdf..1796684877 100644
--- a/src/cmd/go/internal/txtar/archive.go
+++ b/src/cmd/go/internal/txtar/archive.go
@@ -34,7 +34,7 @@ package txtar
import (
"bytes"
"fmt"
- "io/ioutil"
+ "os"
"strings"
)
@@ -66,7 +66,7 @@ func Format(a *Archive) []byte {
// ParseFile parses the named file as an archive.
func ParseFile(file string) (*Archive, error) {
- data, err := ioutil.ReadFile(file)
+ data, err := os.ReadFile(file)
if err != nil {
return nil, err
}
diff --git a/src/cmd/go/internal/vcs/vcs_test.go b/src/cmd/go/internal/vcs/vcs_test.go
index 72d74a01e3..c5c7a3283b 100644
--- a/src/cmd/go/internal/vcs/vcs_test.go
+++ b/src/cmd/go/internal/vcs/vcs_test.go
@@ -7,7 +7,6 @@ package vcs
import (
"errors"
"internal/testenv"
- "io/ioutil"
"os"
"path"
"path/filepath"
@@ -208,7 +207,7 @@ func TestRepoRootForImportPath(t *testing.T) {
// Test that vcsFromDir correctly inspects a given directory and returns the right VCS and root.
func TestFromDir(t *testing.T) {
- tempDir, err := ioutil.TempDir("", "vcstest")
+ tempDir, err := os.MkdirTemp("", "vcstest")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/web/file_test.go b/src/cmd/go/internal/web/file_test.go
index a1bb080e07..3734df5c4e 100644
--- a/src/cmd/go/internal/web/file_test.go
+++ b/src/cmd/go/internal/web/file_test.go
@@ -7,7 +7,6 @@ package web
import (
"errors"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"testing"
@@ -16,7 +15,7 @@ import (
func TestGetFileURL(t *testing.T) {
const content = "Hello, file!\n"
- f, err := ioutil.TempFile("", "web-TestGetFileURL")
+ f, err := os.CreateTemp("", "web-TestGetFileURL")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/work/action.go b/src/cmd/go/internal/work/action.go
index f461c5780f..9d141ae233 100644
--- a/src/cmd/go/internal/work/action.go
+++ b/src/cmd/go/internal/work/action.go
@@ -14,7 +14,6 @@ import (
"debug/elf"
"encoding/json"
"fmt"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -253,7 +252,7 @@ func (b *Builder) Init() {
if cfg.BuildN {
b.WorkDir = "$WORK"
} else {
- tmp, err := ioutil.TempDir(cfg.Getenv("GOTMPDIR"), "go-build")
+ tmp, err := os.MkdirTemp(cfg.Getenv("GOTMPDIR"), "go-build")
if err != nil {
base.Fatalf("go: creating work dir: %v", err)
}
diff --git a/src/cmd/go/internal/work/build_test.go b/src/cmd/go/internal/work/build_test.go
index e941729734..eaf2639e9e 100644
--- a/src/cmd/go/internal/work/build_test.go
+++ b/src/cmd/go/internal/work/build_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"reflect"
@@ -170,7 +169,7 @@ func TestSharedLibName(t *testing.T) {
for _, data := range testData {
func() {
if data.rootedAt != "" {
- tmpGopath, err := ioutil.TempDir("", "gopath")
+ tmpGopath, err := os.MkdirTemp("", "gopath")
if err != nil {
t.Fatal(err)
}
@@ -238,7 +237,7 @@ func TestRespectSetgidDir(t *testing.T) {
return cmdBuf.WriteString(fmt.Sprint(a...))
}
- setgiddir, err := ioutil.TempDir("", "SetGroupID")
+ setgiddir, err := os.MkdirTemp("", "SetGroupID")
if err != nil {
t.Fatal(err)
}
@@ -258,9 +257,9 @@ func TestRespectSetgidDir(t *testing.T) {
t.Fatal(err)
}
- pkgfile, err := ioutil.TempFile("", "pkgfile")
+ pkgfile, err := os.CreateTemp("", "pkgfile")
if err != nil {
- t.Fatalf("ioutil.TempFile(\"\", \"pkgfile\"): %v", err)
+ t.Fatalf("os.CreateTemp(\"\", \"pkgfile\"): %v", err)
}
defer os.Remove(pkgfile.Name())
defer pkgfile.Close()
diff --git a/src/cmd/go/internal/work/buildid.go b/src/cmd/go/internal/work/buildid.go
index 3c7be5a3e3..d76988145b 100644
--- a/src/cmd/go/internal/work/buildid.go
+++ b/src/cmd/go/internal/work/buildid.go
@@ -7,7 +7,6 @@ package work
import (
"bytes"
"fmt"
- "io/ioutil"
"os"
"os/exec"
"strings"
@@ -344,7 +343,7 @@ func (b *Builder) gccgoBuildIDFile(a *Action) (string, error) {
}
}
- if err := ioutil.WriteFile(sfile, buf.Bytes(), 0666); err != nil {
+ if err := os.WriteFile(sfile, buf.Bytes(), 0666); err != nil {
return "", err
}
diff --git a/src/cmd/go/internal/work/exec.go b/src/cmd/go/internal/work/exec.go
index 6ce56dd6f4..336751df27 100644
--- a/src/cmd/go/internal/work/exec.go
+++ b/src/cmd/go/internal/work/exec.go
@@ -16,7 +16,6 @@ import (
"internal/lazyregexp"
"io"
"io/fs"
- "io/ioutil"
"log"
"math/rand"
"os"
@@ -94,7 +93,7 @@ func (b *Builder) Do(ctx context.Context, root *Action) {
base.Fatalf("go: refusing to write action graph to %v\n", file)
}
js := actionGraphJSON(root)
- if err := ioutil.WriteFile(file, []byte(js), 0666); err != nil {
+ if err := os.WriteFile(file, []byte(js), 0666); err != nil {
fmt.Fprintf(os.Stderr, "go: writing action graph: %v\n", err)
base.SetExitStatus(1)
}
@@ -636,7 +635,7 @@ OverlayLoop:
sfiles, gccfiles = filter(sfiles, sfiles[:0], gccfiles)
} else {
for _, sfile := range sfiles {
- data, err := ioutil.ReadFile(filepath.Join(a.Package.Dir, sfile))
+ data, err := os.ReadFile(filepath.Join(a.Package.Dir, sfile))
if err == nil {
if bytes.HasPrefix(data, []byte("TEXT")) || bytes.Contains(data, []byte("\nTEXT")) ||
bytes.HasPrefix(data, []byte("DATA")) || bytes.Contains(data, []byte("\nDATA")) ||
@@ -1471,7 +1470,7 @@ func (b *Builder) installShlibname(ctx context.Context, a *Action) error {
// TODO: BuildN
a1 := a.Deps[0]
- err := ioutil.WriteFile(a.Target, []byte(filepath.Base(a1.Target)+"\n"), 0666)
+ err := os.WriteFile(a.Target, []byte(filepath.Base(a1.Target)+"\n"), 0666)
if err != nil {
return err
}
@@ -1788,7 +1787,7 @@ func (b *Builder) writeFile(file string, text []byte) error {
if cfg.BuildN {
return nil
}
- return ioutil.WriteFile(file, text, 0666)
+ return os.WriteFile(file, text, 0666)
}
// Install the cgo export header file, if there is one.
@@ -2537,7 +2536,7 @@ func (b *Builder) gccSupportsFlag(compiler []string, flag string) bool {
tmp := os.DevNull
if runtime.GOOS == "windows" {
- f, err := ioutil.TempFile(b.WorkDir, "")
+ f, err := os.CreateTemp(b.WorkDir, "")
if err != nil {
return false
}
@@ -2840,7 +2839,7 @@ func (b *Builder) cgo(a *Action, cgoExe, objdir string, pcCFLAGS, pcLDFLAGS, cgo
continue
}
- src, err := ioutil.ReadFile(f)
+ src, err := os.ReadFile(f)
if err != nil {
return nil, nil, err
}
@@ -3070,7 +3069,7 @@ func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error) {
return "$INTBITS", nil
}
src := filepath.Join(b.WorkDir, "swig_intsize.go")
- if err = ioutil.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil {
+ if err = os.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil {
return
}
srcs := []string{src}
@@ -3230,7 +3229,7 @@ func passLongArgsInResponseFiles(cmd *exec.Cmd) (cleanup func()) {
return
}
- tf, err := ioutil.TempFile("", "args")
+ tf, err := os.CreateTemp("", "args")
if err != nil {
log.Fatalf("error writing long arguments to response file: %v", err)
}
diff --git a/src/cmd/go/internal/work/gc.go b/src/cmd/go/internal/work/gc.go
index 3a53c714e3..cc4e2b2b2b 100644
--- a/src/cmd/go/internal/work/gc.go
+++ b/src/cmd/go/internal/work/gc.go
@@ -9,7 +9,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"log"
"os"
"path/filepath"
@@ -426,11 +425,11 @@ func toolVerify(a *Action, b *Builder, p *load.Package, newTool string, ofile st
if err := b.run(a, p.Dir, p.ImportPath, nil, newArgs...); err != nil {
return err
}
- data1, err := ioutil.ReadFile(ofile)
+ data1, err := os.ReadFile(ofile)
if err != nil {
return err
}
- data2, err := ioutil.ReadFile(ofile + ".new")
+ data2, err := os.ReadFile(ofile + ".new")
if err != nil {
return err
}
@@ -580,7 +579,7 @@ func pluginPath(a *Action) string {
}
fmt.Fprintf(h, "build ID: %s\n", buildID)
for _, file := range str.StringList(p.GoFiles, p.CgoFiles, p.SFiles) {
- data, err := ioutil.ReadFile(filepath.Join(p.Dir, file))
+ data, err := os.ReadFile(filepath.Join(p.Dir, file))
if err != nil {
base.Fatalf("go: %s", err)
}
diff --git a/src/cmd/go/internal/work/gccgo.go b/src/cmd/go/internal/work/gccgo.go
index 01d2b89159..3ffd01c473 100644
--- a/src/cmd/go/internal/work/gccgo.go
+++ b/src/cmd/go/internal/work/gccgo.go
@@ -6,7 +6,6 @@ package work
import (
"fmt"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -271,7 +270,7 @@ func (tools gccgoToolchain) link(b *Builder, root *Action, out, importcfg string
}
readCgoFlags := func(flagsFile string) error {
- flags, err := ioutil.ReadFile(flagsFile)
+ flags, err := os.ReadFile(flagsFile)
if err != nil {
return err
}
diff --git a/src/cmd/go/script_test.go b/src/cmd/go/script_test.go
index aee3742f13..dfaa40548e 100644
--- a/src/cmd/go/script_test.go
+++ b/src/cmd/go/script_test.go
@@ -15,7 +15,6 @@ import (
"go/build"
"internal/testenv"
"io/fs"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -220,7 +219,7 @@ func (ts *testScript) run() {
for _, f := range a.Files {
name := ts.mkabs(ts.expand(f.Name, false))
ts.check(os.MkdirAll(filepath.Dir(name), 0777))
- ts.check(ioutil.WriteFile(name, f.Data, 0666))
+ ts.check(os.WriteFile(name, f.Data, 0666))
}
// With -v or -testwork, start log with full environment.
@@ -377,19 +376,19 @@ var (
func isCaseSensitive(t *testing.T) bool {
onceCaseSensitive.Do(func() {
- tmpdir, err := ioutil.TempDir("", "case-sensitive")
+ tmpdir, err := os.MkdirTemp("", "case-sensitive")
if err != nil {
t.Fatal("failed to create directory to determine case-sensitivity:", err)
}
defer os.RemoveAll(tmpdir)
fcap := filepath.Join(tmpdir, "FILE")
- if err := ioutil.WriteFile(fcap, []byte{}, 0644); err != nil {
+ if err := os.WriteFile(fcap, []byte{}, 0644); err != nil {
t.Fatal("error writing file to determine case-sensitivity:", err)
}
flow := filepath.Join(tmpdir, "file")
- _, err = ioutil.ReadFile(flow)
+ _, err = os.ReadFile(flow)
switch {
case err == nil:
caseSensitive = false
@@ -450,9 +449,9 @@ func (ts *testScript) cmdAddcrlf(want simpleStatus, args []string) {
for _, file := range args {
file = ts.mkabs(file)
- data, err := ioutil.ReadFile(file)
+ data, err := os.ReadFile(file)
ts.check(err)
- ts.check(ioutil.WriteFile(file, bytes.ReplaceAll(data, []byte("\n"), []byte("\r\n")), 0666))
+ ts.check(os.WriteFile(file, bytes.ReplaceAll(data, []byte("\n"), []byte("\r\n")), 0666))
}
}
@@ -557,12 +556,12 @@ func (ts *testScript) doCmdCmp(args []string, env, quiet bool) {
} else if name1 == "stderr" {
text1 = ts.stderr
} else {
- data, err := ioutil.ReadFile(ts.mkabs(name1))
+ data, err := os.ReadFile(ts.mkabs(name1))
ts.check(err)
text1 = string(data)
}
- data, err := ioutil.ReadFile(ts.mkabs(name2))
+ data, err := os.ReadFile(ts.mkabs(name2))
ts.check(err)
text2 = string(data)
@@ -614,14 +613,14 @@ func (ts *testScript) cmdCp(want simpleStatus, args []string) {
info, err := os.Stat(src)
ts.check(err)
mode = info.Mode() & 0777
- data, err = ioutil.ReadFile(src)
+ data, err = os.ReadFile(src)
ts.check(err)
}
targ := dst
if dstDir {
targ = filepath.Join(dst, filepath.Base(src))
}
- err := ioutil.WriteFile(targ, data, mode)
+ err := os.WriteFile(targ, data, mode)
switch want {
case failure:
if err == nil {
@@ -897,7 +896,7 @@ func scriptMatch(ts *testScript, want simpleStatus, args []string, text, name st
isGrep := name == "grep"
if isGrep {
name = args[1] // for error messages
- data, err := ioutil.ReadFile(ts.mkabs(args[1]))
+ data, err := os.ReadFile(ts.mkabs(args[1]))
ts.check(err)
text = string(data)
}
diff --git a/src/cmd/go/testdata/addmod.go b/src/cmd/go/testdata/addmod.go
index 71ac47fdc1..58376b7ed4 100644
--- a/src/cmd/go/testdata/addmod.go
+++ b/src/cmd/go/testdata/addmod.go
@@ -23,7 +23,6 @@ import (
"flag"
"fmt"
"io/fs"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -58,7 +57,7 @@ func main() {
log.SetFlags(0)
var err error
- tmpdir, err = ioutil.TempDir("", "addmod-")
+ tmpdir, err = os.MkdirTemp("", "addmod-")
if err != nil {
log.Fatal(err)
}
@@ -82,7 +81,7 @@ func main() {
exitCode := 0
for _, arg := range flag.Args() {
- if err := ioutil.WriteFile(filepath.Join(tmpdir, "go.mod"), []byte("module m\n"), 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(tmpdir, "go.mod"), []byte("module m\n"), 0666); err != nil {
fatalf("%v", err)
}
run(goCmd, "get", "-d", arg)
@@ -98,13 +97,13 @@ func main() {
continue
}
path, vers, dir := f[0], f[1], f[2]
- mod, err := ioutil.ReadFile(filepath.Join(gopath, "pkg/mod/cache/download", path, "@v", vers+".mod"))
+ mod, err := os.ReadFile(filepath.Join(gopath, "pkg/mod/cache/download", path, "@v", vers+".mod"))
if err != nil {
log.Printf("%s: %v", arg, err)
exitCode = 1
continue
}
- info, err := ioutil.ReadFile(filepath.Join(gopath, "pkg/mod/cache/download", path, "@v", vers+".info"))
+ info, err := os.ReadFile(filepath.Join(gopath, "pkg/mod/cache/download", path, "@v", vers+".info"))
if err != nil {
log.Printf("%s: %v", arg, err)
exitCode = 1
@@ -128,7 +127,7 @@ func main() {
}
name := info.Name()
if name == "go.mod" || strings.HasSuffix(name, ".go") {
- data, err := ioutil.ReadFile(path)
+ data, err := os.ReadFile(path)
if err != nil {
return err
}
@@ -144,7 +143,7 @@ func main() {
data := txtar.Format(a)
target := filepath.Join("mod", strings.ReplaceAll(path, "/", "_")+"_"+vers+".txt")
- if err := ioutil.WriteFile(target, data, 0666); err != nil {
+ if err := os.WriteFile(target, data, 0666); err != nil {
log.Printf("%s: %v", arg, err)
exitCode = 1
continue
diff --git a/src/cmd/go/testdata/savedir.go b/src/cmd/go/testdata/savedir.go
index 75895ee279..d469c31a91 100644
--- a/src/cmd/go/testdata/savedir.go
+++ b/src/cmd/go/testdata/savedir.go
@@ -18,7 +18,6 @@ import (
"flag"
"fmt"
"io/fs"
- "io/ioutil"
"log"
"os"
"path/filepath"
@@ -63,7 +62,7 @@ func main() {
if !info.Type().IsRegular() {
return nil
}
- data, err := ioutil.ReadFile(path)
+ data, err := os.ReadFile(path)
if err != nil {
log.Fatal(err)
}
diff --git a/src/cmd/go/testdata/script/build_issue6480.txt b/src/cmd/go/testdata/script/build_issue6480.txt
index ae99c60d99..cf1e9ea6c2 100644
--- a/src/cmd/go/testdata/script/build_issue6480.txt
+++ b/src/cmd/go/testdata/script/build_issue6480.txt
@@ -81,7 +81,6 @@ package main
import (
"encoding/json"
"fmt"
- "io/ioutil"
"os"
"time"
)
@@ -100,7 +99,7 @@ func truncateLike(t, p time.Time) time.Time {
func main() {
var t1 time.Time
- b1, err := ioutil.ReadFile(os.Args[1])
+ b1, err := os.ReadFile(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
@@ -111,7 +110,7 @@ func main() {
}
var t2 time.Time
- b2, err := ioutil.ReadFile(os.Args[2])
+ b2, err := os.ReadFile(os.Args[2])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
diff --git a/src/cmd/go/testdata/script/build_trimpath.txt b/src/cmd/go/testdata/script/build_trimpath.txt
index 2c3bee8fdc..e1ea0a48b2 100644
--- a/src/cmd/go/testdata/script/build_trimpath.txt
+++ b/src/cmd/go/testdata/script/build_trimpath.txt
@@ -121,7 +121,6 @@ package main
import (
"bytes"
"fmt"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -131,7 +130,7 @@ import (
func main() {
exe := os.Args[1]
- data, err := ioutil.ReadFile(exe)
+ data, err := os.ReadFile(exe)
if err != nil {
log.Fatal(err)
}
diff --git a/src/cmd/go/testdata/script/cover_error.txt b/src/cmd/go/testdata/script/cover_error.txt
index 4abdf1137a..583a664237 100644
--- a/src/cmd/go/testdata/script/cover_error.txt
+++ b/src/cmd/go/testdata/script/cover_error.txt
@@ -54,7 +54,6 @@ func Test(t *testing.T) {}
package main
import (
- "io/ioutil"
"log"
"os"
"strings"
@@ -62,13 +61,13 @@ import (
func main() {
log.SetFlags(0)
- b, err := ioutil.ReadFile(os.Args[1])
+ b, err := os.ReadFile(os.Args[1])
if err != nil {
log.Fatal(err)
}
s := strings.ReplaceAll(string(b), "p.go:4:2:", "p.go:4:")
s = strings.ReplaceAll(s, "p1.go:6:2:", "p1.go:6:")
- ioutil.WriteFile(os.Args[1], []byte(s), 0644)
+ os.WriteFile(os.Args[1], []byte(s), 0644)
if err != nil {
log.Fatal(err)
}
diff --git a/src/cmd/go/testdata/script/gopath_moved_repo.txt b/src/cmd/go/testdata/script/gopath_moved_repo.txt
index 869980da7c..99d80bff5d 100644
--- a/src/cmd/go/testdata/script/gopath_moved_repo.txt
+++ b/src/cmd/go/testdata/script/gopath_moved_repo.txt
@@ -45,7 +45,6 @@ package main
import (
"bytes"
- "io/ioutil"
"log"
"os"
)
@@ -57,11 +56,11 @@ func main() {
base := []byte(os.Args[1])
path := os.Args[2]
- data, err := ioutil.ReadFile(path)
+ data, err := os.ReadFile(path)
if err != nil {
log.Fatal(err)
}
- err = ioutil.WriteFile(path, bytes.ReplaceAll(data, base, append(base, "XXX"...)), 0644)
+ err = os.WriteFile(path, bytes.ReplaceAll(data, base, append(base, "XXX"...)), 0644)
if err != nil {
log.Fatal(err)
}
diff --git a/src/cmd/go/testdata/script/mod_download_concurrent_read.txt b/src/cmd/go/testdata/script/mod_download_concurrent_read.txt
index caf105c6e5..231babd0c0 100644
--- a/src/cmd/go/testdata/script/mod_download_concurrent_read.txt
+++ b/src/cmd/go/testdata/script/mod_download_concurrent_read.txt
@@ -25,7 +25,6 @@ package main
import (
"fmt"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -45,7 +44,7 @@ func main() {
// don't need to clean the cache or synchronize closing files after each
// iteration.
func run() (err error) {
- tmpDir, err := ioutil.TempDir("", "")
+ tmpDir, err := os.MkdirTemp("", "")
if err != nil {
return err
}
diff --git a/src/cmd/go/testdata/script/mod_modinfo.txt b/src/cmd/go/testdata/script/mod_modinfo.txt
index d9e9fdec21..8d77e224a5 100644
--- a/src/cmd/go/testdata/script/mod_modinfo.txt
+++ b/src/cmd/go/testdata/script/mod_modinfo.txt
@@ -69,7 +69,6 @@ package main
import (
"bytes"
"encoding/hex"
- "io/ioutil"
"log"
"os"
@@ -77,7 +76,7 @@ import (
)
func main() {
- b, err := ioutil.ReadFile(os.Args[0])
+ b, err := os.ReadFile(os.Args[0])
if err != nil {
log.Fatal(err)
}
diff --git a/src/cmd/go/testdata/script/mod_test_cached.txt b/src/cmd/go/testdata/script/mod_test_cached.txt
index ffd573c02a..3da4358fa1 100644
--- a/src/cmd/go/testdata/script/mod_test_cached.txt
+++ b/src/cmd/go/testdata/script/mod_test_cached.txt
@@ -51,26 +51,25 @@ bar
package foo_test
import (
- "io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestWriteTmp(t *testing.T) {
- dir, err := ioutil.TempDir("", "")
+ dir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
- err = ioutil.WriteFile(filepath.Join(dir, "x"), nil, 0666)
+ err = os.WriteFile(filepath.Join(dir, "x"), nil, 0666)
if err != nil {
t.Fatal(err)
}
}
func TestReadTestdata(t *testing.T) {
- _, err := ioutil.ReadFile("testdata/foo.txt")
+ _, err := os.ReadFile("testdata/foo.txt")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/testdata/script/test_compile_tempfile.txt b/src/cmd/go/testdata/script/test_compile_tempfile.txt
index 912410814f..05f721a800 100644
--- a/src/cmd/go/testdata/script/test_compile_tempfile.txt
+++ b/src/cmd/go/testdata/script/test_compile_tempfile.txt
@@ -1,7 +1,7 @@
[short] skip
# Ensure that the target of 'go build -o' can be an existing, empty file so that
-# its name can be reserved using ioutil.TempFile or the 'mktemp` command.
+# its name can be reserved using os.CreateTemp or the 'mktemp` command.
go build -o empty-file$GOEXE main.go
diff --git a/src/cmd/go/testdata/script/test_generated_main.txt b/src/cmd/go/testdata/script/test_generated_main.txt
index 75ffa9cde2..2e991a5797 100644
--- a/src/cmd/go/testdata/script/test_generated_main.txt
+++ b/src/cmd/go/testdata/script/test_generated_main.txt
@@ -12,7 +12,6 @@ package x
import (
"os"
"path/filepath"
- "io/ioutil"
"regexp"
"testing"
)
@@ -23,7 +22,7 @@ func Test(t *testing.T) {
t.Fatal(err)
}
testmainPath := filepath.Join(filepath.Dir(exePath), "_testmain.go")
- source, err := ioutil.ReadFile(testmainPath)
+ source, err := os.ReadFile(testmainPath)
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/testdata/script/test_race_install_cgo.txt b/src/cmd/go/testdata/script/test_race_install_cgo.txt
index 82f00f2086..3f4eb90e3f 100644
--- a/src/cmd/go/testdata/script/test_race_install_cgo.txt
+++ b/src/cmd/go/testdata/script/test_race_install_cgo.txt
@@ -29,7 +29,6 @@ go 1.16
package main
import (
- "io/ioutil"
"encoding/json"
"fmt"
"os"
@@ -37,7 +36,7 @@ import (
)
func main() {
- b, err := ioutil.ReadFile(os.Args[1])
+ b, err := os.ReadFile(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
@@ -59,7 +58,6 @@ package main
import (
"encoding/json"
"fmt"
- "io/ioutil"
"os"
"time"
)
@@ -67,7 +65,7 @@ import (
func main() {
var t1 time.Time
- b1, err := ioutil.ReadFile(os.Args[1])
+ b1, err := os.ReadFile(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
@@ -78,7 +76,7 @@ func main() {
}
var t2 time.Time
- b2, err := ioutil.ReadFile(os.Args[2])
+ b2, err := os.ReadFile(os.Args[2])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
diff --git a/src/cmd/gofmt/gofmt.go b/src/cmd/gofmt/gofmt.go
index 719c681a3e..2793c2c2a4 100644
--- a/src/cmd/gofmt/gofmt.go
+++ b/src/cmd/gofmt/gofmt.go
@@ -15,7 +15,6 @@ import (
"go/token"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -137,7 +136,7 @@ func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error
if err != nil {
return err
}
- err = ioutil.WriteFile(filename, res, perm)
+ err = os.WriteFile(filename, res, perm)
if err != nil {
os.Rename(bakname, filename)
return err
@@ -278,7 +277,7 @@ const chmodSupported = runtime.GOOS != "windows"
// the chosen file name.
func backupFile(filename string, data []byte, perm fs.FileMode) (string, error) {
// create backup file
- f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename))
+ f, err := os.CreateTemp(filepath.Dir(filename), filepath.Base(filename))
if err != nil {
return "", err
}
diff --git a/src/cmd/gofmt/gofmt_test.go b/src/cmd/gofmt/gofmt_test.go
index 98d3eb7eb2..bf2adfe64c 100644
--- a/src/cmd/gofmt/gofmt_test.go
+++ b/src/cmd/gofmt/gofmt_test.go
@@ -7,7 +7,6 @@ package main
import (
"bytes"
"flag"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -93,7 +92,7 @@ func runTest(t *testing.T, in, out string) {
return
}
- expected, err := ioutil.ReadFile(out)
+ expected, err := os.ReadFile(out)
if err != nil {
t.Error(err)
return
@@ -102,7 +101,7 @@ func runTest(t *testing.T, in, out string) {
if got := buf.Bytes(); !bytes.Equal(got, expected) {
if *update {
if in != out {
- if err := ioutil.WriteFile(out, got, 0666); err != nil {
+ if err := os.WriteFile(out, got, 0666); err != nil {
t.Error(err)
}
return
@@ -116,7 +115,7 @@ func runTest(t *testing.T, in, out string) {
if err == nil {
t.Errorf("%s", d)
}
- if err := ioutil.WriteFile(in+".gofmt", got, 0666); err != nil {
+ if err := os.WriteFile(in+".gofmt", got, 0666); err != nil {
t.Error(err)
}
}
@@ -157,7 +156,7 @@ func TestCRLF(t *testing.T) {
const input = "testdata/crlf.input" // must contain CR/LF's
const golden = "testdata/crlf.golden" // must not contain any CR's
- data, err := ioutil.ReadFile(input)
+ data, err := os.ReadFile(input)
if err != nil {
t.Error(err)
}
@@ -165,7 +164,7 @@ func TestCRLF(t *testing.T) {
t.Errorf("%s contains no CR/LF's", input)
}
- data, err = ioutil.ReadFile(golden)
+ data, err = os.ReadFile(golden)
if err != nil {
t.Error(err)
}
@@ -175,7 +174,7 @@ func TestCRLF(t *testing.T) {
}
func TestBackupFile(t *testing.T) {
- dir, err := ioutil.TempDir("", "gofmt_test")
+ dir, err := os.MkdirTemp("", "gofmt_test")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/nm/nm_test.go b/src/cmd/nm/nm_test.go
index 382446e9fe..0d51b07a44 100644
--- a/src/cmd/nm/nm_test.go
+++ b/src/cmd/nm/nm_test.go
@@ -8,7 +8,6 @@ import (
"fmt"
"internal/obscuretestdata"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -31,7 +30,7 @@ func testMain(m *testing.M) int {
return 0
}
- tmpDir, err := ioutil.TempDir("", "TestNM")
+ tmpDir, err := os.MkdirTemp("", "TestNM")
if err != nil {
fmt.Println("TempDir failed:", err)
return 2
@@ -88,7 +87,7 @@ func TestNonGoExecs(t *testing.T) {
func testGoExec(t *testing.T, iscgo, isexternallinker bool) {
t.Parallel()
- tmpdir, err := ioutil.TempDir("", "TestGoExec")
+ tmpdir, err := os.MkdirTemp("", "TestGoExec")
if err != nil {
t.Fatal(err)
}
@@ -222,7 +221,7 @@ func TestGoExec(t *testing.T) {
func testGoLib(t *testing.T, iscgo bool) {
t.Parallel()
- tmpdir, err := ioutil.TempDir("", "TestGoLib")
+ tmpdir, err := os.MkdirTemp("", "TestGoLib")
if err != nil {
t.Fatal(err)
}
@@ -245,7 +244,7 @@ func testGoLib(t *testing.T, iscgo bool) {
err = e
}
if err == nil {
- err = ioutil.WriteFile(filepath.Join(libpath, "go.mod"), []byte("module mylib\n"), 0666)
+ err = os.WriteFile(filepath.Join(libpath, "go.mod"), []byte("module mylib\n"), 0666)
}
if err != nil {
t.Fatal(err)
diff --git a/src/cmd/objdump/objdump_test.go b/src/cmd/objdump/objdump_test.go
index cb692e7a81..edaca774f7 100644
--- a/src/cmd/objdump/objdump_test.go
+++ b/src/cmd/objdump/objdump_test.go
@@ -10,7 +10,6 @@ import (
"fmt"
"go/build"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -39,7 +38,7 @@ func TestMain(m *testing.M) {
func buildObjdump() error {
var err error
- tmp, err = ioutil.TempDir("", "TestObjDump")
+ tmp, err = os.MkdirTemp("", "TestObjDump")
if err != nil {
return fmt.Errorf("TempDir failed: %v", err)
}
@@ -320,7 +319,7 @@ func TestGoobjFileNumber(t *testing.T) {
t.Parallel()
- tmpdir, err := ioutil.TempDir("", "TestGoobjFileNumber")
+ tmpdir, err := os.MkdirTemp("", "TestGoobjFileNumber")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/pack/pack_test.go b/src/cmd/pack/pack_test.go
index 9f65705def..218c7acda6 100644
--- a/src/cmd/pack/pack_test.go
+++ b/src/cmd/pack/pack_test.go
@@ -12,7 +12,6 @@ import (
"internal/testenv"
"io"
"io/fs"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -22,7 +21,7 @@ import (
// tmpDir creates a temporary directory and returns its name.
func tmpDir(t *testing.T) string {
- name, err := ioutil.TempDir("", "pack")
+ name, err := os.MkdirTemp("", "pack")
if err != nil {
t.Fatal(err)
}
@@ -158,7 +157,7 @@ func TestExtract(t *testing.T) {
ar = openArchive(name, os.O_RDONLY, []string{goodbyeFile.name})
ar.scan(ar.extractContents)
ar.a.File().Close()
- data, err := ioutil.ReadFile(goodbyeFile.name)
+ data, err := os.ReadFile(goodbyeFile.name)
if err != nil {
t.Fatal(err)
}
@@ -183,7 +182,7 @@ func TestHello(t *testing.T) {
println("hello world")
}
`
- err := ioutil.WriteFile(hello, []byte(prog), 0666)
+ err := os.WriteFile(hello, []byte(prog), 0666)
if err != nil {
t.Fatal(err)
}
@@ -251,7 +250,7 @@ func TestLargeDefs(t *testing.T) {
println("ok")
}
`
- err = ioutil.WriteFile(main, []byte(prog), 0666)
+ err = os.WriteFile(main, []byte(prog), 0666)
if err != nil {
t.Fatal(err)
}
@@ -281,13 +280,13 @@ func TestIssue21703(t *testing.T) {
defer os.RemoveAll(dir)
const aSrc = `package a; const X = "\n!\n"`
- err := ioutil.WriteFile(filepath.Join(dir, "a.go"), []byte(aSrc), 0666)
+ err := os.WriteFile(filepath.Join(dir, "a.go"), []byte(aSrc), 0666)
if err != nil {
t.Fatal(err)
}
const bSrc = `package b; import _ "a"`
- err = ioutil.WriteFile(filepath.Join(dir, "b.go"), []byte(bSrc), 0666)
+ err = os.WriteFile(filepath.Join(dir, "b.go"), []byte(bSrc), 0666)
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/trace/annotations_test.go b/src/cmd/trace/annotations_test.go
index a9068d53c1..9c2d027366 100644
--- a/src/cmd/trace/annotations_test.go
+++ b/src/cmd/trace/annotations_test.go
@@ -12,7 +12,7 @@ import (
"flag"
"fmt"
traceparser "internal/trace"
- "io/ioutil"
+ "os"
"reflect"
"runtime/debug"
"runtime/trace"
@@ -386,7 +386,7 @@ func saveTrace(buf *bytes.Buffer, name string) {
if !*saveTraces {
return
}
- if err := ioutil.WriteFile(name+".trace", buf.Bytes(), 0600); err != nil {
+ if err := os.WriteFile(name+".trace", buf.Bytes(), 0600); err != nil {
panic(fmt.Errorf("failed to write trace file: %v", err))
}
}
diff --git a/src/cmd/trace/pprof.go b/src/cmd/trace/pprof.go
index a31d71b013..a73ff5336a 100644
--- a/src/cmd/trace/pprof.go
+++ b/src/cmd/trace/pprof.go
@@ -11,7 +11,6 @@ import (
"fmt"
"internal/trace"
"io"
- "io/ioutil"
"net/http"
"os"
"os/exec"
@@ -294,7 +293,7 @@ func serveSVGProfile(prof func(w io.Writer, r *http.Request) error) http.Handler
return
}
- blockf, err := ioutil.TempFile("", "block")
+ blockf, err := os.CreateTemp("", "block")
if err != nil {
http.Error(w, fmt.Sprintf("failed to create temp file: %v", err), http.StatusInternalServerError)
return
diff --git a/src/cmd/vet/vet_test.go b/src/cmd/vet/vet_test.go
index 5d8139d977..d15d1ce377 100644
--- a/src/cmd/vet/vet_test.go
+++ b/src/cmd/vet/vet_test.go
@@ -9,7 +9,6 @@ import (
"errors"
"fmt"
"internal/testenv"
- "io/ioutil"
"log"
"os"
"os/exec"
@@ -32,7 +31,7 @@ func TestMain(m *testing.M) {
}
func testMain(m *testing.M) int {
- dir, err := ioutil.TempDir("", "vet_test")
+ dir, err := os.MkdirTemp("", "vet_test")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
@@ -345,7 +344,7 @@ var (
func wantedErrors(file, short string) (errs []wantedError) {
cache := make(map[string]*regexp.Regexp)
- src, err := ioutil.ReadFile(file)
+ src, err := os.ReadFile(file)
if err != nil {
log.Fatal(err)
}
diff --git a/src/compress/bzip2/bzip2_test.go b/src/compress/bzip2/bzip2_test.go
index 98477791b3..e6065cb43f 100644
--- a/src/compress/bzip2/bzip2_test.go
+++ b/src/compress/bzip2/bzip2_test.go
@@ -9,7 +9,7 @@ import (
"encoding/hex"
"fmt"
"io"
- "io/ioutil"
+ "os"
"testing"
)
@@ -22,7 +22,7 @@ func mustDecodeHex(s string) []byte {
}
func mustLoadFile(f string) []byte {
- b, err := ioutil.ReadFile(f)
+ b, err := os.ReadFile(f)
if err != nil {
panic(err)
}
diff --git a/src/compress/flate/deflate_test.go b/src/compress/flate/deflate_test.go
index 6fc5abf4d5..ff56712123 100644
--- a/src/compress/flate/deflate_test.go
+++ b/src/compress/flate/deflate_test.go
@@ -10,8 +10,8 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"math/rand"
+ "os"
"reflect"
"runtime/debug"
"sync"
@@ -387,7 +387,7 @@ func TestDeflateInflateString(t *testing.T) {
t.Skip("skipping in short mode")
}
for _, test := range deflateInflateStringTests {
- gold, err := ioutil.ReadFile(test.filename)
+ gold, err := os.ReadFile(test.filename)
if err != nil {
t.Error(err)
}
@@ -685,7 +685,7 @@ func (w *failWriter) Write(b []byte) (int, error) {
func TestWriterPersistentError(t *testing.T) {
t.Parallel()
- d, err := ioutil.ReadFile("../../testdata/Isaac.Newton-Opticks.txt")
+ d, err := os.ReadFile("../../testdata/Isaac.Newton-Opticks.txt")
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
diff --git a/src/compress/flate/huffman_bit_writer_test.go b/src/compress/flate/huffman_bit_writer_test.go
index 882d3abec1..a57799cae0 100644
--- a/src/compress/flate/huffman_bit_writer_test.go
+++ b/src/compress/flate/huffman_bit_writer_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"flag"
"fmt"
- "io/ioutil"
"os"
"path/filepath"
"strings"
@@ -38,7 +37,7 @@ func TestBlockHuff(t *testing.T) {
}
func testBlockHuff(t *testing.T, in, out string) {
- all, err := ioutil.ReadFile(in)
+ all, err := os.ReadFile(in)
if err != nil {
t.Error(err)
return
@@ -49,7 +48,7 @@ func testBlockHuff(t *testing.T, in, out string) {
bw.flush()
got := buf.Bytes()
- want, err := ioutil.ReadFile(out)
+ want, err := os.ReadFile(out)
if err != nil && !*update {
t.Error(err)
return
@@ -60,7 +59,7 @@ func testBlockHuff(t *testing.T, in, out string) {
if *update {
if in != out {
t.Logf("Updating %q", out)
- if err := ioutil.WriteFile(out, got, 0666); err != nil {
+ if err := os.WriteFile(out, got, 0666); err != nil {
t.Error(err)
}
return
@@ -70,7 +69,7 @@ func testBlockHuff(t *testing.T, in, out string) {
}
t.Errorf("%q != %q (see %q)", in, out, in+".got")
- if err := ioutil.WriteFile(in+".got", got, 0666); err != nil {
+ if err := os.WriteFile(in+".got", got, 0666); err != nil {
t.Error(err)
}
return
@@ -85,7 +84,7 @@ func testBlockHuff(t *testing.T, in, out string) {
got = buf.Bytes()
if !bytes.Equal(got, want) {
t.Errorf("after reset %q != %q (see %q)", in, out, in+".reset.got")
- if err := ioutil.WriteFile(in+".reset.got", got, 0666); err != nil {
+ if err := os.WriteFile(in+".reset.got", got, 0666); err != nil {
t.Error(err)
}
return
@@ -186,7 +185,7 @@ func testBlock(t *testing.T, test huffTest, ttype string) {
if *update {
if test.input != "" {
t.Logf("Updating %q", test.want)
- input, err := ioutil.ReadFile(test.input)
+ input, err := os.ReadFile(test.input)
if err != nil {
t.Error(err)
return
@@ -216,12 +215,12 @@ func testBlock(t *testing.T, test huffTest, ttype string) {
if test.input != "" {
t.Logf("Testing %q", test.want)
- input, err := ioutil.ReadFile(test.input)
+ input, err := os.ReadFile(test.input)
if err != nil {
t.Error(err)
return
}
- want, err := ioutil.ReadFile(test.want)
+ want, err := os.ReadFile(test.want)
if err != nil {
t.Error(err)
return
@@ -233,7 +232,7 @@ func testBlock(t *testing.T, test huffTest, ttype string) {
got := buf.Bytes()
if !bytes.Equal(got, want) {
t.Errorf("writeBlock did not yield expected result for file %q with input. See %q", test.want, test.want+".got")
- if err := ioutil.WriteFile(test.want+".got", got, 0666); err != nil {
+ if err := os.WriteFile(test.want+".got", got, 0666); err != nil {
t.Error(err)
}
}
@@ -247,7 +246,7 @@ func testBlock(t *testing.T, test huffTest, ttype string) {
got = buf.Bytes()
if !bytes.Equal(got, want) {
t.Errorf("reset: writeBlock did not yield expected result for file %q with input. See %q", test.want, test.want+".reset.got")
- if err := ioutil.WriteFile(test.want+".reset.got", got, 0666); err != nil {
+ if err := os.WriteFile(test.want+".reset.got", got, 0666); err != nil {
t.Error(err)
}
return
@@ -256,7 +255,7 @@ func testBlock(t *testing.T, test huffTest, ttype string) {
testWriterEOF(t, "wb", test, true)
}
t.Logf("Testing %q", test.wantNoInput)
- wantNI, err := ioutil.ReadFile(test.wantNoInput)
+ wantNI, err := os.ReadFile(test.wantNoInput)
if err != nil {
t.Error(err)
return
@@ -268,7 +267,7 @@ func testBlock(t *testing.T, test huffTest, ttype string) {
got := buf.Bytes()
if !bytes.Equal(got, wantNI) {
t.Errorf("writeBlock did not yield expected result for file %q with input. See %q", test.wantNoInput, test.wantNoInput+".got")
- if err := ioutil.WriteFile(test.want+".got", got, 0666); err != nil {
+ if err := os.WriteFile(test.want+".got", got, 0666); err != nil {
t.Error(err)
}
} else if got[0]&1 == 1 {
@@ -286,7 +285,7 @@ func testBlock(t *testing.T, test huffTest, ttype string) {
got = buf.Bytes()
if !bytes.Equal(got, wantNI) {
t.Errorf("reset: writeBlock did not yield expected result for file %q without input. See %q", test.want, test.want+".reset.got")
- if err := ioutil.WriteFile(test.want+".reset.got", got, 0666); err != nil {
+ if err := os.WriteFile(test.want+".reset.got", got, 0666); err != nil {
t.Error(err)
}
return
@@ -325,7 +324,7 @@ func testWriterEOF(t *testing.T, ttype string, test huffTest, useInput bool) {
var input []byte
if useInput {
var err error
- input, err = ioutil.ReadFile(test.input)
+ input, err = os.ReadFile(test.input)
if err != nil {
t.Error(err)
return
diff --git a/src/compress/flate/reader_test.go b/src/compress/flate/reader_test.go
index eb32c89184..94610fbb78 100644
--- a/src/compress/flate/reader_test.go
+++ b/src/compress/flate/reader_test.go
@@ -7,7 +7,7 @@ package flate
import (
"bytes"
"io"
- "io/ioutil"
+ "os"
"runtime"
"strings"
"testing"
@@ -80,7 +80,7 @@ var sizes = []struct {
func doBench(b *testing.B, f func(b *testing.B, buf []byte, level, n int)) {
for _, suite := range suites {
- buf, err := ioutil.ReadFile(suite.file)
+ buf, err := os.ReadFile(suite.file)
if err != nil {
b.Fatal(err)
}
diff --git a/src/compress/lzw/reader_test.go b/src/compress/lzw/reader_test.go
index 6d91dd806f..d1eb76d042 100644
--- a/src/compress/lzw/reader_test.go
+++ b/src/compress/lzw/reader_test.go
@@ -8,8 +8,8 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"math"
+ "os"
"runtime"
"strconv"
"strings"
@@ -218,7 +218,7 @@ func TestNoLongerSavingPriorExpansions(t *testing.T) {
}
func BenchmarkDecoder(b *testing.B) {
- buf, err := ioutil.ReadFile("../testdata/e.txt")
+ buf, err := os.ReadFile("../testdata/e.txt")
if err != nil {
b.Fatal(err)
}
diff --git a/src/compress/lzw/writer_test.go b/src/compress/lzw/writer_test.go
index 33a28bdd3a..1a5dbcae93 100644
--- a/src/compress/lzw/writer_test.go
+++ b/src/compress/lzw/writer_test.go
@@ -8,7 +8,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"math"
"os"
"runtime"
@@ -125,7 +124,7 @@ func TestSmallLitWidth(t *testing.T) {
}
func BenchmarkEncoder(b *testing.B) {
- buf, err := ioutil.ReadFile("../testdata/e.txt")
+ buf, err := os.ReadFile("../testdata/e.txt")
if err != nil {
b.Fatal(err)
}
diff --git a/src/compress/zlib/writer_test.go b/src/compress/zlib/writer_test.go
index c518729146..f0b38880a6 100644
--- a/src/compress/zlib/writer_test.go
+++ b/src/compress/zlib/writer_test.go
@@ -9,7 +9,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"os"
"testing"
)
@@ -95,7 +94,7 @@ func testFileLevelDictReset(t *testing.T, fn string, level int, dict []byte) {
var b0 []byte
var err error
if fn != "" {
- b0, err = ioutil.ReadFile(fn)
+ b0, err = os.ReadFile(fn)
if err != nil {
t.Errorf("%s (level=%d): %v", fn, level, err)
return
diff --git a/src/crypto/md5/gen.go b/src/crypto/md5/gen.go
index a11f22059f..1468924cbc 100644
--- a/src/crypto/md5/gen.go
+++ b/src/crypto/md5/gen.go
@@ -15,8 +15,8 @@ import (
"bytes"
"flag"
"go/format"
- "io/ioutil"
"log"
+ "os"
"strings"
"text/template"
)
@@ -37,7 +37,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
- err = ioutil.WriteFile(*filename, data, 0644)
+ err = os.WriteFile(*filename, data, 0644)
if err != nil {
log.Fatal(err)
}
diff --git a/src/crypto/tls/handshake_test.go b/src/crypto/tls/handshake_test.go
index 605be587b5..d9ff9fe948 100644
--- a/src/crypto/tls/handshake_test.go
+++ b/src/crypto/tls/handshake_test.go
@@ -13,7 +13,6 @@ import (
"flag"
"fmt"
"io"
- "io/ioutil"
"net"
"os"
"os/exec"
@@ -224,7 +223,7 @@ func parseTestData(r io.Reader) (flows [][]byte, err error) {
// tempFile creates a temp file containing contents and returns its path.
func tempFile(contents string) string {
- file, err := ioutil.TempFile("", "go-tls-test")
+ file, err := os.CreateTemp("", "go-tls-test")
if err != nil {
panic("failed to create temp file: " + err.Error())
}
diff --git a/src/crypto/tls/link_test.go b/src/crypto/tls/link_test.go
index 8224216b5c..8c392ff7c4 100644
--- a/src/crypto/tls/link_test.go
+++ b/src/crypto/tls/link_test.go
@@ -7,7 +7,6 @@ package tls
import (
"bytes"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -77,7 +76,7 @@ func main() { tls.Dial("", "", nil) }
exeFile := filepath.Join(tmpDir, "x.exe")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- if err := ioutil.WriteFile(goFile, []byte(tt.program), 0644); err != nil {
+ if err := os.WriteFile(goFile, []byte(tt.program), 0644); err != nil {
t.Fatal(err)
}
os.Remove(exeFile)
diff --git a/src/crypto/tls/tls.go b/src/crypto/tls/tls.go
index bf577cadea..19884f96e7 100644
--- a/src/crypto/tls/tls.go
+++ b/src/crypto/tls/tls.go
@@ -22,8 +22,8 @@ import (
"encoding/pem"
"errors"
"fmt"
- "io/ioutil"
"net"
+ "os"
"strings"
)
@@ -222,11 +222,11 @@ func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Con
// form a certificate chain. On successful return, Certificate.Leaf will
// be nil because the parsed form of the certificate is not retained.
func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
- certPEMBlock, err := ioutil.ReadFile(certFile)
+ certPEMBlock, err := os.ReadFile(certFile)
if err != nil {
return Certificate{}, err
}
- keyPEMBlock, err := ioutil.ReadFile(keyFile)
+ keyPEMBlock, err := os.ReadFile(keyFile)
if err != nil {
return Certificate{}, err
}
diff --git a/src/crypto/x509/name_constraints_test.go b/src/crypto/x509/name_constraints_test.go
index 34055d07b5..3826c82c38 100644
--- a/src/crypto/x509/name_constraints_test.go
+++ b/src/crypto/x509/name_constraints_test.go
@@ -14,7 +14,6 @@ import (
"encoding/hex"
"encoding/pem"
"fmt"
- "io/ioutil"
"math/big"
"net"
"net/url"
@@ -2005,7 +2004,7 @@ func TestConstraintCases(t *testing.T) {
}
func writePEMsToTempFile(certs []*Certificate) *os.File {
- file, err := ioutil.TempFile("", "name_constraints_test")
+ file, err := os.CreateTemp("", "name_constraints_test")
if err != nil {
panic("cannot create tempfile")
}
diff --git a/src/crypto/x509/root_ios_gen.go b/src/crypto/x509/root_ios_gen.go
index 2bcdab1a77..8bc6e7d9c4 100644
--- a/src/crypto/x509/root_ios_gen.go
+++ b/src/crypto/x509/root_ios_gen.go
@@ -27,9 +27,9 @@ import (
"fmt"
"go/format"
"io"
- "io/ioutil"
"log"
"net/http"
+ "os"
"path"
"sort"
"strings"
@@ -155,7 +155,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
- if err := ioutil.WriteFile(*output, source, 0644); err != nil {
+ if err := os.WriteFile(*output, source, 0644); err != nil {
log.Fatal(err)
}
}
diff --git a/src/crypto/x509/root_plan9.go b/src/crypto/x509/root_plan9.go
index 09f0e23033..2dc4aaf5d7 100644
--- a/src/crypto/x509/root_plan9.go
+++ b/src/crypto/x509/root_plan9.go
@@ -7,7 +7,6 @@
package x509
import (
- "io/ioutil"
"os"
)
@@ -24,7 +23,7 @@ func loadSystemRoots() (*CertPool, error) {
roots := NewCertPool()
var bestErr error
for _, file := range certFiles {
- data, err := ioutil.ReadFile(file)
+ data, err := os.ReadFile(file)
if err == nil {
roots.AppendCertsFromPEM(data)
return roots, nil
diff --git a/src/crypto/x509/root_unix.go b/src/crypto/x509/root_unix.go
index 1090b69f83..3c643466ed 100644
--- a/src/crypto/x509/root_unix.go
+++ b/src/crypto/x509/root_unix.go
@@ -40,7 +40,7 @@ func loadSystemRoots() (*CertPool, error) {
var firstErr error
for _, file := range files {
- data, err := ioutil.ReadFile(file)
+ data, err := os.ReadFile(file)
if err == nil {
roots.AppendCertsFromPEM(data)
break
@@ -68,7 +68,7 @@ func loadSystemRoots() (*CertPool, error) {
continue
}
for _, fi := range fis {
- data, err := ioutil.ReadFile(directory + "/" + fi.Name())
+ data, err := os.ReadFile(directory + "/" + fi.Name())
if err == nil {
roots.AppendCertsFromPEM(data)
}
diff --git a/src/crypto/x509/root_unix_test.go b/src/crypto/x509/root_unix_test.go
index b2e832ff36..878ed7c2fa 100644
--- a/src/crypto/x509/root_unix_test.go
+++ b/src/crypto/x509/root_unix_test.go
@@ -9,7 +9,6 @@ package x509
import (
"bytes"
"fmt"
- "io/ioutil"
"os"
"path/filepath"
"reflect"
@@ -147,7 +146,7 @@ func TestLoadSystemCertsLoadColonSeparatedDirs(t *testing.T) {
os.Setenv(certFileEnv, origFile)
}()
- tmpDir, err := ioutil.TempDir(os.TempDir(), "x509-issue35325")
+ tmpDir, err := os.MkdirTemp(os.TempDir(), "x509-issue35325")
if err != nil {
t.Fatalf("Failed to create temporary directory: %v", err)
}
@@ -166,7 +165,7 @@ func TestLoadSystemCertsLoadColonSeparatedDirs(t *testing.T) {
t.Fatalf("Failed to create certificate dir: %v", err)
}
certOutFile := filepath.Join(certDir, "cert.crt")
- if err := ioutil.WriteFile(certOutFile, []byte(certPEM), 0655); err != nil {
+ if err := os.WriteFile(certOutFile, []byte(certPEM), 0655); err != nil {
t.Fatalf("Failed to write certificate to file: %v", err)
}
certDirs = append(certDirs, certDir)
diff --git a/src/debug/dwarf/dwarf5ranges_test.go b/src/debug/dwarf/dwarf5ranges_test.go
index 2229d439a5..0ff1a55bc9 100644
--- a/src/debug/dwarf/dwarf5ranges_test.go
+++ b/src/debug/dwarf/dwarf5ranges_test.go
@@ -6,13 +6,13 @@ package dwarf
import (
"encoding/binary"
- "io/ioutil"
+ "os"
"reflect"
"testing"
)
func TestDwarf5Ranges(t *testing.T) {
- rngLists, err := ioutil.ReadFile("testdata/debug_rnglists")
+ rngLists, err := os.ReadFile("testdata/debug_rnglists")
if err != nil {
t.Fatalf("could not read test data: %v", err)
}
diff --git a/src/debug/gosym/pclntab_test.go b/src/debug/gosym/pclntab_test.go
index f93a5bf5e5..7347139b5d 100644
--- a/src/debug/gosym/pclntab_test.go
+++ b/src/debug/gosym/pclntab_test.go
@@ -10,7 +10,6 @@ import (
"debug/elf"
"internal/testenv"
"io"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -31,7 +30,7 @@ func dotest(t *testing.T) {
t.Skipf("skipping on non-AMD64 system %s", runtime.GOARCH)
}
var err error
- pclineTempDir, err = ioutil.TempDir("", "pclinetest")
+ pclineTempDir, err = os.MkdirTemp("", "pclinetest")
if err != nil {
t.Fatal(err)
}
@@ -278,7 +277,7 @@ func TestPCLine(t *testing.T) {
// }
// [END]
func Test115PclnParsing(t *testing.T) {
- zippedDat, err := ioutil.ReadFile("testdata/pcln115.gz")
+ zippedDat, err := os.ReadFile("testdata/pcln115.gz")
if err != nil {
t.Fatal(err)
}
diff --git a/src/debug/pe/file_test.go b/src/debug/pe/file_test.go
index d96cd30904..58deff1450 100644
--- a/src/debug/pe/file_test.go
+++ b/src/debug/pe/file_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"debug/dwarf"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -354,7 +353,7 @@ func testDWARF(t *testing.T, linktype int) {
}
testenv.MustHaveGoRun(t)
- tmpdir, err := ioutil.TempDir("", "TestDWARF")
+ tmpdir, err := os.MkdirTemp("", "TestDWARF")
if err != nil {
t.Fatal(err)
}
@@ -473,7 +472,7 @@ func TestBSSHasZeros(t *testing.T) {
t.Skip("skipping test: gcc is missing")
}
- tmpdir, err := ioutil.TempDir("", "TestBSSHasZeros")
+ tmpdir, err := os.MkdirTemp("", "TestBSSHasZeros")
if err != nil {
t.Fatal(err)
}
@@ -492,7 +491,7 @@ main(void)
return 0;
}
`
- err = ioutil.WriteFile(srcpath, []byte(src), 0644)
+ err = os.WriteFile(srcpath, []byte(src), 0644)
if err != nil {
t.Fatal(err)
}
@@ -597,14 +596,14 @@ func TestBuildingWindowsGUI(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("skipping windows only test")
}
- tmpdir, err := ioutil.TempDir("", "TestBuildingWindowsGUI")
+ tmpdir, err := os.MkdirTemp("", "TestBuildingWindowsGUI")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
src := filepath.Join(tmpdir, "a.go")
- err = ioutil.WriteFile(src, []byte(`package main; func main() {}`), 0644)
+ err = os.WriteFile(src, []byte(`package main; func main() {}`), 0644)
if err != nil {
t.Fatal(err)
}
@@ -684,7 +683,7 @@ func TestInvalidOptionalHeaderMagic(t *testing.T) {
func TestImportedSymbolsNoPanicMissingOptionalHeader(t *testing.T) {
// https://golang.org/issue/30250
// ImportedSymbols shouldn't panic if optional headers is missing
- data, err := ioutil.ReadFile("testdata/gcc-amd64-mingw-obj")
+ data, err := os.ReadFile("testdata/gcc-amd64-mingw-obj")
if err != nil {
t.Fatal(err)
}
diff --git a/src/embed/internal/embedtest/embedx_test.go b/src/embed/internal/embedtest/embedx_test.go
index 53d45488f1..20d5a28c11 100644
--- a/src/embed/internal/embedtest/embedx_test.go
+++ b/src/embed/internal/embedtest/embedx_test.go
@@ -6,7 +6,7 @@ package embedtest_test
import (
"embed"
- "io/ioutil"
+ "os"
"testing"
)
@@ -59,7 +59,7 @@ func TestXGlobal(t *testing.T) {
testString(t, concurrency2, "concurrency2", "Concurrency is not parallelism.\n")
testString(t, string(glass2), "glass2", "I can eat glass and it doesn't hurt me.\n")
- big, err := ioutil.ReadFile("testdata/ascii.txt")
+ big, err := os.ReadFile("testdata/ascii.txt")
if err != nil {
t.Fatal(err)
}
diff --git a/src/go/build/build_test.go b/src/go/build/build_test.go
index 5a4a2d62f5..5a3e9ee714 100644
--- a/src/go/build/build_test.go
+++ b/src/go/build/build_test.go
@@ -8,7 +8,6 @@ import (
"flag"
"internal/testenv"
"io"
- "io/ioutil"
"os"
"path/filepath"
"reflect"
@@ -454,7 +453,7 @@ func TestImportDirNotExist(t *testing.T) {
testenv.MustHaveGoBuild(t) // really must just have source
ctxt := Default
- emptyDir, err := ioutil.TempDir("", t.Name())
+ emptyDir, err := os.MkdirTemp("", t.Name())
if err != nil {
t.Fatal(err)
}
@@ -592,7 +591,7 @@ func TestImportPackageOutsideModule(t *testing.T) {
// Create a GOPATH in a temporary directory. We don't use testdata
// because it's in GOROOT, which interferes with the module heuristic.
- gopath, err := ioutil.TempDir("", "gobuild-notmodule")
+ gopath, err := os.MkdirTemp("", "gobuild-notmodule")
if err != nil {
t.Fatal(err)
}
@@ -600,7 +599,7 @@ func TestImportPackageOutsideModule(t *testing.T) {
if err := os.MkdirAll(filepath.Join(gopath, "src/example.com/p"), 0777); err != nil {
t.Fatal(err)
}
- if err := ioutil.WriteFile(filepath.Join(gopath, "src/example.com/p/p.go"), []byte("package p"), 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(gopath, "src/example.com/p/p.go"), []byte("package p"), 0666); err != nil {
t.Fatal(err)
}
@@ -656,12 +655,12 @@ func TestIssue23594(t *testing.T) {
// Verifies golang.org/issue/34752.
func TestMissingImportErrorRepetition(t *testing.T) {
testenv.MustHaveGoBuild(t) // need 'go list' internally
- tmp, err := ioutil.TempDir("", "")
+ tmp, err := os.MkdirTemp("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
- if err := ioutil.WriteFile(filepath.Join(tmp, "go.mod"), []byte("module m"), 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(tmp, "go.mod"), []byte("module m"), 0666); err != nil {
t.Fatal(err)
}
defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE"))
diff --git a/src/go/doc/doc_test.go b/src/go/doc/doc_test.go
index ab98bed62b..cbdca62aa1 100644
--- a/src/go/doc/doc_test.go
+++ b/src/go/doc/doc_test.go
@@ -13,7 +13,7 @@ import (
"go/printer"
"go/token"
"io/fs"
- "io/ioutil"
+ "os"
"path/filepath"
"regexp"
"strings"
@@ -127,7 +127,7 @@ func test(t *testing.T, mode Mode) {
// update golden file if necessary
golden := filepath.Join(dataDir, fmt.Sprintf("%s.%d.golden", pkg.Name, mode))
if *update {
- err := ioutil.WriteFile(golden, got, 0644)
+ err := os.WriteFile(golden, got, 0644)
if err != nil {
t.Error(err)
}
@@ -135,7 +135,7 @@ func test(t *testing.T, mode Mode) {
}
// get golden file
- want, err := ioutil.ReadFile(golden)
+ want, err := os.ReadFile(golden)
if err != nil {
t.Error(err)
continue
diff --git a/src/go/format/benchmark_test.go b/src/go/format/benchmark_test.go
index 7bd45c0e95..ac19aa3bf5 100644
--- a/src/go/format/benchmark_test.go
+++ b/src/go/format/benchmark_test.go
@@ -12,7 +12,7 @@ import (
"flag"
"fmt"
"go/format"
- "io/ioutil"
+ "os"
"testing"
)
@@ -67,7 +67,7 @@ func BenchmarkFormat(b *testing.B) {
if *debug {
filename := t.name + ".src"
- err := ioutil.WriteFile(filename, data, 0660)
+ err := os.WriteFile(filename, data, 0660)
if err != nil {
b.Fatalf("couldn't write %s: %v", filename, err)
}
diff --git a/src/go/format/format_test.go b/src/go/format/format_test.go
index 58e088ede3..27f4c74cdf 100644
--- a/src/go/format/format_test.go
+++ b/src/go/format/format_test.go
@@ -9,7 +9,7 @@ import (
"go/ast"
"go/parser"
"go/token"
- "io/ioutil"
+ "os"
"strings"
"testing"
)
@@ -38,7 +38,7 @@ func diff(t *testing.T, dst, src []byte) {
}
func TestNode(t *testing.T) {
- src, err := ioutil.ReadFile(testfile)
+ src, err := os.ReadFile(testfile)
if err != nil {
t.Fatal(err)
}
@@ -96,7 +96,7 @@ func TestNodeNoModify(t *testing.T) {
}
func TestSource(t *testing.T) {
- src, err := ioutil.ReadFile(testfile)
+ src, err := os.ReadFile(testfile)
if err != nil {
t.Fatal(err)
}
diff --git a/src/go/importer/importer_test.go b/src/go/importer/importer_test.go
index ff6e12c0da..0f5121d802 100644
--- a/src/go/importer/importer_test.go
+++ b/src/go/importer/importer_test.go
@@ -8,7 +8,6 @@ import (
"go/token"
"internal/testenv"
"io"
- "io/ioutil"
"os"
"os/exec"
"runtime"
@@ -52,7 +51,7 @@ func TestForCompiler(t *testing.T) {
mathBigInt := pkg.Scope().Lookup("Int")
posn := fset.Position(mathBigInt.Pos()) // "$GOROOT/src/math/big/int.go:25:1"
filename := strings.Replace(posn.Filename, "$GOROOT", runtime.GOROOT(), 1)
- data, err := ioutil.ReadFile(filename)
+ data, err := os.ReadFile(filename)
if err != nil {
t.Fatalf("can't read file containing declaration of math/big.Int: %v", err)
}
diff --git a/src/go/internal/gccgoimporter/importer_test.go b/src/go/internal/gccgoimporter/importer_test.go
index e4236a5867..35240c8fe6 100644
--- a/src/go/internal/gccgoimporter/importer_test.go
+++ b/src/go/internal/gccgoimporter/importer_test.go
@@ -7,7 +7,6 @@ package gccgoimporter
import (
"go/types"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -150,7 +149,7 @@ func TestObjImporter(t *testing.T) {
}
t.Logf("gccgo version %d.%d", major, minor)
- tmpdir, err := ioutil.TempDir("", "TestObjImporter")
+ tmpdir, err := os.MkdirTemp("", "TestObjImporter")
if err != nil {
t.Fatal(err)
}
@@ -159,7 +158,7 @@ func TestObjImporter(t *testing.T) {
initmap := make(map[*types.Package]InitData)
imp := GetImporter([]string{tmpdir}, initmap)
- artmpdir, err := ioutil.TempDir("", "TestObjImporter")
+ artmpdir, err := os.MkdirTemp("", "TestObjImporter")
if err != nil {
t.Fatal(err)
}
diff --git a/src/go/internal/gcimporter/gcimporter_test.go b/src/go/internal/gcimporter/gcimporter_test.go
index 663753a18a..8991e3bdee 100644
--- a/src/go/internal/gcimporter/gcimporter_test.go
+++ b/src/go/internal/gcimporter/gcimporter_test.go
@@ -94,7 +94,7 @@ func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) {
}
func mktmpdir(t *testing.T) string {
- tmpdir, err := ioutil.TempDir("", "gcimporter_test")
+ tmpdir, err := os.MkdirTemp("", "gcimporter_test")
if err != nil {
t.Fatal("mktmpdir:", err)
}
@@ -199,7 +199,7 @@ func TestVersionHandling(t *testing.T) {
// create file with corrupted export data
// 1) read file
- data, err := ioutil.ReadFile(filepath.Join(dir, name))
+ data, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
t.Fatal(err)
}
@@ -216,7 +216,7 @@ func TestVersionHandling(t *testing.T) {
// 4) write the file
pkgpath += "_corrupted"
filename := filepath.Join(corruptdir, pkgpath) + ".a"
- ioutil.WriteFile(filename, data, 0666)
+ os.WriteFile(filename, data, 0666)
// test that importing the corrupted file results in an error
_, err = Import(fset, make(map[string]*types.Package), pkgpath, corruptdir, nil)
diff --git a/src/go/internal/srcimporter/srcimporter.go b/src/go/internal/srcimporter/srcimporter.go
index 90bb3a9bc1..c4d501dcd9 100644
--- a/src/go/internal/srcimporter/srcimporter.go
+++ b/src/go/internal/srcimporter/srcimporter.go
@@ -14,7 +14,6 @@ import (
"go/token"
"go/types"
"io"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -200,7 +199,7 @@ func (p *Importer) parseFiles(dir string, filenames []string) ([]*ast.File, erro
}
func (p *Importer) cgo(bp *build.Package) (*ast.File, error) {
- tmpdir, err := ioutil.TempDir("", "srcimporter")
+ tmpdir, err := os.MkdirTemp("", "srcimporter")
if err != nil {
return nil, err
}
diff --git a/src/go/parser/interface.go b/src/go/parser/interface.go
index d5c18a9e2d..41d9a52847 100644
--- a/src/go/parser/interface.go
+++ b/src/go/parser/interface.go
@@ -14,6 +14,7 @@ import (
"io"
"io/fs"
"io/ioutil"
+ "os"
"path/filepath"
"strings"
)
@@ -39,7 +40,7 @@ func readSource(filename string, src interface{}) ([]byte, error) {
}
return nil, errors.New("invalid source")
}
- return ioutil.ReadFile(filename)
+ return os.ReadFile(filename)
}
// A Mode value is a set of flags (or 0).
diff --git a/src/go/parser/performance_test.go b/src/go/parser/performance_test.go
index f2732c0e2b..f81bcee969 100644
--- a/src/go/parser/performance_test.go
+++ b/src/go/parser/performance_test.go
@@ -6,14 +6,14 @@ package parser
import (
"go/token"
- "io/ioutil"
+ "os"
"testing"
)
var src = readFile("parser.go")
func readFile(filename string) []byte {
- data, err := ioutil.ReadFile(filename)
+ data, err := os.ReadFile(filename)
if err != nil {
panic(err)
}
diff --git a/src/go/printer/performance_test.go b/src/go/printer/performance_test.go
index e23de3fbae..e655fa13ee 100644
--- a/src/go/printer/performance_test.go
+++ b/src/go/printer/performance_test.go
@@ -12,8 +12,8 @@ import (
"go/ast"
"go/parser"
"io"
- "io/ioutil"
"log"
+ "os"
"testing"
)
@@ -29,7 +29,7 @@ func testprint(out io.Writer, file *ast.File) {
func initialize() {
const filename = "testdata/parser.go"
- src, err := ioutil.ReadFile(filename)
+ src, err := os.ReadFile(filename)
if err != nil {
log.Fatalf("%s", err)
}
diff --git a/src/go/printer/printer_test.go b/src/go/printer/printer_test.go
index b64bc6bfb7..45e501115a 100644
--- a/src/go/printer/printer_test.go
+++ b/src/go/printer/printer_test.go
@@ -13,7 +13,7 @@ import (
"go/parser"
"go/token"
"io"
- "io/ioutil"
+ "os"
"path/filepath"
"testing"
"time"
@@ -119,7 +119,7 @@ func diff(aname, bname string, a, b []byte) error {
}
func runcheck(t *testing.T, source, golden string, mode checkMode) {
- src, err := ioutil.ReadFile(source)
+ src, err := os.ReadFile(source)
if err != nil {
t.Error(err)
return
@@ -133,14 +133,14 @@ func runcheck(t *testing.T, source, golden string, mode checkMode) {
// update golden files if necessary
if *update {
- if err := ioutil.WriteFile(golden, res, 0644); err != nil {
+ if err := os.WriteFile(golden, res, 0644); err != nil {
t.Error(err)
}
return
}
// get golden
- gld, err := ioutil.ReadFile(golden)
+ gld, err := os.ReadFile(golden)
if err != nil {
t.Error(err)
return
@@ -552,7 +552,7 @@ func TestBaseIndent(t *testing.T) {
// are not indented (because their values must not change) and make
// this test fail.
const filename = "printer.go"
- src, err := ioutil.ReadFile(filename)
+ src, err := os.ReadFile(filename)
if err != nil {
panic(err) // error in test
}
@@ -639,7 +639,7 @@ func (l *limitWriter) Write(buf []byte) (n int, err error) {
func TestWriteErrors(t *testing.T) {
t.Parallel()
const filename = "printer.go"
- src, err := ioutil.ReadFile(filename)
+ src, err := os.ReadFile(filename)
if err != nil {
panic(err) // error in test
}
diff --git a/src/go/scanner/scanner_test.go b/src/go/scanner/scanner_test.go
index 9d3bbbbb24..ab4c2dd962 100644
--- a/src/go/scanner/scanner_test.go
+++ b/src/go/scanner/scanner_test.go
@@ -6,7 +6,6 @@ package scanner
import (
"go/token"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -893,7 +892,7 @@ func BenchmarkScan(b *testing.B) {
func BenchmarkScanFile(b *testing.B) {
b.StopTimer()
const filename = "scanner.go"
- src, err := ioutil.ReadFile(filename)
+ src, err := os.ReadFile(filename)
if err != nil {
panic(err)
}
diff --git a/src/go/types/check_test.go b/src/go/types/check_test.go
index 37b287a20d..841ca24511 100644
--- a/src/go/types/check_test.go
+++ b/src/go/types/check_test.go
@@ -34,6 +34,7 @@ import (
"go/token"
"internal/testenv"
"io/ioutil"
+ "os"
"path/filepath"
"regexp"
"strings"
@@ -153,7 +154,7 @@ func errMap(t *testing.T, testname string, files []*ast.File) map[string][]strin
for _, file := range files {
filename := fset.Position(file.Package).Filename
- src, err := ioutil.ReadFile(filename)
+ src, err := os.ReadFile(filename)
if err != nil {
t.Fatalf("%s: could not read %s", testname, filename)
}
diff --git a/src/go/types/hilbert_test.go b/src/go/types/hilbert_test.go
index 9783ce6dc9..77954d2f8b 100644
--- a/src/go/types/hilbert_test.go
+++ b/src/go/types/hilbert_test.go
@@ -12,7 +12,7 @@ import (
"go/importer"
"go/parser"
"go/token"
- "io/ioutil"
+ "os"
"testing"
. "go/types"
@@ -27,7 +27,7 @@ func TestHilbert(t *testing.T) {
// generate source
src := program(*H, *out)
if *out != "" {
- ioutil.WriteFile(*out, src, 0666)
+ os.WriteFile(*out, src, 0666)
return
}
diff --git a/src/hash/crc32/gen_const_ppc64le.go b/src/hash/crc32/gen_const_ppc64le.go
index bfb3b3a227..d7af018af4 100644
--- a/src/hash/crc32/gen_const_ppc64le.go
+++ b/src/hash/crc32/gen_const_ppc64le.go
@@ -27,7 +27,7 @@ package main
import (
"bytes"
"fmt"
- "io/ioutil"
+ "os"
)
var blocking = 32 * 1024
@@ -103,7 +103,7 @@ func main() {
genCrc32ConstTable(w, 0xeb31d82e, "Koop")
b := w.Bytes()
- err := ioutil.WriteFile("crc32_table_ppc64le.s", b, 0666)
+ err := os.WriteFile("crc32_table_ppc64le.s", b, 0666)
if err != nil {
fmt.Printf("can't write output: %s\n", err)
}
diff --git a/src/html/template/examplefiles_test.go b/src/html/template/examplefiles_test.go
index 60518aee9e..5eb2597464 100644
--- a/src/html/template/examplefiles_test.go
+++ b/src/html/template/examplefiles_test.go
@@ -6,7 +6,6 @@ package template_test
import (
"io"
- "io/ioutil"
"log"
"os"
"path/filepath"
@@ -20,7 +19,7 @@ type templateFile struct {
}
func createTestDir(files []templateFile) string {
- dir, err := ioutil.TempDir("", "template")
+ dir, err := os.MkdirTemp("", "template")
if err != nil {
log.Fatal(err)
}
diff --git a/src/html/template/template.go b/src/html/template/template.go
index bc960afe5f..69312d36fd 100644
--- a/src/html/template/template.go
+++ b/src/html/template/template.go
@@ -8,7 +8,7 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
+ "os"
"path"
"path/filepath"
"sync"
@@ -523,7 +523,7 @@ func parseFS(t *Template, fsys fs.FS, patterns []string) (*Template, error) {
func readFileOS(file string) (name string, b []byte, err error) {
name = filepath.Base(file)
- b, err = ioutil.ReadFile(file)
+ b, err = os.ReadFile(file)
return
}
diff --git a/src/image/color/palette/gen.go b/src/image/color/palette/gen.go
index f8587db8f3..3243e53981 100644
--- a/src/image/color/palette/gen.go
+++ b/src/image/color/palette/gen.go
@@ -15,8 +15,8 @@ import (
"fmt"
"go/format"
"io"
- "io/ioutil"
"log"
+ "os"
)
var filename = flag.String("output", "palette.go", "output file name")
@@ -43,7 +43,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
- err = ioutil.WriteFile(*filename, data, 0644)
+ err = os.WriteFile(*filename, data, 0644)
if err != nil {
log.Fatal(err)
}
diff --git a/src/image/gif/reader_test.go b/src/image/gif/reader_test.go
index 29f47b6c08..5eec5ecb4a 100644
--- a/src/image/gif/reader_test.go
+++ b/src/image/gif/reader_test.go
@@ -11,7 +11,7 @@ import (
"image/color"
"image/color/palette"
"io"
- "io/ioutil"
+ "os"
"reflect"
"runtime"
"runtime/debug"
@@ -424,7 +424,7 @@ func TestDecodeMemoryConsumption(t *testing.T) {
}
func BenchmarkDecode(b *testing.B) {
- data, err := ioutil.ReadFile("../testdata/video-001.gif")
+ data, err := os.ReadFile("../testdata/video-001.gif")
if err != nil {
b.Fatal(err)
}
diff --git a/src/image/internal/imageutil/gen.go b/src/image/internal/imageutil/gen.go
index bc85c512f9..36de5dc9cc 100644
--- a/src/image/internal/imageutil/gen.go
+++ b/src/image/internal/imageutil/gen.go
@@ -11,7 +11,6 @@ import (
"flag"
"fmt"
"go/format"
- "io/ioutil"
"log"
"os"
)
@@ -36,7 +35,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
- if err := ioutil.WriteFile("impl.go", out, 0660); err != nil {
+ if err := os.WriteFile("impl.go", out, 0660); err != nil {
log.Fatal(err)
}
}
diff --git a/src/image/jpeg/reader_test.go b/src/image/jpeg/reader_test.go
index 1e2798c945..bf07fadede 100644
--- a/src/image/jpeg/reader_test.go
+++ b/src/image/jpeg/reader_test.go
@@ -11,7 +11,6 @@ import (
"image"
"image/color"
"io"
- "io/ioutil"
"math/rand"
"os"
"strings"
@@ -118,7 +117,7 @@ func (r *eofReader) Read(b []byte) (n int, err error) {
func TestDecodeEOF(t *testing.T) {
// Check that if reader returns final data and EOF at same time, jpeg handles it.
- data, err := ioutil.ReadFile("../testdata/video-001.jpeg")
+ data, err := os.ReadFile("../testdata/video-001.jpeg")
if err != nil {
t.Fatal(err)
}
@@ -189,7 +188,7 @@ func pixString(pix []byte, stride, x, y int) string {
}
func TestTruncatedSOSDataDoesntPanic(t *testing.T) {
- b, err := ioutil.ReadFile("../testdata/video-005.gray.q50.jpeg")
+ b, err := os.ReadFile("../testdata/video-005.gray.q50.jpeg")
if err != nil {
t.Fatal(err)
}
@@ -493,7 +492,7 @@ func TestExtraneousData(t *testing.T) {
}
func benchmarkDecode(b *testing.B, filename string) {
- data, err := ioutil.ReadFile(filename)
+ data, err := os.ReadFile(filename)
if err != nil {
b.Fatal(err)
}
diff --git a/src/image/png/reader_test.go b/src/image/png/reader_test.go
index 22c704e5cb..3937685294 100644
--- a/src/image/png/reader_test.go
+++ b/src/image/png/reader_test.go
@@ -11,7 +11,6 @@ import (
"image"
"image/color"
"io"
- "io/ioutil"
"os"
"reflect"
"strings"
@@ -785,7 +784,7 @@ func TestDimensionOverflow(t *testing.T) {
}
func benchmarkDecode(b *testing.B, filename string, bytesPerPixel int) {
- data, err := ioutil.ReadFile(filename)
+ data, err := os.ReadFile(filename)
if err != nil {
b.Fatal(err)
}
diff --git a/src/index/suffixarray/gen.go b/src/index/suffixarray/gen.go
index 8c3de553c9..94184d71b6 100644
--- a/src/index/suffixarray/gen.go
+++ b/src/index/suffixarray/gen.go
@@ -11,8 +11,8 @@ package main
import (
"bytes"
- "io/ioutil"
"log"
+ "os"
"strings"
)
@@ -20,7 +20,7 @@ func main() {
log.SetPrefix("gen: ")
log.SetFlags(0)
- data, err := ioutil.ReadFile("sais.go")
+ data, err := os.ReadFile("sais.go")
if err != nil {
log.Fatal(err)
}
@@ -64,7 +64,7 @@ func main() {
}
}
- if err := ioutil.WriteFile("sais2.go", buf.Bytes(), 0666); err != nil {
+ if err := os.WriteFile("sais2.go", buf.Bytes(), 0666); err != nil {
log.Fatal(err)
}
}
diff --git a/src/index/suffixarray/suffixarray_test.go b/src/index/suffixarray/suffixarray_test.go
index a11a98dae0..44c5041535 100644
--- a/src/index/suffixarray/suffixarray_test.go
+++ b/src/index/suffixarray/suffixarray_test.go
@@ -8,8 +8,8 @@ import (
"bytes"
"fmt"
"io/fs"
- "io/ioutil"
"math/rand"
+ "os"
"path/filepath"
"regexp"
"sort"
@@ -498,14 +498,14 @@ func makeText(name string) ([]byte, error) {
switch name {
case "opticks":
var err error
- data, err = ioutil.ReadFile("../../testdata/Isaac.Newton-Opticks.txt")
+ data, err = os.ReadFile("../../testdata/Isaac.Newton-Opticks.txt")
if err != nil {
return nil, err
}
case "go":
err := filepath.WalkDir("../..", func(path string, info fs.DirEntry, err error) error {
if err == nil && strings.HasSuffix(path, ".go") && !info.IsDir() {
- file, err := ioutil.ReadFile(path)
+ file, err := os.ReadFile(path)
if err != nil {
return err
}
diff --git a/src/internal/cpu/cpu_s390x_test.go b/src/internal/cpu/cpu_s390x_test.go
index d910bbe695..ad86858db0 100644
--- a/src/internal/cpu/cpu_s390x_test.go
+++ b/src/internal/cpu/cpu_s390x_test.go
@@ -7,13 +7,13 @@ package cpu_test
import (
"errors"
. "internal/cpu"
- "io/ioutil"
+ "os"
"regexp"
"testing"
)
func getFeatureList() ([]string, error) {
- cpuinfo, err := ioutil.ReadFile("/proc/cpuinfo")
+ cpuinfo, err := os.ReadFile("/proc/cpuinfo")
if err != nil {
return nil, err
}
diff --git a/src/internal/obscuretestdata/obscuretestdata.go b/src/internal/obscuretestdata/obscuretestdata.go
index 06cd1df22c..5ea2cdf5d1 100644
--- a/src/internal/obscuretestdata/obscuretestdata.go
+++ b/src/internal/obscuretestdata/obscuretestdata.go
@@ -10,7 +10,6 @@ package obscuretestdata
import (
"encoding/base64"
"io"
- "io/ioutil"
"os"
)
@@ -24,7 +23,7 @@ func DecodeToTempFile(name string) (path string, err error) {
}
defer f.Close()
- tmp, err := ioutil.TempFile("", "obscuretestdata-decoded-")
+ tmp, err := os.CreateTemp("", "obscuretestdata-decoded-")
if err != nil {
return "", err
}
diff --git a/src/internal/poll/read_test.go b/src/internal/poll/read_test.go
index 2d4ef97da0..598a52ee44 100644
--- a/src/internal/poll/read_test.go
+++ b/src/internal/poll/read_test.go
@@ -5,7 +5,6 @@
package poll_test
import (
- "io/ioutil"
"os"
"runtime"
"sync"
@@ -22,7 +21,7 @@ func TestRead(t *testing.T) {
go func(p string) {
defer wg.Done()
for i := 0; i < 100; i++ {
- if _, err := ioutil.ReadFile(p); err != nil {
+ if _, err := os.ReadFile(p); err != nil {
t.Error(err)
return
}
diff --git a/src/internal/testenv/testenv_windows.go b/src/internal/testenv/testenv_windows.go
index eb8d6ac165..4802b13951 100644
--- a/src/internal/testenv/testenv_windows.go
+++ b/src/internal/testenv/testenv_windows.go
@@ -5,7 +5,6 @@
package testenv
import (
- "io/ioutil"
"os"
"path/filepath"
"sync"
@@ -16,7 +15,7 @@ var symlinkOnce sync.Once
var winSymlinkErr error
func initWinHasSymlink() {
- tmpdir, err := ioutil.TempDir("", "symtest")
+ tmpdir, err := os.MkdirTemp("", "symtest")
if err != nil {
panic("failed to create temp directory: " + err.Error())
}
diff --git a/src/internal/trace/gc_test.go b/src/internal/trace/gc_test.go
index 4f9c77041a..9b9771e7b0 100644
--- a/src/internal/trace/gc_test.go
+++ b/src/internal/trace/gc_test.go
@@ -6,8 +6,8 @@ package trace
import (
"bytes"
- "io/ioutil"
"math"
+ "os"
"testing"
"time"
)
@@ -84,7 +84,7 @@ func TestMMUTrace(t *testing.T) {
t.Skip("skipping in -short mode")
}
- data, err := ioutil.ReadFile("testdata/stress_1_10_good")
+ data, err := os.ReadFile("testdata/stress_1_10_good")
if err != nil {
t.Fatalf("failed to read input file: %v", err)
}
@@ -126,7 +126,7 @@ func TestMMUTrace(t *testing.T) {
}
func BenchmarkMMU(b *testing.B) {
- data, err := ioutil.ReadFile("testdata/stress_1_10_good")
+ data, err := os.ReadFile("testdata/stress_1_10_good")
if err != nil {
b.Fatalf("failed to read input file: %v", err)
}
diff --git a/src/internal/trace/parser_test.go b/src/internal/trace/parser_test.go
index 6d87970157..316220cfa8 100644
--- a/src/internal/trace/parser_test.go
+++ b/src/internal/trace/parser_test.go
@@ -47,7 +47,7 @@ func TestParseCanned(t *testing.T) {
if testing.Short() && info.Size() > 10000 {
continue
}
- data, err := ioutil.ReadFile(name)
+ data, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
}
diff --git a/src/log/syslog/syslog_test.go b/src/log/syslog/syslog_test.go
index 8f472a56b7..207bcf57c1 100644
--- a/src/log/syslog/syslog_test.go
+++ b/src/log/syslog/syslog_test.go
@@ -10,7 +10,6 @@ import (
"bufio"
"fmt"
"io"
- "io/ioutil"
"log"
"net"
"os"
@@ -88,8 +87,8 @@ func startServer(n, la string, done chan<- string) (addr string, sock io.Closer,
} else {
// unix and unixgram: choose an address if none given
if la == "" {
- // use ioutil.TempFile to get a name that is unique
- f, err := ioutil.TempFile("", "syslogtest")
+ // use os.CreateTemp to get a name that is unique
+ f, err := os.CreateTemp("", "syslogtest")
if err != nil {
log.Fatal("TempFile: ", err)
}
diff --git a/src/math/big/link_test.go b/src/math/big/link_test.go
index 2212bd444f..42f9cefca0 100644
--- a/src/math/big/link_test.go
+++ b/src/math/big/link_test.go
@@ -7,7 +7,7 @@ package big
import (
"bytes"
"internal/testenv"
- "io/ioutil"
+ "os"
"os/exec"
"path/filepath"
"testing"
@@ -27,7 +27,7 @@ func TestLinkerGC(t *testing.T) {
import _ "math/big"
func main() {}
`)
- if err := ioutil.WriteFile(goFile, file, 0644); err != nil {
+ if err := os.WriteFile(goFile, file, 0644); err != nil {
t.Fatal(err)
}
cmd := exec.Command(goBin, "build", "-o", "x.exe", "x.go")
diff --git a/src/math/bits/make_examples.go b/src/math/bits/make_examples.go
index cd81cd6c4d..1d3ad53fe6 100644
--- a/src/math/bits/make_examples.go
+++ b/src/math/bits/make_examples.go
@@ -11,9 +11,9 @@ package main
import (
"bytes"
"fmt"
- "io/ioutil"
"log"
"math/bits"
+ "os"
)
const header = `// Copyright 2017 The Go Authors. All rights reserved.
@@ -106,7 +106,7 @@ func main() {
}
}
- if err := ioutil.WriteFile("example_test.go", w.Bytes(), 0666); err != nil {
+ if err := os.WriteFile("example_test.go", w.Bytes(), 0666); err != nil {
log.Fatal(err)
}
}
diff --git a/src/math/bits/make_tables.go b/src/math/bits/make_tables.go
index ff2fe2e385..b068d5e0e3 100644
--- a/src/math/bits/make_tables.go
+++ b/src/math/bits/make_tables.go
@@ -13,8 +13,8 @@ import (
"fmt"
"go/format"
"io"
- "io/ioutil"
"log"
+ "os"
)
var header = []byte(`// Copyright 2017 The Go Authors. All rights reserved.
@@ -40,7 +40,7 @@ func main() {
log.Fatal(err)
}
- err = ioutil.WriteFile("bits_tables.go", out, 0666)
+ err = os.WriteFile("bits_tables.go", out, 0666)
if err != nil {
log.Fatal(err)
}
diff --git a/src/mime/multipart/formdata.go b/src/mime/multipart/formdata.go
index 9c42ea8c02..fca5f9e15f 100644
--- a/src/mime/multipart/formdata.go
+++ b/src/mime/multipart/formdata.go
@@ -8,7 +8,6 @@ import (
"bytes"
"errors"
"io"
- "io/ioutil"
"math"
"net/textproto"
"os"
@@ -91,7 +90,7 @@ func (r *Reader) readForm(maxMemory int64) (_ *Form, err error) {
}
if n > maxMemory {
// too big, write to disk and flush buffer
- file, err := ioutil.TempFile("", "multipart-")
+ file, err := os.CreateTemp("", "multipart-")
if err != nil {
return nil, err
}
diff --git a/src/net/dnsclient_unix_test.go b/src/net/dnsclient_unix_test.go
index 06553636ee..0530c92c2e 100644
--- a/src/net/dnsclient_unix_test.go
+++ b/src/net/dnsclient_unix_test.go
@@ -10,7 +10,6 @@ import (
"context"
"errors"
"fmt"
- "io/ioutil"
"os"
"path"
"reflect"
@@ -235,7 +234,7 @@ type resolvConfTest struct {
}
func newResolvConfTest() (*resolvConfTest, error) {
- dir, err := ioutil.TempDir("", "go-resolvconftest")
+ dir, err := os.MkdirTemp("", "go-resolvconftest")
if err != nil {
return nil, err
}
diff --git a/src/net/error_test.go b/src/net/error_test.go
index 7823fdf9d8..556eb8c8d4 100644
--- a/src/net/error_test.go
+++ b/src/net/error_test.go
@@ -13,7 +13,6 @@ import (
"internal/poll"
"io"
"io/fs"
- "io/ioutil"
"net/internal/socktest"
"os"
"runtime"
@@ -730,7 +729,7 @@ func TestFileError(t *testing.T) {
t.Skipf("not supported on %s", runtime.GOOS)
}
- f, err := ioutil.TempFile("", "go-nettest")
+ f, err := os.CreateTemp("", "go-nettest")
if err != nil {
t.Fatal(err)
}
diff --git a/src/net/http/filetransport_test.go b/src/net/http/filetransport_test.go
index fdfd44d967..b58888dcb1 100644
--- a/src/net/http/filetransport_test.go
+++ b/src/net/http/filetransport_test.go
@@ -6,7 +6,6 @@ package http
import (
"io"
- "io/ioutil"
"os"
"path/filepath"
"testing"
@@ -24,10 +23,10 @@ func checker(t *testing.T) func(string, error) {
func TestFileTransport(t *testing.T) {
check := checker(t)
- dname, err := ioutil.TempDir("", "")
+ dname, err := os.MkdirTemp("", "")
check("TempDir", err)
fname := filepath.Join(dname, "foo.txt")
- err = ioutil.WriteFile(fname, []byte("Bar"), 0644)
+ err = os.WriteFile(fname, []byte("Bar"), 0644)
check("WriteFile", err)
defer os.Remove(dname)
defer os.Remove(fname)
diff --git a/src/net/http/fs_test.go b/src/net/http/fs_test.go
index 2e4751114d..2499051625 100644
--- a/src/net/http/fs_test.go
+++ b/src/net/http/fs_test.go
@@ -79,7 +79,7 @@ func TestServeFile(t *testing.T) {
var err error
- file, err := ioutil.ReadFile(testFile)
+ file, err := os.ReadFile(testFile)
if err != nil {
t.Fatal("reading file:", err)
}
@@ -379,12 +379,12 @@ func mustRemoveAll(dir string) {
func TestFileServerImplicitLeadingSlash(t *testing.T) {
defer afterTest(t)
- tempDir, err := ioutil.TempDir("", "")
+ tempDir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
defer mustRemoveAll(tempDir)
- if err := ioutil.WriteFile(filepath.Join(tempDir, "foo.txt"), []byte("Hello world"), 0644); err != nil {
+ if err := os.WriteFile(filepath.Join(tempDir, "foo.txt"), []byte("Hello world"), 0644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
ts := httptest.NewServer(StripPrefix("/bar/", FileServer(Dir(tempDir))))
@@ -1177,7 +1177,7 @@ func TestLinuxSendfile(t *testing.T) {
filename := fmt.Sprintf("1kb-%d", os.Getpid())
filepath := path.Join(os.TempDir(), filename)
- if err := ioutil.WriteFile(filepath, bytes.Repeat([]byte{'a'}, 1<<10), 0755); err != nil {
+ if err := os.WriteFile(filepath, bytes.Repeat([]byte{'a'}, 1<<10), 0755); err != nil {
t.Fatal(err)
}
defer os.Remove(filepath)
diff --git a/src/net/http/request_test.go b/src/net/http/request_test.go
index 689498e19d..29297b0e7b 100644
--- a/src/net/http/request_test.go
+++ b/src/net/http/request_test.go
@@ -12,7 +12,6 @@ import (
"encoding/base64"
"fmt"
"io"
- "io/ioutil"
"math"
"mime/multipart"
. "net/http"
@@ -1164,7 +1163,7 @@ func BenchmarkFileAndServer_64MB(b *testing.B) {
}
func benchmarkFileAndServer(b *testing.B, n int64) {
- f, err := ioutil.TempFile(os.TempDir(), "go-bench-http-file-and-server")
+ f, err := os.CreateTemp(os.TempDir(), "go-bench-http-file-and-server")
if err != nil {
b.Fatalf("Failed to create temp file: %v", err)
}
diff --git a/src/net/http/transfer_test.go b/src/net/http/transfer_test.go
index 1f3d32526d..f0c28b2629 100644
--- a/src/net/http/transfer_test.go
+++ b/src/net/http/transfer_test.go
@@ -10,7 +10,6 @@ import (
"crypto/rand"
"fmt"
"io"
- "io/ioutil"
"os"
"reflect"
"strings"
@@ -118,7 +117,7 @@ func TestTransferWriterWriteBodyReaderTypes(t *testing.T) {
nBytes := int64(1 << 10)
newFileFunc := func() (r io.Reader, done func(), err error) {
- f, err := ioutil.TempFile("", "net-http-newfilefunc")
+ f, err := os.CreateTemp("", "net-http-newfilefunc")
if err != nil {
return nil, nil, err
}
diff --git a/src/net/http/transport_test.go b/src/net/http/transport_test.go
index f22b798035..7f6e0938c2 100644
--- a/src/net/http/transport_test.go
+++ b/src/net/http/transport_test.go
@@ -23,7 +23,6 @@ import (
"go/token"
"internal/nettrace"
"io"
- "io/ioutil"
"log"
mrand "math/rand"
"net"
@@ -5746,7 +5745,7 @@ func (c *testMockTCPConn) ReadFrom(r io.Reader) (int64, error) {
func TestTransportRequestWriteRoundTrip(t *testing.T) {
nBytes := int64(1 << 10)
newFileFunc := func() (r io.Reader, done func(), err error) {
- f, err := ioutil.TempFile("", "net-http-newfilefunc")
+ f, err := os.CreateTemp("", "net-http-newfilefunc")
if err != nil {
return nil, nil, err
}
diff --git a/src/net/mockserver_test.go b/src/net/mockserver_test.go
index e085f4440b..9faf173679 100644
--- a/src/net/mockserver_test.go
+++ b/src/net/mockserver_test.go
@@ -9,16 +9,15 @@ package net
import (
"errors"
"fmt"
- "io/ioutil"
"os"
"sync"
"testing"
"time"
)
-// testUnixAddr uses ioutil.TempFile to get a name that is unique.
+// testUnixAddr uses os.CreateTemp to get a name that is unique.
func testUnixAddr() string {
- f, err := ioutil.TempFile("", "go-nettest")
+ f, err := os.CreateTemp("", "go-nettest")
if err != nil {
panic(err)
}
diff --git a/src/net/net_windows_test.go b/src/net/net_windows_test.go
index 8aa719f433..a0000950c6 100644
--- a/src/net/net_windows_test.go
+++ b/src/net/net_windows_test.go
@@ -9,7 +9,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"os"
"os/exec"
"regexp"
@@ -176,7 +175,7 @@ func runCmd(args ...string) ([]byte, error) {
}
return b
}
- f, err := ioutil.TempFile("", "netcmd")
+ f, err := os.CreateTemp("", "netcmd")
if err != nil {
return nil, err
}
@@ -189,7 +188,7 @@ func runCmd(args ...string) ([]byte, error) {
return nil, fmt.Errorf("%s failed: %v: %q", args[0], err, string(removeUTF8BOM(out)))
}
var err2 error
- out, err2 = ioutil.ReadFile(f.Name())
+ out, err2 = os.ReadFile(f.Name())
if err2 != nil {
return nil, err2
}
@@ -198,7 +197,7 @@ func runCmd(args ...string) ([]byte, error) {
}
return nil, fmt.Errorf("%s failed: %v", args[0], err)
}
- out, err = ioutil.ReadFile(f.Name())
+ out, err = os.ReadFile(f.Name())
if err != nil {
return nil, err
}
diff --git a/src/net/unixsock_test.go b/src/net/unixsock_test.go
index 4b2cfc4d62..0b13bf655f 100644
--- a/src/net/unixsock_test.go
+++ b/src/net/unixsock_test.go
@@ -9,7 +9,6 @@ package net
import (
"bytes"
"internal/testenv"
- "io/ioutil"
"os"
"reflect"
"runtime"
@@ -417,7 +416,7 @@ func TestUnixUnlink(t *testing.T) {
checkExists(t, "after Listen")
l.Close()
checkNotExists(t, "after Listener close")
- if err := ioutil.WriteFile(name, []byte("hello world"), 0666); err != nil {
+ if err := os.WriteFile(name, []byte("hello world"), 0666); err != nil {
t.Fatalf("cannot recreate socket file: %v", err)
}
checkExists(t, "after writing temp file")
diff --git a/src/os/error_test.go b/src/os/error_test.go
index 060cf59875..6264ccc966 100644
--- a/src/os/error_test.go
+++ b/src/os/error_test.go
@@ -8,14 +8,13 @@ import (
"errors"
"fmt"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestErrIsExist(t *testing.T) {
- f, err := ioutil.TempFile("", "_Go_ErrIsExist")
+ f, err := os.CreateTemp("", "_Go_ErrIsExist")
if err != nil {
t.Fatalf("open ErrIsExist tempfile: %s", err)
return
@@ -55,7 +54,7 @@ func testErrNotExist(name string) string {
}
func TestErrIsNotExist(t *testing.T) {
- tmpDir, err := ioutil.TempDir("", "_Go_ErrIsNotExist")
+ tmpDir, err := os.MkdirTemp("", "_Go_ErrIsNotExist")
if err != nil {
t.Fatalf("create ErrIsNotExist tempdir: %s", err)
return
@@ -147,12 +146,12 @@ func TestIsPermission(t *testing.T) {
}
func TestErrPathNUL(t *testing.T) {
- f, err := ioutil.TempFile("", "_Go_ErrPathNUL\x00")
+ f, err := os.CreateTemp("", "_Go_ErrPathNUL\x00")
if err == nil {
f.Close()
t.Fatal("TempFile should have failed")
}
- f, err = ioutil.TempFile("", "_Go_ErrPathNUL")
+ f, err = os.CreateTemp("", "_Go_ErrPathNUL")
if err != nil {
t.Fatalf("open ErrPathNUL tempfile: %s", err)
}
diff --git a/src/os/exec/exec_test.go b/src/os/exec/exec_test.go
index fc49b8a332..92429f63a5 100644
--- a/src/os/exec/exec_test.go
+++ b/src/os/exec/exec_test.go
@@ -645,7 +645,7 @@ func TestExtraFiles(t *testing.T) {
t.Errorf("success trying to fetch %s; want an error", ts.URL)
}
- tf, err := ioutil.TempFile("", "")
+ tf, err := os.CreateTemp("", "")
if err != nil {
t.Fatalf("TempFile: %v", err)
}
diff --git a/src/os/exec/lp_unix_test.go b/src/os/exec/lp_unix_test.go
index e4656cafb8..296480fd04 100644
--- a/src/os/exec/lp_unix_test.go
+++ b/src/os/exec/lp_unix_test.go
@@ -7,13 +7,12 @@
package exec
import (
- "io/ioutil"
"os"
"testing"
)
func TestLookPathUnixEmptyPath(t *testing.T) {
- tmp, err := ioutil.TempDir("", "TestLookPathUnixEmptyPath")
+ tmp, err := os.MkdirTemp("", "TestLookPathUnixEmptyPath")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
diff --git a/src/os/exec/lp_windows_test.go b/src/os/exec/lp_windows_test.go
index 59b5f1c2c7..c6f3d5d406 100644
--- a/src/os/exec/lp_windows_test.go
+++ b/src/os/exec/lp_windows_test.go
@@ -11,7 +11,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -307,7 +306,7 @@ var lookPathTests = []lookPathTest{
}
func TestLookPath(t *testing.T) {
- tmp, err := ioutil.TempDir("", "TestLookPath")
+ tmp, err := os.MkdirTemp("", "TestLookPath")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
@@ -504,7 +503,7 @@ var commandTests = []commandTest{
}
func TestCommand(t *testing.T) {
- tmp, err := ioutil.TempDir("", "TestCommand")
+ tmp, err := os.MkdirTemp("", "TestCommand")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
@@ -529,7 +528,7 @@ func TestCommand(t *testing.T) {
func buildPrintPathExe(t *testing.T, dir string) string {
const name = "printpath"
srcname := name + ".go"
- err := ioutil.WriteFile(filepath.Join(dir, srcname), []byte(printpathSrc), 0644)
+ err := os.WriteFile(filepath.Join(dir, srcname), []byte(printpathSrc), 0644)
if err != nil {
t.Fatalf("failed to create source: %v", err)
}
diff --git a/src/os/fifo_test.go b/src/os/fifo_test.go
index 3041dcfa02..2439192a9d 100644
--- a/src/os/fifo_test.go
+++ b/src/os/fifo_test.go
@@ -11,7 +11,6 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -31,7 +30,7 @@ func TestFifoEOF(t *testing.T) {
t.Skip("skipping on OpenBSD; issue 25877")
}
- dir, err := ioutil.TempDir("", "TestFifoEOF")
+ dir, err := os.MkdirTemp("", "TestFifoEOF")
if err != nil {
t.Fatal(err)
}
diff --git a/src/os/os_test.go b/src/os/os_test.go
index c5e5cbbb1b..765797f5fb 100644
--- a/src/os/os_test.go
+++ b/src/os/os_test.go
@@ -11,7 +11,7 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
+ "os"
. "os"
osexec "os/exec"
"path/filepath"
@@ -155,7 +155,7 @@ func localTmp() string {
}
func newFile(testName string, t *testing.T) (f *File) {
- f, err := ioutil.TempFile(localTmp(), "_Go_"+testName)
+ f, err := os.CreateTemp(localTmp(), "_Go_"+testName)
if err != nil {
t.Fatalf("TempFile %s: %s", testName, err)
}
@@ -163,7 +163,7 @@ func newFile(testName string, t *testing.T) (f *File) {
}
func newDir(testName string, t *testing.T) (name string) {
- name, err := ioutil.TempDir(localTmp(), "_Go_"+testName)
+ name, err := os.MkdirTemp(localTmp(), "_Go_"+testName)
if err != nil {
t.Fatalf("TempDir %s: %s", testName, err)
}
@@ -616,7 +616,7 @@ func TestReaddirNValues(t *testing.T) {
if testing.Short() {
t.Skip("test.short; skipping")
}
- dir, err := ioutil.TempDir("", "")
+ dir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
@@ -715,7 +715,7 @@ func TestReaddirStatFailures(t *testing.T) {
// testing it wouldn't work.
t.Skipf("skipping test on %v", runtime.GOOS)
}
- dir, err := ioutil.TempDir("", "")
+ dir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
@@ -776,7 +776,7 @@ func TestReaddirStatFailures(t *testing.T) {
// Readdir on a regular file should fail.
func TestReaddirOfFile(t *testing.T) {
- f, err := ioutil.TempFile("", "_Go_ReaddirOfFile")
+ f, err := os.CreateTemp("", "_Go_ReaddirOfFile")
if err != nil {
t.Fatal(err)
}
@@ -867,7 +867,7 @@ func chtmpdir(t *testing.T) func() {
if err != nil {
t.Fatalf("chtmpdir: %v", err)
}
- d, err := ioutil.TempDir("", "test")
+ d, err := os.MkdirTemp("", "test")
if err != nil {
t.Fatalf("chtmpdir: %v", err)
}
@@ -992,12 +992,12 @@ func TestRenameOverwriteDest(t *testing.T) {
toData := []byte("to")
fromData := []byte("from")
- err := ioutil.WriteFile(to, toData, 0777)
+ err := os.WriteFile(to, toData, 0777)
if err != nil {
t.Fatalf("write file %q failed: %v", to, err)
}
- err = ioutil.WriteFile(from, fromData, 0777)
+ err = os.WriteFile(from, fromData, 0777)
if err != nil {
t.Fatalf("write file %q failed: %v", from, err)
}
@@ -1341,7 +1341,7 @@ func testChtimes(t *testing.T, name string) {
// the contents are accessed; also, it is set
// whenever mtime is set.
case "netbsd":
- mounts, _ := ioutil.ReadFile("/proc/mounts")
+ mounts, _ := os.ReadFile("/proc/mounts")
if strings.Contains(string(mounts), "noatime") {
t.Logf("AccessTime didn't go backwards, but see a filesystem mounted noatime; ignoring. Issue 19293.")
} else {
@@ -1415,7 +1415,7 @@ func TestChdirAndGetwd(t *testing.T) {
case "arm64":
dirs = nil
for _, d := range []string{"d1", "d2"} {
- dir, err := ioutil.TempDir("", d)
+ dir, err := os.MkdirTemp("", d)
if err != nil {
t.Fatalf("TempDir: %v", err)
}
@@ -1509,7 +1509,7 @@ func TestProgWideChdir(t *testing.T) {
c <- true
t.Fatalf("Getwd: %v", err)
}
- d, err := ioutil.TempDir("", "test")
+ d, err := os.MkdirTemp("", "test")
if err != nil {
c <- true
t.Fatalf("TempDir: %v", err)
@@ -1576,7 +1576,7 @@ func TestSeek(t *testing.T) {
off, err := f.Seek(tt.in, tt.whence)
if off != tt.out || err != nil {
if e, ok := err.(*PathError); ok && e.Err == syscall.EINVAL && tt.out > 1<<32 && runtime.GOOS == "linux" {
- mounts, _ := ioutil.ReadFile("/proc/mounts")
+ mounts, _ := os.ReadFile("/proc/mounts")
if strings.Contains(string(mounts), "reiserfs") {
// Reiserfs rejects the big seeks.
t.Skipf("skipping test known to fail on reiserfs; https://golang.org/issue/91")
@@ -1858,7 +1858,7 @@ func TestWriteAt(t *testing.T) {
t.Fatalf("WriteAt 7: %d, %v", n, err)
}
- b, err := ioutil.ReadFile(f.Name())
+ b, err := os.ReadFile(f.Name())
if err != nil {
t.Fatalf("ReadFile %s: %v", f.Name(), err)
}
@@ -1906,7 +1906,7 @@ func writeFile(t *testing.T, fname string, flag int, text string) string {
t.Fatalf("WriteString: %d, %v", n, err)
}
f.Close()
- data, err := ioutil.ReadFile(fname)
+ data, err := os.ReadFile(fname)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
@@ -1948,7 +1948,7 @@ func TestAppend(t *testing.T) {
func TestStatDirWithTrailingSlash(t *testing.T) {
// Create new temporary directory and arrange to clean it up.
- path, err := ioutil.TempDir("", "_TestStatDirWithSlash_")
+ path, err := os.MkdirTemp("", "_TestStatDirWithSlash_")
if err != nil {
t.Fatalf("TempDir: %s", err)
}
@@ -2090,7 +2090,7 @@ func TestLargeWriteToConsole(t *testing.T) {
func TestStatDirModeExec(t *testing.T) {
const mode = 0111
- path, err := ioutil.TempDir("", "go-build")
+ path, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
@@ -2159,7 +2159,7 @@ func TestStatStdin(t *testing.T) {
func TestStatRelativeSymlink(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpdir, err := ioutil.TempDir("", "TestStatRelativeSymlink")
+ tmpdir, err := os.MkdirTemp("", "TestStatRelativeSymlink")
if err != nil {
t.Fatal(err)
}
@@ -2249,8 +2249,8 @@ func TestLongPath(t *testing.T) {
t.Fatalf("MkdirAll failed: %v", err)
}
data := []byte("hello world\n")
- if err := ioutil.WriteFile(sizedTempDir+"/foo.txt", data, 0644); err != nil {
- t.Fatalf("ioutil.WriteFile() failed: %v", err)
+ if err := os.WriteFile(sizedTempDir+"/foo.txt", data, 0644); err != nil {
+ t.Fatalf("os.WriteFile() failed: %v", err)
}
if err := Rename(sizedTempDir+"/foo.txt", sizedTempDir+"/bar.txt"); err != nil {
t.Fatalf("Rename failed: %v", err)
@@ -2434,7 +2434,7 @@ func TestRemoveAllRace(t *testing.T) {
n := runtime.GOMAXPROCS(16)
defer runtime.GOMAXPROCS(n)
- root, err := ioutil.TempDir("", "issue")
+ root, err := os.MkdirTemp("", "issue")
if err != nil {
t.Fatal(err)
}
diff --git a/src/os/os_unix_test.go b/src/os/os_unix_test.go
index 0bce2989c4..51693fd82a 100644
--- a/src/os/os_unix_test.go
+++ b/src/os/os_unix_test.go
@@ -8,7 +8,7 @@ package os_test
import (
"io"
- "io/ioutil"
+ "os"
. "os"
"path/filepath"
"runtime"
@@ -190,7 +190,7 @@ func TestReaddirRemoveRace(t *testing.T) {
}
dir := newDir("TestReaddirRemoveRace", t)
defer RemoveAll(dir)
- if err := ioutil.WriteFile(filepath.Join(dir, "some-file"), []byte("hello"), 0644); err != nil {
+ if err := os.WriteFile(filepath.Join(dir, "some-file"), []byte("hello"), 0644); err != nil {
t.Fatal(err)
}
d, err := Open(dir)
diff --git a/src/os/os_windows_test.go b/src/os/os_windows_test.go
index e002774844..8d1d1f61b2 100644
--- a/src/os/os_windows_test.go
+++ b/src/os/os_windows_test.go
@@ -13,7 +13,6 @@ import (
"internal/testenv"
"io"
"io/fs"
- "io/ioutil"
"os"
osexec "os/exec"
"path/filepath"
@@ -31,7 +30,7 @@ import (
type syscallDescriptor = syscall.Handle
func TestSameWindowsFile(t *testing.T) {
- temp, err := ioutil.TempDir("", "TestSameWindowsFile")
+ temp, err := os.MkdirTemp("", "TestSameWindowsFile")
if err != nil {
t.Fatal(err)
}
@@ -90,7 +89,7 @@ type dirLinkTest struct {
}
func testDirLinks(t *testing.T, tests []dirLinkTest) {
- tmpdir, err := ioutil.TempDir("", "testDirLinks")
+ tmpdir, err := os.MkdirTemp("", "testDirLinks")
if err != nil {
t.Fatal(err)
}
@@ -115,7 +114,7 @@ func testDirLinks(t *testing.T, tests []dirLinkTest) {
if err != nil {
t.Fatal(err)
}
- err = ioutil.WriteFile(filepath.Join(dir, "abc"), []byte("abc"), 0644)
+ err = os.WriteFile(filepath.Join(dir, "abc"), []byte("abc"), 0644)
if err != nil {
t.Fatal(err)
}
@@ -127,7 +126,7 @@ func testDirLinks(t *testing.T, tests []dirLinkTest) {
continue
}
- data, err := ioutil.ReadFile(filepath.Join(link, "abc"))
+ data, err := os.ReadFile(filepath.Join(link, "abc"))
if err != nil {
t.Errorf("failed to read abc file: %v", err)
continue
@@ -439,7 +438,7 @@ func TestNetworkSymbolicLink(t *testing.T) {
const _NERR_ServerNotStarted = syscall.Errno(2114)
- dir, err := ioutil.TempDir("", "TestNetworkSymbolicLink")
+ dir, err := os.MkdirTemp("", "TestNetworkSymbolicLink")
if err != nil {
t.Fatal(err)
}
@@ -600,7 +599,7 @@ func TestStatDir(t *testing.T) {
}
func TestOpenVolumeName(t *testing.T) {
- tmpdir, err := ioutil.TempDir("", "TestOpenVolumeName")
+ tmpdir, err := os.MkdirTemp("", "TestOpenVolumeName")
if err != nil {
t.Fatal(err)
}
@@ -619,7 +618,7 @@ func TestOpenVolumeName(t *testing.T) {
want := []string{"file1", "file2", "file3", "gopher.txt"}
sort.Strings(want)
for _, name := range want {
- err := ioutil.WriteFile(filepath.Join(tmpdir, name), nil, 0777)
+ err := os.WriteFile(filepath.Join(tmpdir, name), nil, 0777)
if err != nil {
t.Fatal(err)
}
@@ -643,7 +642,7 @@ func TestOpenVolumeName(t *testing.T) {
}
func TestDeleteReadOnly(t *testing.T) {
- tmpdir, err := ioutil.TempDir("", "TestDeleteReadOnly")
+ tmpdir, err := os.MkdirTemp("", "TestDeleteReadOnly")
if err != nil {
t.Fatal(err)
}
@@ -804,7 +803,7 @@ func compareCommandLineToArgvWithSyscall(t *testing.T, cmd string) {
}
func TestCmdArgs(t *testing.T) {
- tmpdir, err := ioutil.TempDir("", "TestCmdArgs")
+ tmpdir, err := os.MkdirTemp("", "TestCmdArgs")
if err != nil {
t.Fatal(err)
}
@@ -823,7 +822,7 @@ func main() {
}
`
src := filepath.Join(tmpdir, "main.go")
- err = ioutil.WriteFile(src, []byte(prog), 0666)
+ err = os.WriteFile(src, []byte(prog), 0666)
if err != nil {
t.Fatal(err)
}
@@ -971,14 +970,14 @@ func TestSymlinkCreation(t *testing.T) {
}
t.Parallel()
- temp, err := ioutil.TempDir("", "TestSymlinkCreation")
+ temp, err := os.MkdirTemp("", "TestSymlinkCreation")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(temp)
dummyFile := filepath.Join(temp, "file")
- err = ioutil.WriteFile(dummyFile, []byte(""), 0644)
+ err = os.WriteFile(dummyFile, []byte(""), 0644)
if err != nil {
t.Fatal(err)
}
@@ -1207,7 +1206,7 @@ func mklinkd(t *testing.T, link, target string) {
}
func TestWindowsReadlink(t *testing.T) {
- tmpdir, err := ioutil.TempDir("", "TestWindowsReadlink")
+ tmpdir, err := os.MkdirTemp("", "TestWindowsReadlink")
if err != nil {
t.Fatal(err)
}
@@ -1272,7 +1271,7 @@ func TestWindowsReadlink(t *testing.T) {
testReadlink(t, "reldirlink", "dir")
file := filepath.Join(tmpdir, "file")
- err = ioutil.WriteFile(file, []byte(""), 0666)
+ err = os.WriteFile(file, []byte(""), 0666)
if err != nil {
t.Fatal(err)
}
diff --git a/src/os/path_test.go b/src/os/path_test.go
index 3fe9c5ffa3..b79d958711 100644
--- a/src/os/path_test.go
+++ b/src/os/path_test.go
@@ -6,7 +6,7 @@ package os_test
import (
"internal/testenv"
- "io/ioutil"
+ "os"
. "os"
"path/filepath"
"runtime"
@@ -78,7 +78,7 @@ func TestMkdirAll(t *testing.T) {
func TestMkdirAllWithSymlink(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpDir, err := ioutil.TempDir("", "TestMkdirAllWithSymlink-")
+ tmpDir, err := os.MkdirTemp("", "TestMkdirAllWithSymlink-")
if err != nil {
t.Fatal(err)
}
diff --git a/src/os/path_windows_test.go b/src/os/path_windows_test.go
index 862b404362..869db8fd6c 100644
--- a/src/os/path_windows_test.go
+++ b/src/os/path_windows_test.go
@@ -5,7 +5,6 @@
package os_test
import (
- "io/ioutil"
"os"
"strings"
"syscall"
@@ -48,7 +47,7 @@ func TestFixLongPath(t *testing.T) {
}
func TestMkdirAllExtendedLength(t *testing.T) {
- tmpDir, err := ioutil.TempDir("", "TestMkdirAllExtendedLength")
+ tmpDir, err := os.MkdirTemp("", "TestMkdirAllExtendedLength")
if err != nil {
t.Fatal(err)
}
diff --git a/src/os/pipe_test.go b/src/os/pipe_test.go
index 0593efec75..b98e53845c 100644
--- a/src/os/pipe_test.go
+++ b/src/os/pipe_test.go
@@ -14,7 +14,6 @@ import (
"internal/testenv"
"io"
"io/fs"
- "io/ioutil"
"os"
osexec "os/exec"
"os/signal"
@@ -161,7 +160,7 @@ func testClosedPipeRace(t *testing.T, read bool) {
// Get the amount we have to write to overload a pipe
// with no reader.
limit = 131073
- if b, err := ioutil.ReadFile("/proc/sys/fs/pipe-max-size"); err == nil {
+ if b, err := os.ReadFile("/proc/sys/fs/pipe-max-size"); err == nil {
if i, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil {
limit = i + 1
}
diff --git a/src/os/readfrom_linux_test.go b/src/os/readfrom_linux_test.go
index 00faf39fe5..37047175e6 100644
--- a/src/os/readfrom_linux_test.go
+++ b/src/os/readfrom_linux_test.go
@@ -8,8 +8,8 @@ import (
"bytes"
"internal/poll"
"io"
- "io/ioutil"
"math/rand"
+ "os"
. "os"
"path/filepath"
"strconv"
@@ -173,7 +173,7 @@ func TestCopyFileRange(t *testing.T) {
})
t.Run("Nil", func(t *testing.T) {
var nilFile *File
- anyFile, err := ioutil.TempFile("", "")
+ anyFile, err := os.CreateTemp("", "")
if err != nil {
t.Fatal(err)
}
diff --git a/src/os/removeall_test.go b/src/os/removeall_test.go
index 90efa313ea..3a2f6e3759 100644
--- a/src/os/removeall_test.go
+++ b/src/os/removeall_test.go
@@ -6,7 +6,7 @@ package os_test
import (
"fmt"
- "io/ioutil"
+ "os"
. "os"
"path/filepath"
"runtime"
@@ -15,7 +15,7 @@ import (
)
func TestRemoveAll(t *testing.T) {
- tmpDir, err := ioutil.TempDir("", "TestRemoveAll-")
+ tmpDir, err := os.MkdirTemp("", "TestRemoveAll-")
if err != nil {
t.Fatal(err)
}
@@ -128,7 +128,7 @@ func TestRemoveAllLarge(t *testing.T) {
t.Skip("skipping in short mode")
}
- tmpDir, err := ioutil.TempDir("", "TestRemoveAll-")
+ tmpDir, err := os.MkdirTemp("", "TestRemoveAll-")
if err != nil {
t.Fatal(err)
}
@@ -169,7 +169,7 @@ func TestRemoveAllLongPath(t *testing.T) {
t.Fatalf("Could not get wd: %s", err)
}
- startPath, err := ioutil.TempDir("", "TestRemoveAllLongPath-")
+ startPath, err := os.MkdirTemp("", "TestRemoveAllLongPath-")
if err != nil {
t.Fatalf("Could not create TempDir: %s", err)
}
@@ -211,7 +211,7 @@ func TestRemoveAllDot(t *testing.T) {
if err != nil {
t.Fatalf("Could not get wd: %s", err)
}
- tempDir, err := ioutil.TempDir("", "TestRemoveAllDot-")
+ tempDir, err := os.MkdirTemp("", "TestRemoveAllDot-")
if err != nil {
t.Fatalf("Could not create TempDir: %s", err)
}
@@ -236,7 +236,7 @@ func TestRemoveAllDot(t *testing.T) {
func TestRemoveAllDotDot(t *testing.T) {
t.Parallel()
- tempDir, err := ioutil.TempDir("", "TestRemoveAllDotDot-")
+ tempDir, err := os.MkdirTemp("", "TestRemoveAllDotDot-")
if err != nil {
t.Fatal(err)
}
@@ -261,7 +261,7 @@ func TestRemoveAllDotDot(t *testing.T) {
func TestRemoveReadOnlyDir(t *testing.T) {
t.Parallel()
- tempDir, err := ioutil.TempDir("", "TestRemoveReadOnlyDir-")
+ tempDir, err := os.MkdirTemp("", "TestRemoveReadOnlyDir-")
if err != nil {
t.Fatal(err)
}
@@ -298,7 +298,7 @@ func TestRemoveAllButReadOnlyAndPathError(t *testing.T) {
t.Parallel()
- tempDir, err := ioutil.TempDir("", "TestRemoveAllButReadOnly-")
+ tempDir, err := os.MkdirTemp("", "TestRemoveAllButReadOnly-")
if err != nil {
t.Fatal(err)
}
@@ -389,7 +389,7 @@ func TestRemoveUnreadableDir(t *testing.T) {
t.Parallel()
- tempDir, err := ioutil.TempDir("", "TestRemoveAllButReadOnly-")
+ tempDir, err := os.MkdirTemp("", "TestRemoveAllButReadOnly-")
if err != nil {
t.Fatal(err)
}
@@ -413,7 +413,7 @@ func TestRemoveAllWithMoreErrorThanReqSize(t *testing.T) {
t.Skip("skipping in short mode")
}
- tmpDir, err := ioutil.TempDir("", "TestRemoveAll-")
+ tmpDir, err := os.MkdirTemp("", "TestRemoveAll-")
if err != nil {
t.Fatal(err)
}
diff --git a/src/os/signal/signal_test.go b/src/os/signal/signal_test.go
index 23e33fe82b..8945cbfccb 100644
--- a/src/os/signal/signal_test.go
+++ b/src/os/signal/signal_test.go
@@ -12,7 +12,6 @@ import (
"flag"
"fmt"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"runtime"
@@ -304,7 +303,7 @@ func TestDetectNohup(t *testing.T) {
os.Remove("nohup.out")
out, err := exec.Command("/usr/bin/nohup", os.Args[0], "-test.run=TestDetectNohup", "-check_sighup_ignored").CombinedOutput()
- data, _ := ioutil.ReadFile("nohup.out")
+ data, _ := os.ReadFile("nohup.out")
os.Remove("nohup.out")
if err != nil {
t.Errorf("ran test with -check_sighup_ignored under nohup and it failed: expected success.\nError: %v\nOutput:\n%s%s", err, out, data)
diff --git a/src/os/signal/signal_windows_test.go b/src/os/signal/signal_windows_test.go
index c2b59010fc..4640428587 100644
--- a/src/os/signal/signal_windows_test.go
+++ b/src/os/signal/signal_windows_test.go
@@ -7,7 +7,6 @@ package signal
import (
"bytes"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -57,7 +56,7 @@ func main() {
}
}
`
- tmp, err := ioutil.TempDir("", "TestCtrlBreak")
+ tmp, err := os.MkdirTemp("", "TestCtrlBreak")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
diff --git a/src/os/stat_test.go b/src/os/stat_test.go
index 88b789080e..c409f0ff18 100644
--- a/src/os/stat_test.go
+++ b/src/os/stat_test.go
@@ -7,7 +7,6 @@ package os_test
import (
"internal/testenv"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -186,7 +185,7 @@ func testSymlinkSameFile(t *testing.T, path, link string) {
func TestDirAndSymlinkStats(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpdir, err := ioutil.TempDir("", "TestDirAndSymlinkStats")
+ tmpdir, err := os.MkdirTemp("", "TestDirAndSymlinkStats")
if err != nil {
t.Fatal(err)
}
@@ -219,14 +218,14 @@ func TestDirAndSymlinkStats(t *testing.T) {
func TestFileAndSymlinkStats(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpdir, err := ioutil.TempDir("", "TestFileAndSymlinkStats")
+ tmpdir, err := os.MkdirTemp("", "TestFileAndSymlinkStats")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
file := filepath.Join(tmpdir, "file")
- err = ioutil.WriteFile(file, []byte(""), 0644)
+ err = os.WriteFile(file, []byte(""), 0644)
if err != nil {
t.Fatal(err)
}
@@ -253,7 +252,7 @@ func TestFileAndSymlinkStats(t *testing.T) {
func TestSymlinkWithTrailingSlash(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpdir, err := ioutil.TempDir("", "TestSymlinkWithTrailingSlash")
+ tmpdir, err := os.MkdirTemp("", "TestSymlinkWithTrailingSlash")
if err != nil {
t.Fatal(err)
}
diff --git a/src/os/timeout_test.go b/src/os/timeout_test.go
index d848e41642..0a39f46333 100644
--- a/src/os/timeout_test.go
+++ b/src/os/timeout_test.go
@@ -11,7 +11,6 @@ package os_test
import (
"fmt"
"io"
- "io/ioutil"
"math/rand"
"os"
"os/signal"
@@ -29,7 +28,7 @@ func TestNonpollableDeadline(t *testing.T) {
t.Skipf("skipping on %s", runtime.GOOS)
}
- f, err := ioutil.TempFile("", "ostest")
+ f, err := os.CreateTemp("", "ostest")
if err != nil {
t.Fatal(err)
}
diff --git a/src/os/user/lookup_plan9.go b/src/os/user/lookup_plan9.go
index ea3ce0bc7c..33ae3a6adf 100644
--- a/src/os/user/lookup_plan9.go
+++ b/src/os/user/lookup_plan9.go
@@ -6,7 +6,6 @@ package user
import (
"fmt"
- "io/ioutil"
"os"
"syscall"
)
@@ -23,7 +22,7 @@ func init() {
}
func current() (*User, error) {
- ubytes, err := ioutil.ReadFile(userFile)
+ ubytes, err := os.ReadFile(userFile)
if err != nil {
return nil, fmt.Errorf("user: %s", err)
}
diff --git a/src/path/filepath/example_unix_walk_test.go b/src/path/filepath/example_unix_walk_test.go
index 66dc7f6b53..c8a818fd6e 100644
--- a/src/path/filepath/example_unix_walk_test.go
+++ b/src/path/filepath/example_unix_walk_test.go
@@ -9,13 +9,12 @@ package filepath_test
import (
"fmt"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
)
func prepareTestDirTree(tree string) (string, error) {
- tmpDir, err := ioutil.TempDir("", "")
+ tmpDir, err := os.MkdirTemp("", "")
if err != nil {
return "", fmt.Errorf("error creating temp directory: %v\n", err)
}
diff --git a/src/path/filepath/match_test.go b/src/path/filepath/match_test.go
index 1c3b567fa3..48880ea439 100644
--- a/src/path/filepath/match_test.go
+++ b/src/path/filepath/match_test.go
@@ -7,7 +7,6 @@ package filepath_test
import (
"fmt"
"internal/testenv"
- "io/ioutil"
"os"
. "path/filepath"
"reflect"
@@ -182,7 +181,7 @@ var globSymlinkTests = []struct {
func TestGlobSymlink(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpDir, err := ioutil.TempDir("", "globsymlink")
+ tmpDir, err := os.MkdirTemp("", "globsymlink")
if err != nil {
t.Fatal("creating temp dir:", err)
}
@@ -268,7 +267,7 @@ func TestWindowsGlob(t *testing.T) {
t.Skipf("skipping windows specific test")
}
- tmpDir, err := ioutil.TempDir("", "TestWindowsGlob")
+ tmpDir, err := os.MkdirTemp("", "TestWindowsGlob")
if err != nil {
t.Fatal(err)
}
@@ -302,7 +301,7 @@ func TestWindowsGlob(t *testing.T) {
}
}
for _, file := range files {
- err := ioutil.WriteFile(Join(tmpDir, file), nil, 0666)
+ err := os.WriteFile(Join(tmpDir, file), nil, 0666)
if err != nil {
t.Fatal(err)
}
diff --git a/src/path/filepath/path_test.go b/src/path/filepath/path_test.go
index d760530e26..8616256ac0 100644
--- a/src/path/filepath/path_test.go
+++ b/src/path/filepath/path_test.go
@@ -9,7 +9,6 @@ import (
"fmt"
"internal/testenv"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"reflect"
@@ -416,7 +415,7 @@ func chtmpdir(t *testing.T) (restore func()) {
if err != nil {
t.Fatalf("chtmpdir: %v", err)
}
- d, err := ioutil.TempDir("", "test")
+ d, err := os.MkdirTemp("", "test")
if err != nil {
t.Fatalf("chtmpdir: %v", err)
}
@@ -459,7 +458,7 @@ func testWalk(t *testing.T, walk func(string, fs.WalkDirFunc) error, errVisit in
defer restore()
}
- tmpDir, err := ioutil.TempDir("", "TestWalk")
+ tmpDir, err := os.MkdirTemp("", "TestWalk")
if err != nil {
t.Fatal("creating temp dir:", err)
}
@@ -563,7 +562,7 @@ func touch(t *testing.T, name string) {
}
func TestWalkSkipDirOnFile(t *testing.T) {
- td, err := ioutil.TempDir("", "walktest")
+ td, err := os.MkdirTemp("", "walktest")
if err != nil {
t.Fatal(err)
}
@@ -613,7 +612,7 @@ func TestWalkSkipDirOnFile(t *testing.T) {
}
func TestWalkFileError(t *testing.T) {
- td, err := ioutil.TempDir("", "walktest")
+ td, err := os.MkdirTemp("", "walktest")
if err != nil {
t.Fatal(err)
}
@@ -892,7 +891,7 @@ func testEvalSymlinksAfterChdir(t *testing.T, wd, path, want string) {
func TestEvalSymlinks(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpDir, err := ioutil.TempDir("", "evalsymlink")
+ tmpDir, err := os.MkdirTemp("", "evalsymlink")
if err != nil {
t.Fatal("creating temp dir:", err)
}
@@ -978,7 +977,7 @@ func TestEvalSymlinksIsNotExist(t *testing.T) {
func TestIssue13582(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpDir, err := ioutil.TempDir("", "issue13582")
+ tmpDir, err := os.MkdirTemp("", "issue13582")
if err != nil {
t.Fatal(err)
}
@@ -995,7 +994,7 @@ func TestIssue13582(t *testing.T) {
t.Fatal(err)
}
file := filepath.Join(linkToDir, "file")
- err = ioutil.WriteFile(file, nil, 0644)
+ err = os.WriteFile(file, nil, 0644)
if err != nil {
t.Fatal(err)
}
@@ -1065,7 +1064,7 @@ var absTests = []string{
}
func TestAbs(t *testing.T) {
- root, err := ioutil.TempDir("", "TestAbs")
+ root, err := os.MkdirTemp("", "TestAbs")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
@@ -1136,7 +1135,7 @@ func TestAbs(t *testing.T) {
// We test it separately from all other absTests because the empty string is not
// a valid path, so it can't be used with os.Stat.
func TestAbsEmptyString(t *testing.T) {
- root, err := ioutil.TempDir("", "TestAbsEmptyString")
+ root, err := os.MkdirTemp("", "TestAbsEmptyString")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
@@ -1357,7 +1356,7 @@ func TestBug3486(t *testing.T) { // https://golang.org/issue/3486
}
func testWalkSymlink(t *testing.T, mklink func(target, link string) error) {
- tmpdir, err := ioutil.TempDir("", "testWalkSymlink")
+ tmpdir, err := os.MkdirTemp("", "testWalkSymlink")
if err != nil {
t.Fatal(err)
}
@@ -1407,14 +1406,14 @@ func TestWalkSymlink(t *testing.T) {
}
func TestIssue29372(t *testing.T) {
- tmpDir, err := ioutil.TempDir("", "TestIssue29372")
+ tmpDir, err := os.MkdirTemp("", "TestIssue29372")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
path := filepath.Join(tmpDir, "file.txt")
- err = ioutil.WriteFile(path, nil, 0644)
+ err = os.WriteFile(path, nil, 0644)
if err != nil {
t.Fatal(err)
}
@@ -1443,7 +1442,7 @@ func TestEvalSymlinksAboveRoot(t *testing.T) {
t.Parallel()
- tmpDir, err := ioutil.TempDir("", "TestEvalSymlinksAboveRoot")
+ tmpDir, err := os.MkdirTemp("", "TestEvalSymlinksAboveRoot")
if err != nil {
t.Fatal(err)
}
@@ -1460,7 +1459,7 @@ func TestEvalSymlinksAboveRoot(t *testing.T) {
if err := os.Symlink(filepath.Join(evalTmpDir, "a"), filepath.Join(evalTmpDir, "b")); err != nil {
t.Fatal(err)
}
- if err := ioutil.WriteFile(filepath.Join(evalTmpDir, "a", "file"), nil, 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(evalTmpDir, "a", "file"), nil, 0666); err != nil {
t.Fatal(err)
}
@@ -1491,7 +1490,7 @@ func TestEvalSymlinksAboveRoot(t *testing.T) {
func TestEvalSymlinksAboveRootChdir(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpDir, err := ioutil.TempDir("", "TestEvalSymlinksAboveRootChdir")
+ tmpDir, err := os.MkdirTemp("", "TestEvalSymlinksAboveRootChdir")
if err != nil {
t.Fatal(err)
}
@@ -1514,7 +1513,7 @@ func TestEvalSymlinksAboveRootChdir(t *testing.T) {
if err := os.Symlink(subdir, "c"); err != nil {
t.Fatal(err)
}
- if err := ioutil.WriteFile(filepath.Join(subdir, "file"), nil, 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(subdir, "file"), nil, 0666); err != nil {
t.Fatal(err)
}
diff --git a/src/path/filepath/path_windows_test.go b/src/path/filepath/path_windows_test.go
index 9309a7dc4d..1c3d84c62d 100644
--- a/src/path/filepath/path_windows_test.go
+++ b/src/path/filepath/path_windows_test.go
@@ -9,7 +9,6 @@ import (
"fmt"
"internal/testenv"
"io/fs"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -38,7 +37,7 @@ func testWinSplitListTestIsValid(t *testing.T, ti int, tt SplitListTest,
perm fs.FileMode = 0700
)
- tmp, err := ioutil.TempDir("", "testWinSplitListTestIsValid")
+ tmp, err := os.MkdirTemp("", "testWinSplitListTestIsValid")
if err != nil {
t.Fatalf("TempDir failed: %v", err)
}
@@ -63,7 +62,7 @@ func testWinSplitListTestIsValid(t *testing.T, ti int, tt SplitListTest,
return
}
fn, data := filepath.Join(dd, cmdfile), []byte("@echo "+d+"\r\n")
- if err = ioutil.WriteFile(fn, data, perm); err != nil {
+ if err = os.WriteFile(fn, data, perm); err != nil {
t.Errorf("%d,%d: WriteFile(%#q) failed: %v", ti, i, fn, err)
return
}
@@ -104,7 +103,7 @@ func testWinSplitListTestIsValid(t *testing.T, ti int, tt SplitListTest,
func TestWindowsEvalSymlinks(t *testing.T) {
testenv.MustHaveSymlink(t)
- tmpDir, err := ioutil.TempDir("", "TestWindowsEvalSymlinks")
+ tmpDir, err := os.MkdirTemp("", "TestWindowsEvalSymlinks")
if err != nil {
t.Fatal(err)
}
@@ -162,13 +161,13 @@ func TestWindowsEvalSymlinks(t *testing.T) {
// TestEvalSymlinksCanonicalNames verify that EvalSymlinks
// returns "canonical" path names on windows.
func TestEvalSymlinksCanonicalNames(t *testing.T) {
- tmp, err := ioutil.TempDir("", "evalsymlinkcanonical")
+ tmp, err := os.MkdirTemp("", "evalsymlinkcanonical")
if err != nil {
t.Fatal("creating temp dir:", err)
}
defer os.RemoveAll(tmp)
- // ioutil.TempDir might return "non-canonical" name.
+ // os.MkdirTemp might return "non-canonical" name.
cTmpName, err := filepath.EvalSymlinks(tmp)
if err != nil {
t.Errorf("EvalSymlinks(%q) error: %v", tmp, err)
@@ -418,7 +417,7 @@ func TestToNorm(t *testing.T) {
{".", `\\localhost\c$`, `\\localhost\c$`},
}
- tmp, err := ioutil.TempDir("", "testToNorm")
+ tmp, err := os.MkdirTemp("", "testToNorm")
if err != nil {
t.Fatal(err)
}
@@ -429,7 +428,7 @@ func TestToNorm(t *testing.T) {
}
}()
- // ioutil.TempDir might return "non-canonical" name.
+ // os.MkdirTemp might return "non-canonical" name.
ctmp, err := filepath.EvalSymlinks(tmp)
if err != nil {
t.Fatal(err)
@@ -527,7 +526,7 @@ func TestNTNamespaceSymlink(t *testing.T) {
t.Skip("skipping test because mklink command does not support junctions")
}
- tmpdir, err := ioutil.TempDir("", "TestNTNamespaceSymlink")
+ tmpdir, err := os.MkdirTemp("", "TestNTNamespaceSymlink")
if err != nil {
t.Fatal(err)
}
@@ -564,7 +563,7 @@ func TestNTNamespaceSymlink(t *testing.T) {
testenv.MustHaveSymlink(t)
file := filepath.Join(tmpdir, "file")
- err = ioutil.WriteFile(file, []byte(""), 0666)
+ err = os.WriteFile(file, []byte(""), 0666)
if err != nil {
t.Fatal(err)
}
diff --git a/src/runtime/crash_test.go b/src/runtime/crash_test.go
index 5e22b7593e..58ad4f3eba 100644
--- a/src/runtime/crash_test.go
+++ b/src/runtime/crash_test.go
@@ -9,7 +9,6 @@ import (
"flag"
"fmt"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -117,7 +116,7 @@ func buildTestProg(t *testing.T, binary string, flags ...string) (string, error)
testprog.Lock()
defer testprog.Unlock()
if testprog.dir == "" {
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
diff --git a/src/runtime/crash_unix_test.go b/src/runtime/crash_unix_test.go
index ebbdbfe5b9..803b031873 100644
--- a/src/runtime/crash_unix_test.go
+++ b/src/runtime/crash_unix_test.go
@@ -10,7 +10,6 @@ import (
"bytes"
"internal/testenv"
"io"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -85,13 +84,13 @@ func TestCrashDumpsAllThreads(t *testing.T) {
t.Parallel()
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
- if err := ioutil.WriteFile(filepath.Join(dir, "main.go"), []byte(crashDumpsAllThreadsSource), 0666); err != nil {
+ if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(crashDumpsAllThreadsSource), 0666); err != nil {
t.Fatalf("failed to create Go file: %v", err)
}
diff --git a/src/runtime/debug/heapdump_test.go b/src/runtime/debug/heapdump_test.go
index de1ec27d21..768934d05d 100644
--- a/src/runtime/debug/heapdump_test.go
+++ b/src/runtime/debug/heapdump_test.go
@@ -5,7 +5,6 @@
package debug_test
import (
- "io/ioutil"
"os"
"runtime"
. "runtime/debug"
@@ -16,7 +15,7 @@ func TestWriteHeapDumpNonempty(t *testing.T) {
if runtime.GOOS == "js" {
t.Skipf("WriteHeapDump is not available on %s.", runtime.GOOS)
}
- f, err := ioutil.TempFile("", "heapdumptest")
+ f, err := os.CreateTemp("", "heapdumptest")
if err != nil {
t.Fatalf("TempFile failed: %v", err)
}
@@ -45,7 +44,7 @@ func TestWriteHeapDumpFinalizers(t *testing.T) {
if runtime.GOOS == "js" {
t.Skipf("WriteHeapDump is not available on %s.", runtime.GOOS)
}
- f, err := ioutil.TempFile("", "heapdumptest")
+ f, err := os.CreateTemp("", "heapdumptest")
if err != nil {
t.Fatalf("TempFile failed: %v", err)
}
diff --git a/src/runtime/debug_test.go b/src/runtime/debug_test.go
index 722e81121f..a0b3f84382 100644
--- a/src/runtime/debug_test.go
+++ b/src/runtime/debug_test.go
@@ -17,7 +17,7 @@ package runtime_test
import (
"fmt"
- "io/ioutil"
+ "os"
"regexp"
"runtime"
"runtime/debug"
@@ -95,7 +95,7 @@ func debugCallTKill(tid int) error {
// Linux-specific.
func skipUnderDebugger(t *testing.T) {
pid := syscall.Getpid()
- status, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/status", pid))
+ status, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid))
if err != nil {
t.Logf("couldn't get proc tracer: %s", err)
return
diff --git a/src/runtime/env_plan9.go b/src/runtime/env_plan9.go
index b7ea863735..f1ac4760a7 100644
--- a/src/runtime/env_plan9.go
+++ b/src/runtime/env_plan9.go
@@ -23,8 +23,8 @@ const (
// to the (possibly shared) Plan 9 environment, so that Setenv and Getenv
// conform to the same Posix semantics as on other operating systems.
// For Plan 9 shared environment semantics, instead of Getenv(key) and
-// Setenv(key, value), one can use ioutil.ReadFile("/env/" + key) and
-// ioutil.WriteFile("/env/" + key, value, 0666) respectively.
+// Setenv(key, value), one can use os.ReadFile("/env/" + key) and
+// os.WriteFile("/env/" + key, value, 0666) respectively.
//go:nosplit
func goenvs() {
buf := make([]byte, envBufSize)
diff --git a/src/runtime/internal/sys/gengoos.go b/src/runtime/internal/sys/gengoos.go
index 2a4bf0c3b4..9bbc48d94f 100644
--- a/src/runtime/internal/sys/gengoos.go
+++ b/src/runtime/internal/sys/gengoos.go
@@ -9,8 +9,8 @@ package main
import (
"bytes"
"fmt"
- "io/ioutil"
"log"
+ "os"
"strconv"
"strings"
)
@@ -18,7 +18,7 @@ import (
var gooses, goarches []string
func main() {
- data, err := ioutil.ReadFile("../../../go/build/syslist.go")
+ data, err := os.ReadFile("../../../go/build/syslist.go")
if err != nil {
log.Fatal(err)
}
@@ -68,7 +68,7 @@ func main() {
}
fmt.Fprintf(&buf, "const Goos%s = %d\n", strings.Title(goos), value)
}
- err := ioutil.WriteFile("zgoos_"+target+".go", buf.Bytes(), 0666)
+ err := os.WriteFile("zgoos_"+target+".go", buf.Bytes(), 0666)
if err != nil {
log.Fatal(err)
}
@@ -90,7 +90,7 @@ func main() {
}
fmt.Fprintf(&buf, "const Goarch%s = %d\n", strings.Title(goarch), value)
}
- err := ioutil.WriteFile("zgoarch_"+target+".go", buf.Bytes(), 0666)
+ err := os.WriteFile("zgoarch_"+target+".go", buf.Bytes(), 0666)
if err != nil {
log.Fatal(err)
}
diff --git a/src/runtime/memmove_linux_amd64_test.go b/src/runtime/memmove_linux_amd64_test.go
index d0e8b42a5a..b3ccd907b9 100644
--- a/src/runtime/memmove_linux_amd64_test.go
+++ b/src/runtime/memmove_linux_amd64_test.go
@@ -5,7 +5,6 @@
package runtime_test
import (
- "io/ioutil"
"os"
"reflect"
"syscall"
@@ -18,7 +17,7 @@ import (
func TestMemmoveOverflow(t *testing.T) {
t.Parallel()
// Create a temporary file.
- tmp, err := ioutil.TempFile("", "go-memmovetest")
+ tmp, err := os.CreateTemp("", "go-memmovetest")
if err != nil {
t.Fatal(err)
}
diff --git a/src/runtime/mkduff.go b/src/runtime/mkduff.go
index 6ddf0256e9..94ae75fbfe 100644
--- a/src/runtime/mkduff.go
+++ b/src/runtime/mkduff.go
@@ -27,8 +27,8 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
"log"
+ "os"
)
func main() {
@@ -54,7 +54,7 @@ func gen(arch string, tags, zero, copy func(io.Writer)) {
fmt.Fprintln(&buf)
copy(&buf)
- if err := ioutil.WriteFile("duff_"+arch+".s", buf.Bytes(), 0644); err != nil {
+ if err := os.WriteFile("duff_"+arch+".s", buf.Bytes(), 0644); err != nil {
log.Fatalln(err)
}
}
diff --git a/src/runtime/mkfastlog2table.go b/src/runtime/mkfastlog2table.go
index 305c84a7c1..d650292394 100644
--- a/src/runtime/mkfastlog2table.go
+++ b/src/runtime/mkfastlog2table.go
@@ -12,9 +12,9 @@ package main
import (
"bytes"
"fmt"
- "io/ioutil"
"log"
"math"
+ "os"
)
func main() {
@@ -36,7 +36,7 @@ func main() {
}
fmt.Fprintln(&buf, "}")
- if err := ioutil.WriteFile("fastlog2table.go", buf.Bytes(), 0644); err != nil {
+ if err := os.WriteFile("fastlog2table.go", buf.Bytes(), 0644); err != nil {
log.Fatalln(err)
}
}
diff --git a/src/runtime/mksizeclasses.go b/src/runtime/mksizeclasses.go
index 1a210953a4..b92d1fed5f 100644
--- a/src/runtime/mksizeclasses.go
+++ b/src/runtime/mksizeclasses.go
@@ -35,7 +35,6 @@ import (
"fmt"
"go/format"
"io"
- "io/ioutil"
"log"
"os"
)
@@ -65,7 +64,7 @@ func main() {
if *stdout {
_, err = os.Stdout.Write(out)
} else {
- err = ioutil.WriteFile("sizeclasses.go", out, 0666)
+ err = os.WriteFile("sizeclasses.go", out, 0666)
}
if err != nil {
log.Fatal(err)
diff --git a/src/runtime/pprof/pprof_test.go b/src/runtime/pprof/pprof_test.go
index b807072485..b6ee160e84 100644
--- a/src/runtime/pprof/pprof_test.go
+++ b/src/runtime/pprof/pprof_test.go
@@ -13,7 +13,6 @@ import (
"internal/profile"
"internal/testenv"
"io"
- "io/ioutil"
"math/big"
"os"
"os/exec"
@@ -1179,7 +1178,7 @@ func TestLabelRace(t *testing.T) {
// Check that there is no deadlock when the program receives SIGPROF while in
// 64bit atomics' critical section. Used to happen on mips{,le}. See #20146.
func TestAtomicLoadStore64(t *testing.T) {
- f, err := ioutil.TempFile("", "profatomic")
+ f, err := os.CreateTemp("", "profatomic")
if err != nil {
t.Fatalf("TempFile: %v", err)
}
@@ -1208,7 +1207,7 @@ func TestAtomicLoadStore64(t *testing.T) {
func TestTracebackAll(t *testing.T) {
// With gccgo, if a profiling signal arrives at the wrong time
// during traceback, it may crash or hang. See issue #29448.
- f, err := ioutil.TempFile("", "proftraceback")
+ f, err := os.CreateTemp("", "proftraceback")
if err != nil {
t.Fatalf("TempFile: %v", err)
}
diff --git a/src/runtime/pprof/proto.go b/src/runtime/pprof/proto.go
index 8519af6985..bdb4454b6e 100644
--- a/src/runtime/pprof/proto.go
+++ b/src/runtime/pprof/proto.go
@@ -9,7 +9,7 @@ import (
"compress/gzip"
"fmt"
"io"
- "io/ioutil"
+ "os"
"runtime"
"strconv"
"time"
@@ -575,7 +575,7 @@ func (b *profileBuilder) emitLocation() uint64 {
// It saves the address ranges of the mappings in b.mem for use
// when emitting locations.
func (b *profileBuilder) readMapping() {
- data, _ := ioutil.ReadFile("/proc/self/maps")
+ data, _ := os.ReadFile("/proc/self/maps")
parseProcSelfMaps(data, b.addMapping)
if len(b.mem) == 0 { // pprof expects a map entry, so fake one.
b.addMappingEntry(0, 0, 0, "", "", true)
diff --git a/src/runtime/pprof/proto_test.go b/src/runtime/pprof/proto_test.go
index 3043d5353f..5eb1aab140 100644
--- a/src/runtime/pprof/proto_test.go
+++ b/src/runtime/pprof/proto_test.go
@@ -10,7 +10,6 @@ import (
"fmt"
"internal/profile"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"reflect"
@@ -78,7 +77,7 @@ func testPCs(t *testing.T) (addr1, addr2 uint64, map1, map2 *profile.Mapping) {
switch runtime.GOOS {
case "linux", "android", "netbsd":
// Figure out two addresses from /proc/self/maps.
- mmap, err := ioutil.ReadFile("/proc/self/maps")
+ mmap, err := os.ReadFile("/proc/self/maps")
if err != nil {
t.Fatal(err)
}
diff --git a/src/runtime/race/output_test.go b/src/runtime/race/output_test.go
index 5d0192f67f..986667332f 100644
--- a/src/runtime/race/output_test.go
+++ b/src/runtime/race/output_test.go
@@ -8,7 +8,6 @@ package race_test
import (
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -19,7 +18,7 @@ import (
)
func TestOutput(t *testing.T) {
- pkgdir, err := ioutil.TempDir("", "go-build-race-output")
+ pkgdir, err := os.MkdirTemp("", "go-build-race-output")
if err != nil {
t.Fatal(err)
}
@@ -34,7 +33,7 @@ func TestOutput(t *testing.T) {
t.Logf("test %v runs only on %v, skipping: ", test.name, test.goos)
continue
}
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
diff --git a/src/runtime/race/testdata/io_test.go b/src/runtime/race/testdata/io_test.go
index 30a121bee4..c5055f7837 100644
--- a/src/runtime/race/testdata/io_test.go
+++ b/src/runtime/race/testdata/io_test.go
@@ -6,7 +6,6 @@ package race_test
import (
"fmt"
- "io/ioutil"
"net"
"net/http"
"os"
@@ -18,7 +17,7 @@ import (
func TestNoRaceIOFile(t *testing.T) {
x := 0
- path, _ := ioutil.TempDir("", "race_test")
+ path, _ := os.MkdirTemp("", "race_test")
fname := filepath.Join(path, "data")
go func() {
x = 42
diff --git a/src/runtime/runtime-gdb_test.go b/src/runtime/runtime-gdb_test.go
index e52bd1c4c4..5df8c3c745 100644
--- a/src/runtime/runtime-gdb_test.go
+++ b/src/runtime/runtime-gdb_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -170,7 +169,7 @@ func testGdbPython(t *testing.T, cgo bool) {
checkGdbVersion(t)
checkGdbPython(t)
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
@@ -195,7 +194,7 @@ func testGdbPython(t *testing.T, cgo bool) {
}
}
- err = ioutil.WriteFile(filepath.Join(dir, "main.go"), src, 0644)
+ err = os.WriteFile(filepath.Join(dir, "main.go"), src, 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
@@ -404,7 +403,7 @@ func TestGdbBacktrace(t *testing.T) {
t.Parallel()
checkGdbVersion(t)
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
@@ -412,7 +411,7 @@ func TestGdbBacktrace(t *testing.T) {
// Build the source code.
src := filepath.Join(dir, "main.go")
- err = ioutil.WriteFile(src, []byte(backtraceSource), 0644)
+ err = os.WriteFile(src, []byte(backtraceSource), 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
@@ -482,7 +481,7 @@ func TestGdbAutotmpTypes(t *testing.T) {
t.Skip("TestGdbAutotmpTypes is too slow on aix/ppc64")
}
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
@@ -490,7 +489,7 @@ func TestGdbAutotmpTypes(t *testing.T) {
// Build the source code.
src := filepath.Join(dir, "main.go")
- err = ioutil.WriteFile(src, []byte(autotmpTypeSource), 0644)
+ err = os.WriteFile(src, []byte(autotmpTypeSource), 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
@@ -551,7 +550,7 @@ func TestGdbConst(t *testing.T) {
t.Parallel()
checkGdbVersion(t)
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
@@ -559,7 +558,7 @@ func TestGdbConst(t *testing.T) {
// Build the source code.
src := filepath.Join(dir, "main.go")
- err = ioutil.WriteFile(src, []byte(constsSource), 0644)
+ err = os.WriteFile(src, []byte(constsSource), 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
@@ -618,7 +617,7 @@ func TestGdbPanic(t *testing.T) {
t.Parallel()
checkGdbVersion(t)
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
@@ -626,7 +625,7 @@ func TestGdbPanic(t *testing.T) {
// Build the source code.
src := filepath.Join(dir, "main.go")
- err = ioutil.WriteFile(src, []byte(panicSource), 0644)
+ err = os.WriteFile(src, []byte(panicSource), 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
@@ -696,7 +695,7 @@ func TestGdbInfCallstack(t *testing.T) {
t.Parallel()
checkGdbVersion(t)
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
@@ -704,7 +703,7 @@ func TestGdbInfCallstack(t *testing.T) {
// Build the source code.
src := filepath.Join(dir, "main.go")
- err = ioutil.WriteFile(src, []byte(InfCallstackSource), 0644)
+ err = os.WriteFile(src, []byte(InfCallstackSource), 0644)
if err != nil {
t.Fatalf("failed to create file: %v", err)
}
diff --git a/src/runtime/runtime-lldb_test.go b/src/runtime/runtime-lldb_test.go
index 1e2e5d5be9..c923b872aa 100644
--- a/src/runtime/runtime-lldb_test.go
+++ b/src/runtime/runtime-lldb_test.go
@@ -6,7 +6,6 @@ package runtime_test
import (
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -143,20 +142,20 @@ func TestLldbPython(t *testing.T) {
checkLldbPython(t)
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
src := filepath.Join(dir, "main.go")
- err = ioutil.WriteFile(src, []byte(lldbHelloSource), 0644)
+ err = os.WriteFile(src, []byte(lldbHelloSource), 0644)
if err != nil {
t.Fatalf("failed to create src file: %v", err)
}
mod := filepath.Join(dir, "go.mod")
- err = ioutil.WriteFile(mod, []byte("module lldbtest"), 0644)
+ err = os.WriteFile(mod, []byte("module lldbtest"), 0644)
if err != nil {
t.Fatalf("failed to create mod file: %v", err)
}
@@ -172,7 +171,7 @@ func TestLldbPython(t *testing.T) {
}
src = filepath.Join(dir, "script.py")
- err = ioutil.WriteFile(src, []byte(lldbScriptSource), 0755)
+ err = os.WriteFile(src, []byte(lldbScriptSource), 0755)
if err != nil {
t.Fatalf("failed to create script: %v", err)
}
diff --git a/src/runtime/signal_windows_test.go b/src/runtime/signal_windows_test.go
index f99857193c..a5a885c2f7 100644
--- a/src/runtime/signal_windows_test.go
+++ b/src/runtime/signal_windows_test.go
@@ -7,7 +7,6 @@ import (
"bytes"
"fmt"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -28,7 +27,7 @@ func TestVectoredHandlerDontCrashOnLibrary(t *testing.T) {
testenv.MustHaveExecPath(t, "gcc")
testprog.Lock()
defer testprog.Unlock()
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
@@ -93,7 +92,7 @@ func TestLibraryCtrlHandler(t *testing.T) {
testenv.MustHaveExecPath(t, "gcc")
testprog.Lock()
defer testprog.Unlock()
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
diff --git a/src/runtime/syscall_windows_test.go b/src/runtime/syscall_windows_test.go
index a20573eb6a..fb215b3c31 100644
--- a/src/runtime/syscall_windows_test.go
+++ b/src/runtime/syscall_windows_test.go
@@ -10,7 +10,6 @@ import (
"internal/syscall/windows/sysdll"
"internal/testenv"
"io"
- "io/ioutil"
"math"
"os"
"os/exec"
@@ -446,7 +445,7 @@ func TestStdcallAndCDeclCallbacks(t *testing.T) {
if _, err := exec.LookPath("gcc"); err != nil {
t.Skip("skipping test: gcc is missing")
}
- tmp, err := ioutil.TempDir("", "TestCDeclCallback")
+ tmp, err := os.MkdirTemp("", "TestCDeclCallback")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
@@ -602,14 +601,14 @@ uintptr_t cfunc(callback f, uintptr_t n) {
return r;
}
`
- tmpdir, err := ioutil.TempDir("", "TestReturnAfterStackGrowInCallback")
+ tmpdir, err := os.MkdirTemp("", "TestReturnAfterStackGrowInCallback")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
defer os.RemoveAll(tmpdir)
srcname := "mydll.c"
- err = ioutil.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
+ err = os.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
if err != nil {
t.Fatal(err)
}
@@ -671,14 +670,14 @@ uintptr_t cfunc(uintptr_t a, double b, float c, double d) {
return 0;
}
`
- tmpdir, err := ioutil.TempDir("", "TestFloatArgs")
+ tmpdir, err := os.MkdirTemp("", "TestFloatArgs")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
defer os.RemoveAll(tmpdir)
srcname := "mydll.c"
- err = ioutil.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
+ err = os.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
if err != nil {
t.Fatal(err)
}
@@ -733,14 +732,14 @@ double cfuncDouble(uintptr_t a, double b, float c, double d) {
return 0;
}
`
- tmpdir, err := ioutil.TempDir("", "TestFloatReturn")
+ tmpdir, err := os.MkdirTemp("", "TestFloatReturn")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
defer os.RemoveAll(tmpdir)
srcname := "mydll.c"
- err = ioutil.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
+ err = os.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
if err != nil {
t.Fatal(err)
}
@@ -948,7 +947,7 @@ func TestDLLPreloadMitigation(t *testing.T) {
t.Skip("skipping test: gcc is missing")
}
- tmpdir, err := ioutil.TempDir("", "TestDLLPreloadMitigation")
+ tmpdir, err := os.MkdirTemp("", "TestDLLPreloadMitigation")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
@@ -975,7 +974,7 @@ uintptr_t cfunc(void) {
}
`
srcname := "nojack.c"
- err = ioutil.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
+ err = os.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
if err != nil {
t.Fatal(err)
}
@@ -1035,7 +1034,7 @@ func TestBigStackCallbackSyscall(t *testing.T) {
t.Fatal("Abs failed: ", err)
}
- tmpdir, err := ioutil.TempDir("", "TestBigStackCallback")
+ tmpdir, err := os.MkdirTemp("", "TestBigStackCallback")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
@@ -1184,14 +1183,14 @@ func BenchmarkOsYield(b *testing.B) {
}
func BenchmarkRunningGoProgram(b *testing.B) {
- tmpdir, err := ioutil.TempDir("", "BenchmarkRunningGoProgram")
+ tmpdir, err := os.MkdirTemp("", "BenchmarkRunningGoProgram")
if err != nil {
b.Fatal(err)
}
defer os.RemoveAll(tmpdir)
src := filepath.Join(tmpdir, "main.go")
- err = ioutil.WriteFile(src, []byte(benchmarkRunningGoProgram), 0666)
+ err = os.WriteFile(src, []byte(benchmarkRunningGoProgram), 0666)
if err != nil {
b.Fatal(err)
}
diff --git a/src/runtime/testdata/testprog/memprof.go b/src/runtime/testdata/testprog/memprof.go
index 7b134bc078..0392e60f84 100644
--- a/src/runtime/testdata/testprog/memprof.go
+++ b/src/runtime/testdata/testprog/memprof.go
@@ -7,7 +7,6 @@ package main
import (
"bytes"
"fmt"
- "io/ioutil"
"os"
"runtime"
"runtime/pprof"
@@ -31,7 +30,7 @@ func MemProf() {
runtime.GC()
- f, err := ioutil.TempFile("", "memprof")
+ f, err := os.CreateTemp("", "memprof")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
diff --git a/src/runtime/testdata/testprog/syscalls_linux.go b/src/runtime/testdata/testprog/syscalls_linux.go
index b8ac087626..48f8014237 100644
--- a/src/runtime/testdata/testprog/syscalls_linux.go
+++ b/src/runtime/testdata/testprog/syscalls_linux.go
@@ -7,7 +7,6 @@ package main
import (
"bytes"
"fmt"
- "io/ioutil"
"os"
"syscall"
)
@@ -17,7 +16,7 @@ func gettid() int {
}
func tidExists(tid int) (exists, supported bool) {
- stat, err := ioutil.ReadFile(fmt.Sprintf("/proc/self/task/%d/stat", tid))
+ stat, err := os.ReadFile(fmt.Sprintf("/proc/self/task/%d/stat", tid))
if os.IsNotExist(err) {
return false, true
}
diff --git a/src/runtime/testdata/testprog/timeprof.go b/src/runtime/testdata/testprog/timeprof.go
index 0702885369..1e90af4033 100644
--- a/src/runtime/testdata/testprog/timeprof.go
+++ b/src/runtime/testdata/testprog/timeprof.go
@@ -6,7 +6,6 @@ package main
import (
"fmt"
- "io/ioutil"
"os"
"runtime/pprof"
"time"
@@ -17,7 +16,7 @@ func init() {
}
func TimeProf() {
- f, err := ioutil.TempFile("", "timeprof")
+ f, err := os.CreateTemp("", "timeprof")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
diff --git a/src/runtime/testdata/testprog/vdso.go b/src/runtime/testdata/testprog/vdso.go
index ef92f48758..d2a300d8f2 100644
--- a/src/runtime/testdata/testprog/vdso.go
+++ b/src/runtime/testdata/testprog/vdso.go
@@ -8,7 +8,6 @@ package main
import (
"fmt"
- "io/ioutil"
"os"
"runtime/pprof"
"time"
@@ -19,7 +18,7 @@ func init() {
}
func signalInVDSO() {
- f, err := ioutil.TempFile("", "timeprofnow")
+ f, err := os.CreateTemp("", "timeprofnow")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
diff --git a/src/runtime/testdata/testprogcgo/pprof.go b/src/runtime/testdata/testprogcgo/pprof.go
index 00f2c42e93..3b73fa0bdd 100644
--- a/src/runtime/testdata/testprogcgo/pprof.go
+++ b/src/runtime/testdata/testprogcgo/pprof.go
@@ -60,7 +60,6 @@ import "C"
import (
"fmt"
- "io/ioutil"
"os"
"runtime"
"runtime/pprof"
@@ -75,7 +74,7 @@ func init() {
func CgoPprof() {
runtime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoTraceback), nil, nil)
- f, err := ioutil.TempFile("", "prof")
+ f, err := os.CreateTemp("", "prof")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
diff --git a/src/runtime/testdata/testprogcgo/threadpprof.go b/src/runtime/testdata/testprogcgo/threadpprof.go
index 37a2a1ab65..feb774ba59 100644
--- a/src/runtime/testdata/testprogcgo/threadpprof.go
+++ b/src/runtime/testdata/testprogcgo/threadpprof.go
@@ -74,7 +74,6 @@ import "C"
import (
"fmt"
- "io/ioutil"
"os"
"runtime"
"runtime/pprof"
@@ -97,7 +96,7 @@ func CgoPprofThreadNoTraceback() {
}
func pprofThread() {
- f, err := ioutil.TempFile("", "prof")
+ f, err := os.CreateTemp("", "prof")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
diff --git a/src/runtime/trace/trace_test.go b/src/runtime/trace/trace_test.go
index 235845df4e..b316eafe4c 100644
--- a/src/runtime/trace/trace_test.go
+++ b/src/runtime/trace/trace_test.go
@@ -10,7 +10,6 @@ import (
"internal/race"
"internal/trace"
"io"
- "io/ioutil"
"net"
"os"
"runtime"
@@ -586,7 +585,7 @@ func saveTrace(t *testing.T, buf *bytes.Buffer, name string) {
if !*saveTraces {
return
}
- if err := ioutil.WriteFile(name+".trace", buf.Bytes(), 0600); err != nil {
+ if err := os.WriteFile(name+".trace", buf.Bytes(), 0600); err != nil {
t.Errorf("failed to write trace file: %s", err)
}
}
diff --git a/src/runtime/wincallback.go b/src/runtime/wincallback.go
index c022916422..fb452222da 100644
--- a/src/runtime/wincallback.go
+++ b/src/runtime/wincallback.go
@@ -11,7 +11,6 @@ package main
import (
"bytes"
"fmt"
- "io/ioutil"
"os"
)
@@ -38,7 +37,7 @@ TEXT runtime·callbackasm(SB),7,$0
}
filename := fmt.Sprintf("zcallback_windows.s")
- err := ioutil.WriteFile(filename, buf.Bytes(), 0666)
+ err := os.WriteFile(filename, buf.Bytes(), 0666)
if err != nil {
fmt.Fprintf(os.Stderr, "wincallback: %s\n", err)
os.Exit(2)
@@ -66,7 +65,7 @@ TEXT runtime·callbackasm(SB),NOSPLIT|NOFRAME,$0
buf.WriteString("\tB\truntime·callbackasm1(SB)\n")
}
- err := ioutil.WriteFile("zcallback_windows_arm.s", buf.Bytes(), 0666)
+ err := os.WriteFile("zcallback_windows_arm.s", buf.Bytes(), 0666)
if err != nil {
fmt.Fprintf(os.Stderr, "wincallback: %s\n", err)
os.Exit(2)
@@ -82,7 +81,7 @@ package runtime
const cb_max = %d // maximum number of windows callbacks allowed
`, maxCallback))
- err := ioutil.WriteFile("zcallback_windows.go", buf.Bytes(), 0666)
+ err := os.WriteFile("zcallback_windows.go", buf.Bytes(), 0666)
if err != nil {
fmt.Fprintf(os.Stderr, "wincallback: %s\n", err)
os.Exit(2)
diff --git a/src/sort/genzfunc.go b/src/sort/genzfunc.go
index 66408d26c6..e7eb573737 100644
--- a/src/sort/genzfunc.go
+++ b/src/sort/genzfunc.go
@@ -20,8 +20,8 @@ import (
"go/format"
"go/parser"
"go/token"
- "io/ioutil"
"log"
+ "os"
"regexp"
)
@@ -92,7 +92,7 @@ func main() {
out.Write(src)
const target = "zfuncversion.go"
- if err := ioutil.WriteFile(target, out.Bytes(), 0644); err != nil {
+ if err := os.WriteFile(target, out.Bytes(), 0644); err != nil {
log.Fatal(err)
}
}
diff --git a/src/strconv/makeisprint.go b/src/strconv/makeisprint.go
index 1a3248f308..0e6e90a6c6 100644
--- a/src/strconv/makeisprint.go
+++ b/src/strconv/makeisprint.go
@@ -17,8 +17,8 @@ import (
"flag"
"fmt"
"go/format"
- "io/ioutil"
"log"
+ "os"
"unicode"
)
@@ -196,7 +196,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
- err = ioutil.WriteFile(*filename, data, 0644)
+ err = os.WriteFile(*filename, data, 0644)
if err != nil {
log.Fatal(err)
}
diff --git a/src/syscall/dirent_test.go b/src/syscall/dirent_test.go
index f63153340a..7dac98ff4b 100644
--- a/src/syscall/dirent_test.go
+++ b/src/syscall/dirent_test.go
@@ -9,7 +9,6 @@ package syscall_test
import (
"bytes"
"fmt"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -27,7 +26,7 @@ func TestDirent(t *testing.T) {
filenameMinSize = 11
)
- d, err := ioutil.TempDir("", "dirent-test")
+ d, err := os.MkdirTemp("", "dirent-test")
if err != nil {
t.Fatalf("tempdir: %v", err)
}
@@ -36,7 +35,7 @@ func TestDirent(t *testing.T) {
for i, c := range []byte("0123456789") {
name := string(bytes.Repeat([]byte{c}, filenameMinSize+i))
- err = ioutil.WriteFile(filepath.Join(d, name), nil, 0644)
+ err = os.WriteFile(filepath.Join(d, name), nil, 0644)
if err != nil {
t.Fatalf("writefile: %v", err)
}
@@ -93,7 +92,7 @@ func TestDirentRepeat(t *testing.T) {
}
// Make a directory containing N files
- d, err := ioutil.TempDir("", "direntRepeat-test")
+ d, err := os.MkdirTemp("", "direntRepeat-test")
if err != nil {
t.Fatalf("tempdir: %v", err)
}
@@ -104,7 +103,7 @@ func TestDirentRepeat(t *testing.T) {
files = append(files, fmt.Sprintf("file%d", i))
}
for _, file := range files {
- err = ioutil.WriteFile(filepath.Join(d, file), []byte("contents"), 0644)
+ err = os.WriteFile(filepath.Join(d, file), []byte("contents"), 0644)
if err != nil {
t.Fatalf("writefile: %v", err)
}
diff --git a/src/syscall/exec_linux_test.go b/src/syscall/exec_linux_test.go
index b79dee7525..ac3a5754ae 100644
--- a/src/syscall/exec_linux_test.go
+++ b/src/syscall/exec_linux_test.go
@@ -11,7 +11,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"os"
"os/exec"
"os/user"
@@ -65,7 +64,7 @@ func skipNoUserNamespaces(t *testing.T) {
func skipUnprivilegedUserClone(t *testing.T) {
// Skip the test if the sysctl that prevents unprivileged user
// from creating user namespaces is enabled.
- data, errRead := ioutil.ReadFile("/proc/sys/kernel/unprivileged_userns_clone")
+ data, errRead := os.ReadFile("/proc/sys/kernel/unprivileged_userns_clone")
if errRead != nil || len(data) < 1 || data[0] == '0' {
t.Skip("kernel prohibits user namespace in unprivileged process")
}
@@ -98,7 +97,7 @@ func checkUserNS(t *testing.T) {
// On Centos 7 make sure they set the kernel parameter user_namespace=1
// See issue 16283 and 20796.
if _, err := os.Stat("/sys/module/user_namespace/parameters/enable"); err == nil {
- buf, _ := ioutil.ReadFile("/sys/module/user_namespace/parameters/enabled")
+ buf, _ := os.ReadFile("/sys/module/user_namespace/parameters/enabled")
if !strings.HasPrefix(string(buf), "Y") {
t.Skip("kernel doesn't support user namespaces")
}
@@ -106,7 +105,7 @@ func checkUserNS(t *testing.T) {
// On Centos 7.5+, user namespaces are disabled if user.max_user_namespaces = 0
if _, err := os.Stat("/proc/sys/user/max_user_namespaces"); err == nil {
- buf, errRead := ioutil.ReadFile("/proc/sys/user/max_user_namespaces")
+ buf, errRead := os.ReadFile("/proc/sys/user/max_user_namespaces")
if errRead == nil && buf[0] == '0' {
t.Skip("kernel doesn't support user namespaces")
}
@@ -226,7 +225,7 @@ func TestUnshare(t *testing.T) {
t.Fatal(err)
}
- orig, err := ioutil.ReadFile(path)
+ orig, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
@@ -349,7 +348,7 @@ func TestUnshareMountNameSpace(t *testing.T) {
t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace")
}
- d, err := ioutil.TempDir("", "unshare")
+ d, err := os.MkdirTemp("", "unshare")
if err != nil {
t.Fatalf("tempdir: %v", err)
}
@@ -391,7 +390,7 @@ func TestUnshareMountNameSpaceChroot(t *testing.T) {
t.Skip("kernel prohibits unshare in unprivileged process, unless using user namespace")
}
- d, err := ioutil.TempDir("", "unshare")
+ d, err := os.MkdirTemp("", "unshare")
if err != nil {
t.Fatalf("tempdir: %v", err)
}
@@ -599,7 +598,7 @@ func testAmbientCaps(t *testing.T, userns bool) {
}
// Copy the test binary to a temporary location which is readable by nobody.
- f, err := ioutil.TempFile("", "gotest")
+ f, err := os.CreateTemp("", "gotest")
if err != nil {
t.Fatal(err)
}
diff --git a/src/syscall/getdirentries_test.go b/src/syscall/getdirentries_test.go
index 2a3419c230..66bb8acba2 100644
--- a/src/syscall/getdirentries_test.go
+++ b/src/syscall/getdirentries_test.go
@@ -8,7 +8,6 @@ package syscall_test
import (
"fmt"
- "io/ioutil"
"os"
"path/filepath"
"sort"
@@ -29,7 +28,7 @@ func testGetdirentries(t *testing.T, count int) {
if count > 100 && testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
t.Skip("skipping in -short mode")
}
- d, err := ioutil.TempDir("", "getdirentries-test")
+ d, err := os.MkdirTemp("", "getdirentries-test")
if err != nil {
t.Fatalf("Tempdir: %v", err)
}
@@ -41,7 +40,7 @@ func testGetdirentries(t *testing.T, count int) {
// Make files in the temp directory
for _, name := range names {
- err := ioutil.WriteFile(filepath.Join(d, name), []byte("data"), 0)
+ err := os.WriteFile(filepath.Join(d, name), []byte("data"), 0)
if err != nil {
t.Fatalf("WriteFile: %v", err)
}
diff --git a/src/syscall/mkasm_darwin.go b/src/syscall/mkasm_darwin.go
index f6f75f99f6..1783387a53 100644
--- a/src/syscall/mkasm_darwin.go
+++ b/src/syscall/mkasm_darwin.go
@@ -11,23 +11,22 @@ package main
import (
"bytes"
"fmt"
- "io/ioutil"
"log"
"os"
"strings"
)
func main() {
- in1, err := ioutil.ReadFile("syscall_darwin.go")
+ in1, err := os.ReadFile("syscall_darwin.go")
if err != nil {
log.Fatalf("can't open syscall_darwin.go: %s", err)
}
arch := os.Args[1]
- in2, err := ioutil.ReadFile(fmt.Sprintf("syscall_darwin_%s.go", arch))
+ in2, err := os.ReadFile(fmt.Sprintf("syscall_darwin_%s.go", arch))
if err != nil {
log.Fatalf("can't open syscall_darwin_%s.go: %s", arch, err)
}
- in3, err := ioutil.ReadFile(fmt.Sprintf("zsyscall_darwin_%s.go", arch))
+ in3, err := os.ReadFile(fmt.Sprintf("zsyscall_darwin_%s.go", arch))
if err != nil {
log.Fatalf("can't open zsyscall_darwin_%s.go: %s", arch, err)
}
@@ -51,7 +50,7 @@ func main() {
fmt.Fprintf(&out, "\tJMP\t%s(SB)\n", fn)
}
}
- err = ioutil.WriteFile(fmt.Sprintf("zsyscall_darwin_%s.s", arch), out.Bytes(), 0644)
+ err = os.WriteFile(fmt.Sprintf("zsyscall_darwin_%s.s", arch), out.Bytes(), 0644)
if err != nil {
log.Fatalf("can't write zsyscall_darwin_%s.s: %s", arch, err)
}
diff --git a/src/syscall/syscall_linux_test.go b/src/syscall/syscall_linux_test.go
index 92764323ee..153d0efef1 100644
--- a/src/syscall/syscall_linux_test.go
+++ b/src/syscall/syscall_linux_test.go
@@ -9,7 +9,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"os"
"os/exec"
"os/signal"
@@ -30,7 +29,7 @@ func chtmpdir(t *testing.T) func() {
if err != nil {
t.Fatalf("chtmpdir: %v", err)
}
- d, err := ioutil.TempDir("", "test")
+ d, err := os.MkdirTemp("", "test")
if err != nil {
t.Fatalf("chtmpdir: %v", err)
}
@@ -160,7 +159,7 @@ func TestLinuxDeathSignal(t *testing.T) {
// Copy the test binary to a location that a non-root user can read/execute
// after we drop privileges
- tempDir, err := ioutil.TempDir("", "TestDeathSignal")
+ tempDir, err := os.MkdirTemp("", "TestDeathSignal")
if err != nil {
t.Fatalf("cannot create temporary directory: %v", err)
}
@@ -321,7 +320,7 @@ func TestSyscallNoError(t *testing.T) {
// Copy the test binary to a location that a non-root user can read/execute
// after we drop privileges
- tempDir, err := ioutil.TempDir("", "TestSyscallNoError")
+ tempDir, err := os.MkdirTemp("", "TestSyscallNoError")
if err != nil {
t.Fatalf("cannot create temporary directory: %v", err)
}
@@ -543,7 +542,7 @@ func TestAllThreadsSyscall(t *testing.T) {
func compareStatus(filter, expect string) error {
expected := filter + expect
pid := syscall.Getpid()
- fs, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/task", pid))
+ fs, err := os.ReadDir(fmt.Sprintf("/proc/%d/task", pid))
if err != nil {
return fmt.Errorf("unable to find %d tasks: %v", pid, err)
}
@@ -551,7 +550,7 @@ func compareStatus(filter, expect string) error {
foundAThread := false
for _, f := range fs {
tf := fmt.Sprintf("/proc/%s/status", f.Name())
- d, err := ioutil.ReadFile(tf)
+ d, err := os.ReadFile(tf)
if err != nil {
// There are a surprising number of ways this
// can error out on linux. We've seen all of
diff --git a/src/syscall/syscall_unix_test.go b/src/syscall/syscall_unix_test.go
index 1c34ed2c27..7e6a8c9043 100644
--- a/src/syscall/syscall_unix_test.go
+++ b/src/syscall/syscall_unix_test.go
@@ -11,7 +11,6 @@ import (
"fmt"
"internal/testenv"
"io"
- "io/ioutil"
"net"
"os"
"os/exec"
@@ -79,7 +78,7 @@ func TestFcntlFlock(t *testing.T) {
}
if os.Getenv("GO_WANT_HELPER_PROCESS") == "" {
// parent
- tempDir, err := ioutil.TempDir("", "TestFcntlFlock")
+ tempDir, err := os.MkdirTemp("", "TestFcntlFlock")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
@@ -157,7 +156,7 @@ func TestPassFD(t *testing.T) {
}
- tempDir, err := ioutil.TempDir("", "TestPassFD")
+ tempDir, err := os.MkdirTemp("", "TestPassFD")
if err != nil {
t.Fatal(err)
}
@@ -257,7 +256,7 @@ func passFDChild() {
// We make it in tempDir, which our parent will clean up.
flag.Parse()
tempDir := flag.Arg(0)
- f, err := ioutil.TempFile(tempDir, "")
+ f, err := os.CreateTemp(tempDir, "")
if err != nil {
fmt.Printf("TempFile: %v", err)
return
diff --git a/src/syscall/syscall_windows_test.go b/src/syscall/syscall_windows_test.go
index d146911073..a9ae54752b 100644
--- a/src/syscall/syscall_windows_test.go
+++ b/src/syscall/syscall_windows_test.go
@@ -5,7 +5,6 @@
package syscall_test
import (
- "io/ioutil"
"os"
"path/filepath"
"syscall"
@@ -13,7 +12,7 @@ import (
)
func TestWin32finddata(t *testing.T) {
- dir, err := ioutil.TempDir("", "go-build")
+ dir, err := os.MkdirTemp("", "go-build")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
diff --git a/src/testing/testing.go b/src/testing/testing.go
index d4b108a183..80354d5ce8 100644
--- a/src/testing/testing.go
+++ b/src/testing/testing.go
@@ -242,7 +242,6 @@ import (
"fmt"
"internal/race"
"io"
- "io/ioutil"
"os"
"runtime"
"runtime/debug"
@@ -936,14 +935,14 @@ func (c *common) TempDir() string {
if nonExistent {
c.Helper()
- // ioutil.TempDir doesn't like path separators in its pattern,
+ // os.MkdirTemp doesn't like path separators in its pattern,
// so mangle the name to accommodate subtests.
tempDirReplacer.Do(func() {
tempDirReplacer.r = strings.NewReplacer("/", "_", "\\", "_", ":", "_")
})
pattern := tempDirReplacer.r.Replace(c.Name())
- c.tempDir, c.tempDirErr = ioutil.TempDir("", pattern)
+ c.tempDir, c.tempDirErr = os.MkdirTemp("", pattern)
if c.tempDirErr == nil {
c.Cleanup(func() {
if err := os.RemoveAll(c.tempDir); err != nil {
diff --git a/src/text/template/examplefiles_test.go b/src/text/template/examplefiles_test.go
index a15c7a62a3..6534ee3315 100644
--- a/src/text/template/examplefiles_test.go
+++ b/src/text/template/examplefiles_test.go
@@ -6,7 +6,6 @@ package template_test
import (
"io"
- "io/ioutil"
"log"
"os"
"path/filepath"
@@ -20,7 +19,7 @@ type templateFile struct {
}
func createTestDir(files []templateFile) string {
- dir, err := ioutil.TempDir("", "template")
+ dir, err := os.MkdirTemp("", "template")
if err != nil {
log.Fatal(err)
}
diff --git a/src/text/template/helper.go b/src/text/template/helper.go
index 8269fa28c5..57905e613a 100644
--- a/src/text/template/helper.go
+++ b/src/text/template/helper.go
@@ -9,7 +9,7 @@ package template
import (
"fmt"
"io/fs"
- "io/ioutil"
+ "os"
"path"
"path/filepath"
)
@@ -164,7 +164,7 @@ func parseFS(t *Template, fsys fs.FS, patterns []string) (*Template, error) {
func readFileOS(file string) (name string, b []byte, err error) {
name = filepath.Base(file)
- b, err = ioutil.ReadFile(file)
+ b, err = os.ReadFile(file)
return
}
diff --git a/src/text/template/link_test.go b/src/text/template/link_test.go
index 4eac7e6755..9dc70dfc0d 100644
--- a/src/text/template/link_test.go
+++ b/src/text/template/link_test.go
@@ -7,7 +7,6 @@ package template_test
import (
"bytes"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -40,13 +39,13 @@ func main() {
t.Used()
}
`
- td, err := ioutil.TempDir("", "text_template_TestDeadCodeElimination")
+ td, err := os.MkdirTemp("", "text_template_TestDeadCodeElimination")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(td)
- if err := ioutil.WriteFile(filepath.Join(td, "x.go"), []byte(prog), 0644); err != nil {
+ if err := os.WriteFile(filepath.Join(td, "x.go"), []byte(prog), 0644); err != nil {
t.Fatal(err)
}
cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "x.exe", "x.go")
@@ -54,7 +53,7 @@ func main() {
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("go build: %v, %s", err, out)
}
- slurp, err := ioutil.ReadFile(filepath.Join(td, "x.exe"))
+ slurp, err := os.ReadFile(filepath.Join(td, "x.exe"))
if err != nil {
t.Fatal(err)
}
diff --git a/src/time/genzabbrs.go b/src/time/genzabbrs.go
index 1d59ba73ce..9825e705d2 100644
--- a/src/time/genzabbrs.go
+++ b/src/time/genzabbrs.go
@@ -18,9 +18,9 @@ import (
"flag"
"go/format"
"io"
- "io/ioutil"
"log"
"net/http"
+ "os"
"sort"
"text/template"
"time"
@@ -128,7 +128,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
- err = ioutil.WriteFile(*filename, data, 0644)
+ err = os.WriteFile(*filename, data, 0644)
if err != nil {
log.Fatal(err)
}
diff --git a/src/time/tzdata/generate_zipdata.go b/src/time/tzdata/generate_zipdata.go
index d8b47e7878..21357fbf1c 100644
--- a/src/time/tzdata/generate_zipdata.go
+++ b/src/time/tzdata/generate_zipdata.go
@@ -10,7 +10,6 @@ package main
import (
"bufio"
"fmt"
- "io/ioutil"
"os"
"strconv"
)
@@ -40,7 +39,7 @@ const zipdata = `
func main() {
// We should be run in the $GOROOT/src/time/tzdata directory.
- data, err := ioutil.ReadFile("../../../lib/time/zoneinfo.zip")
+ data, err := os.ReadFile("../../../lib/time/zoneinfo.zip")
if err != nil {
die("cannot find zoneinfo.zip file: %v", err)
}
diff --git a/src/time/zoneinfo_read.go b/src/time/zoneinfo_read.go
index 22a60f3211..c739864815 100644
--- a/src/time/zoneinfo_read.go
+++ b/src/time/zoneinfo_read.go
@@ -546,7 +546,7 @@ func loadLocation(name string, sources []string) (z *Location, firstErr error) {
}
// readFile reads and returns the content of the named file.
-// It is a trivial implementation of ioutil.ReadFile, reimplemented
+// It is a trivial implementation of os.ReadFile, reimplemented
// here to avoid depending on io/ioutil or os.
// It returns an error if name exceeds maxFileSize bytes.
func readFile(name string) ([]byte, error) {
--
cgit v1.3
From f1980efb92c011eab71aa61b68ccf58d845d1de7 Mon Sep 17 00:00:00 2001
From: Russ Cox
Date: Thu, 29 Oct 2020 14:46:29 -0400
Subject: all: update to use os.ReadDir where appropriate
os.ReadDir is a replacement for ioutil.ReadDir that returns
a slice of fs.DirEntry instead of fs.FileInfo, meaning it is the
more efficient form.
This CL updates call sites throughout the Go source tree
wherever possible. As usual, code built using the Go 1.4
bootstrap toolchain is not included. There is also a use in
go/build that appears in the public API and can't be changed,
at least not without additional changes.
Fixes #42026.
Change-Id: Icfc9dd52c6045020f6830e22c72128499462d561
Reviewed-on: https://go-review.googlesource.com/c/go/+/266366
Trust: Russ Cox
Run-TryBot: Russ Cox
TryBot-Result: Go Bot
Reviewed-by: Ian Lance Taylor
---
src/cmd/go/internal/clean/clean.go | 3 +-
src/cmd/go/internal/imports/scan_test.go | 3 +-
src/cmd/go/internal/load/pkg.go | 7 ++---
src/cmd/go/internal/modcmd/vendor.go | 11 +++----
src/cmd/go/internal/modfetch/cache.go | 3 +-
src/cmd/go/internal/modload/init.go | 17 +++++-----
src/cmd/go/internal/test/test.go | 12 +++++---
src/cmd/go/proxy_test.go | 7 ++---
src/crypto/x509/root_unix.go | 21 ++++++-------
src/go/build/deps_test.go | 3 +-
src/go/internal/gcimporter/gcimporter_test.go | 5 ++-
src/go/internal/srcimporter/srcimporter_test.go | 3 +-
src/go/parser/error_test.go | 10 +++---
src/go/parser/interface.go | 41 +++++++++++++++----------
src/go/types/check_test.go | 11 +++----
src/go/types/stdlib_test.go | 11 +++----
src/internal/trace/parser_test.go | 7 ++---
src/os/exec/exec_test.go | 3 +-
src/testing/testing_test.go | 7 ++---
19 files changed, 91 insertions(+), 94 deletions(-)
(limited to 'src/testing')
diff --git a/src/cmd/go/internal/clean/clean.go b/src/cmd/go/internal/clean/clean.go
index 87933f04f3..b1d40feb27 100644
--- a/src/cmd/go/internal/clean/clean.go
+++ b/src/cmd/go/internal/clean/clean.go
@@ -9,7 +9,6 @@ import (
"context"
"fmt"
"io"
- "io/ioutil"
"os"
"path/filepath"
"strconv"
@@ -244,7 +243,7 @@ func clean(p *load.Package) {
base.Errorf("%v", p.Error)
return
}
- dirs, err := ioutil.ReadDir(p.Dir)
+ dirs, err := os.ReadDir(p.Dir)
if err != nil {
base.Errorf("go clean %s: %v", p.Dir, err)
return
diff --git a/src/cmd/go/internal/imports/scan_test.go b/src/cmd/go/internal/imports/scan_test.go
index 5ba3201968..2d245ee787 100644
--- a/src/cmd/go/internal/imports/scan_test.go
+++ b/src/cmd/go/internal/imports/scan_test.go
@@ -7,7 +7,6 @@ package imports
import (
"bytes"
"internal/testenv"
- "io/ioutil"
"os"
"path"
"path/filepath"
@@ -58,7 +57,7 @@ func TestScan(t *testing.T) {
func TestScanDir(t *testing.T) {
testenv.MustHaveGoBuild(t)
- dirs, err := ioutil.ReadDir("testdata")
+ dirs, err := os.ReadDir("testdata")
if err != nil {
t.Fatal(err)
}
diff --git a/src/cmd/go/internal/load/pkg.go b/src/cmd/go/internal/load/pkg.go
index da3e0b895c..6f95af4f7e 100644
--- a/src/cmd/go/internal/load/pkg.go
+++ b/src/cmd/go/internal/load/pkg.go
@@ -15,7 +15,6 @@ import (
"go/scanner"
"go/token"
"io/fs"
- "io/ioutil"
"os"
"path"
pathpkg "path"
@@ -1296,9 +1295,9 @@ HaveGoMod:
// Otherwise it is not possible to vendor just a/b/c and still import the
// non-vendored a/b. See golang.org/issue/13832.
func hasGoFiles(dir string) bool {
- fis, _ := ioutil.ReadDir(dir)
- for _, fi := range fis {
- if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") {
+ files, _ := os.ReadDir(dir)
+ for _, f := range files {
+ if !f.IsDir() && strings.HasSuffix(f.Name(), ".go") {
return true
}
}
diff --git a/src/cmd/go/internal/modcmd/vendor.go b/src/cmd/go/internal/modcmd/vendor.go
index 390a195547..1bbb57d353 100644
--- a/src/cmd/go/internal/modcmd/vendor.go
+++ b/src/cmd/go/internal/modcmd/vendor.go
@@ -10,7 +10,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"sort"
@@ -244,7 +243,7 @@ var metaPrefixes = []string{
}
// matchMetadata reports whether info is a metadata file.
-func matchMetadata(dir string, info fs.FileInfo) bool {
+func matchMetadata(dir string, info fs.DirEntry) bool {
name := info.Name()
for _, p := range metaPrefixes {
if strings.HasPrefix(name, p) {
@@ -255,7 +254,7 @@ func matchMetadata(dir string, info fs.FileInfo) bool {
}
// matchPotentialSourceFile reports whether info may be relevant to a build operation.
-func matchPotentialSourceFile(dir string, info fs.FileInfo) bool {
+func matchPotentialSourceFile(dir string, info fs.DirEntry) bool {
if strings.HasSuffix(info.Name(), "_test.go") {
return false
}
@@ -281,8 +280,8 @@ func matchPotentialSourceFile(dir string, info fs.FileInfo) bool {
}
// copyDir copies all regular files satisfying match(info) from src to dst.
-func copyDir(dst, src string, match func(dir string, info fs.FileInfo) bool) {
- files, err := ioutil.ReadDir(src)
+func copyDir(dst, src string, match func(dir string, info fs.DirEntry) bool) {
+ files, err := os.ReadDir(src)
if err != nil {
base.Fatalf("go mod vendor: %v", err)
}
@@ -290,7 +289,7 @@ func copyDir(dst, src string, match func(dir string, info fs.FileInfo) bool) {
base.Fatalf("go mod vendor: %v", err)
}
for _, file := range files {
- if file.IsDir() || !file.Mode().IsRegular() || !match(src, file) {
+ if file.IsDir() || !file.Type().IsRegular() || !match(src, file) {
continue
}
r, err := os.Open(filepath.Join(src, file.Name()))
diff --git a/src/cmd/go/internal/modfetch/cache.go b/src/cmd/go/internal/modfetch/cache.go
index 7572ff24f8..3a2ff63721 100644
--- a/src/cmd/go/internal/modfetch/cache.go
+++ b/src/cmd/go/internal/modfetch/cache.go
@@ -11,7 +11,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"strings"
@@ -598,7 +597,7 @@ func rewriteVersionList(dir string) {
}
defer unlock()
- infos, err := ioutil.ReadDir(dir)
+ infos, err := os.ReadDir(dir)
if err != nil {
return
}
diff --git a/src/cmd/go/internal/modload/init.go b/src/cmd/go/internal/modload/init.go
index 6a2cea668d..3f70d04145 100644
--- a/src/cmd/go/internal/modload/init.go
+++ b/src/cmd/go/internal/modload/init.go
@@ -12,7 +12,6 @@ import (
"fmt"
"go/build"
"internal/lazyregexp"
- "io/ioutil"
"os"
"path"
"path/filepath"
@@ -445,13 +444,13 @@ func CreateModFile(ctx context.Context, modPath string) {
// this is an existing project. Walking the tree for packages would be more
// accurate, but could take much longer.
empty := true
- fis, _ := ioutil.ReadDir(modRoot)
- for _, fi := range fis {
- name := fi.Name()
+ files, _ := os.ReadDir(modRoot)
+ for _, f := range files {
+ name := f.Name()
if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") {
continue
}
- if strings.HasSuffix(name, ".go") || fi.IsDir() {
+ if strings.HasSuffix(name, ".go") || f.IsDir() {
empty = false
break
}
@@ -731,9 +730,9 @@ func findModulePath(dir string) (string, error) {
// Cast about for import comments,
// first in top-level directory, then in subdirectories.
- list, _ := ioutil.ReadDir(dir)
+ list, _ := os.ReadDir(dir)
for _, info := range list {
- if info.Mode().IsRegular() && strings.HasSuffix(info.Name(), ".go") {
+ if info.Type().IsRegular() && strings.HasSuffix(info.Name(), ".go") {
if com := findImportComment(filepath.Join(dir, info.Name())); com != "" {
return com, nil
}
@@ -741,9 +740,9 @@ func findModulePath(dir string) (string, error) {
}
for _, info1 := range list {
if info1.IsDir() {
- files, _ := ioutil.ReadDir(filepath.Join(dir, info1.Name()))
+ files, _ := os.ReadDir(filepath.Join(dir, info1.Name()))
for _, info2 := range files {
- if info2.Mode().IsRegular() && strings.HasSuffix(info2.Name(), ".go") {
+ if info2.Type().IsRegular() && strings.HasSuffix(info2.Name(), ".go") {
if com := findImportComment(filepath.Join(dir, info1.Name(), info2.Name())); com != "" {
return path.Dir(com), nil
}
diff --git a/src/cmd/go/internal/test/test.go b/src/cmd/go/internal/test/test.go
index 401b67c260..e8a7aacb85 100644
--- a/src/cmd/go/internal/test/test.go
+++ b/src/cmd/go/internal/test/test.go
@@ -13,7 +13,6 @@ import (
"go/build"
"io"
"io/fs"
- "io/ioutil"
"os"
"os/exec"
"path"
@@ -1561,13 +1560,18 @@ func hashOpen(name string) (cache.ActionID, error) {
}
hashWriteStat(h, info)
if info.IsDir() {
- names, err := ioutil.ReadDir(name)
+ files, err := os.ReadDir(name)
if err != nil {
fmt.Fprintf(h, "err %v\n", err)
}
- for _, f := range names {
+ for _, f := range files {
fmt.Fprintf(h, "file %s ", f.Name())
- hashWriteStat(h, f)
+ finfo, err := f.Info()
+ if err != nil {
+ fmt.Fprintf(h, "err %v\n", err)
+ } else {
+ hashWriteStat(h, finfo)
+ }
}
} else if info.Mode().IsRegular() {
// Because files might be very large, do not attempt
diff --git a/src/cmd/go/proxy_test.go b/src/cmd/go/proxy_test.go
index 3ed42face2..e390c73a9c 100644
--- a/src/cmd/go/proxy_test.go
+++ b/src/cmd/go/proxy_test.go
@@ -13,7 +13,6 @@ import (
"fmt"
"io"
"io/fs"
- "io/ioutil"
"log"
"net"
"net/http"
@@ -75,12 +74,12 @@ func StartProxy() {
var modList []module.Version
func readModList() {
- infos, err := ioutil.ReadDir("testdata/mod")
+ files, err := os.ReadDir("testdata/mod")
if err != nil {
log.Fatal(err)
}
- for _, info := range infos {
- name := info.Name()
+ for _, f := range files {
+ name := f.Name()
if !strings.HasSuffix(name, ".txt") {
continue
}
diff --git a/src/crypto/x509/root_unix.go b/src/crypto/x509/root_unix.go
index 3c643466ed..262fc079d5 100644
--- a/src/crypto/x509/root_unix.go
+++ b/src/crypto/x509/root_unix.go
@@ -8,7 +8,6 @@ package x509
import (
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"strings"
@@ -82,17 +81,17 @@ func loadSystemRoots() (*CertPool, error) {
return nil, firstErr
}
-// readUniqueDirectoryEntries is like ioutil.ReadDir but omits
+// readUniqueDirectoryEntries is like os.ReadDir but omits
// symlinks that point within the directory.
-func readUniqueDirectoryEntries(dir string) ([]fs.FileInfo, error) {
- fis, err := ioutil.ReadDir(dir)
+func readUniqueDirectoryEntries(dir string) ([]fs.DirEntry, error) {
+ files, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
- uniq := fis[:0]
- for _, fi := range fis {
- if !isSameDirSymlink(fi, dir) {
- uniq = append(uniq, fi)
+ uniq := files[:0]
+ for _, f := range files {
+ if !isSameDirSymlink(f, dir) {
+ uniq = append(uniq, f)
}
}
return uniq, nil
@@ -100,10 +99,10 @@ func readUniqueDirectoryEntries(dir string) ([]fs.FileInfo, error) {
// isSameDirSymlink reports whether fi in dir is a symlink with a
// target not containing a slash.
-func isSameDirSymlink(fi fs.FileInfo, dir string) bool {
- if fi.Mode()&fs.ModeSymlink == 0 {
+func isSameDirSymlink(f fs.DirEntry, dir string) bool {
+ if f.Type()&fs.ModeSymlink == 0 {
return false
}
- target, err := os.Readlink(filepath.Join(dir, fi.Name()))
+ target, err := os.Readlink(filepath.Join(dir, f.Name()))
return err == nil && !strings.Contains(target, "/")
}
diff --git a/src/go/build/deps_test.go b/src/go/build/deps_test.go
index e9ed26aa5f..56942c0fd2 100644
--- a/src/go/build/deps_test.go
+++ b/src/go/build/deps_test.go
@@ -12,7 +12,6 @@ import (
"fmt"
"internal/testenv"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -597,7 +596,7 @@ func findImports(pkg string) ([]string, error) {
vpkg = "vendor/" + pkg
}
dir := filepath.Join(Default.GOROOT, "src", vpkg)
- files, err := ioutil.ReadDir(dir)
+ files, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
diff --git a/src/go/internal/gcimporter/gcimporter_test.go b/src/go/internal/gcimporter/gcimporter_test.go
index 8991e3bdee..3c76aafde3 100644
--- a/src/go/internal/gcimporter/gcimporter_test.go
+++ b/src/go/internal/gcimporter/gcimporter_test.go
@@ -8,7 +8,6 @@ import (
"bytes"
"fmt"
"internal/testenv"
- "io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -66,7 +65,7 @@ const maxTime = 30 * time.Second
func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) {
dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir)
- list, err := ioutil.ReadDir(dirname)
+ list, err := os.ReadDir(dirname)
if err != nil {
t.Fatalf("testDir(%s): %s", dirname, err)
}
@@ -144,7 +143,7 @@ func TestVersionHandling(t *testing.T) {
}
const dir = "./testdata/versions"
- list, err := ioutil.ReadDir(dir)
+ list, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
diff --git a/src/go/internal/srcimporter/srcimporter_test.go b/src/go/internal/srcimporter/srcimporter_test.go
index 102ac43f94..05b12f1636 100644
--- a/src/go/internal/srcimporter/srcimporter_test.go
+++ b/src/go/internal/srcimporter/srcimporter_test.go
@@ -10,7 +10,6 @@ import (
"go/token"
"go/types"
"internal/testenv"
- "io/ioutil"
"os"
"path"
"path/filepath"
@@ -59,7 +58,7 @@ func walkDir(t *testing.T, path string, endTime time.Time) (int, bool) {
return 0, false
}
- list, err := ioutil.ReadDir(filepath.Join(runtime.GOROOT(), "src", path))
+ list, err := os.ReadDir(filepath.Join(runtime.GOROOT(), "src", path))
if err != nil {
t.Fatalf("walkDir %s failed (%v)", path, err)
}
diff --git a/src/go/parser/error_test.go b/src/go/parser/error_test.go
index 9b79097acf..358a844f65 100644
--- a/src/go/parser/error_test.go
+++ b/src/go/parser/error_test.go
@@ -25,7 +25,7 @@ package parser
import (
"go/scanner"
"go/token"
- "io/ioutil"
+ "os"
"path/filepath"
"regexp"
"strings"
@@ -174,13 +174,13 @@ func checkErrors(t *testing.T, filename string, input interface{}) {
}
func TestErrors(t *testing.T) {
- list, err := ioutil.ReadDir(testdata)
+ list, err := os.ReadDir(testdata)
if err != nil {
t.Fatal(err)
}
- for _, fi := range list {
- name := fi.Name()
- if !fi.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".src") {
+ for _, d := range list {
+ name := d.Name()
+ if !d.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".src") {
checkErrors(t, filepath.Join(testdata, name), nil)
}
}
diff --git a/src/go/parser/interface.go b/src/go/parser/interface.go
index 41d9a52847..56ff5fefb4 100644
--- a/src/go/parser/interface.go
+++ b/src/go/parser/interface.go
@@ -13,7 +13,6 @@ import (
"go/token"
"io"
"io/fs"
- "io/ioutil"
"os"
"path/filepath"
"strings"
@@ -134,29 +133,39 @@ func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode)
// first error encountered are returned.
//
func ParseDir(fset *token.FileSet, path string, filter func(fs.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error) {
- list, err := ioutil.ReadDir(path)
+ list, err := os.ReadDir(path)
if err != nil {
return nil, err
}
pkgs = make(map[string]*ast.Package)
for _, d := range list {
- if !d.IsDir() && strings.HasSuffix(d.Name(), ".go") && (filter == nil || filter(d)) {
- filename := filepath.Join(path, d.Name())
- if src, err := ParseFile(fset, filename, nil, mode); err == nil {
- name := src.Name.Name
- pkg, found := pkgs[name]
- if !found {
- pkg = &ast.Package{
- Name: name,
- Files: make(map[string]*ast.File),
- }
- pkgs[name] = pkg
+ if d.IsDir() || !strings.HasSuffix(d.Name(), ".go") {
+ continue
+ }
+ if filter != nil {
+ info, err := d.Info()
+ if err != nil {
+ return nil, err
+ }
+ if !filter(info) {
+ continue
+ }
+ }
+ filename := filepath.Join(path, d.Name())
+ if src, err := ParseFile(fset, filename, nil, mode); err == nil {
+ name := src.Name.Name
+ pkg, found := pkgs[name]
+ if !found {
+ pkg = &ast.Package{
+ Name: name,
+ Files: make(map[string]*ast.File),
}
- pkg.Files[filename] = src
- } else if first == nil {
- first = err
+ pkgs[name] = pkg
}
+ pkg.Files[filename] = src
+ } else if first == nil {
+ first = err
}
}
diff --git a/src/go/types/check_test.go b/src/go/types/check_test.go
index 841ca24511..ce31dab68b 100644
--- a/src/go/types/check_test.go
+++ b/src/go/types/check_test.go
@@ -33,7 +33,6 @@ import (
"go/scanner"
"go/token"
"internal/testenv"
- "io/ioutil"
"os"
"path/filepath"
"regexp"
@@ -330,17 +329,17 @@ func TestFixedBugs(t *testing.T) { testDir(t, "fixedbugs") }
func testDir(t *testing.T, dir string) {
testenv.MustHaveGoBuild(t)
- fis, err := ioutil.ReadDir(dir)
+ dirs, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
- for _, fi := range fis {
- testname := filepath.Base(fi.Name())
+ for _, d := range dirs {
+ testname := filepath.Base(d.Name())
testname = strings.TrimSuffix(testname, filepath.Ext(testname))
t.Run(testname, func(t *testing.T) {
- filename := filepath.Join(dir, fi.Name())
- if fi.IsDir() {
+ filename := filepath.Join(dir, d.Name())
+ if d.IsDir() {
t.Errorf("skipped directory %q", filename)
return
}
diff --git a/src/go/types/stdlib_test.go b/src/go/types/stdlib_test.go
index 669e7bec20..23f8f9a18d 100644
--- a/src/go/types/stdlib_test.go
+++ b/src/go/types/stdlib_test.go
@@ -16,7 +16,6 @@ import (
"go/scanner"
"go/token"
"internal/testenv"
- "io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -87,7 +86,7 @@ func firstComment(filename string) string {
}
func testTestDir(t *testing.T, path string, ignore ...string) {
- files, err := ioutil.ReadDir(path)
+ files, err := os.ReadDir(path)
if err != nil {
t.Fatal(err)
}
@@ -297,7 +296,7 @@ func (w *walker) walk(dir string) {
return
}
- fis, err := ioutil.ReadDir(dir)
+ files, err := os.ReadDir(dir)
if err != nil {
w.errh(err)
return
@@ -317,9 +316,9 @@ func (w *walker) walk(dir string) {
}
// traverse subdirectories, but don't walk into testdata
- for _, fi := range fis {
- if fi.IsDir() && fi.Name() != "testdata" {
- w.walk(filepath.Join(dir, fi.Name()))
+ for _, f := range files {
+ if f.IsDir() && f.Name() != "testdata" {
+ w.walk(filepath.Join(dir, f.Name()))
}
}
}
diff --git a/src/internal/trace/parser_test.go b/src/internal/trace/parser_test.go
index 316220cfa8..cdab95a59e 100644
--- a/src/internal/trace/parser_test.go
+++ b/src/internal/trace/parser_test.go
@@ -6,7 +6,6 @@ package trace
import (
"bytes"
- "io/ioutil"
"os"
"path/filepath"
"strings"
@@ -34,19 +33,19 @@ func TestCorruptedInputs(t *testing.T) {
}
func TestParseCanned(t *testing.T) {
- files, err := ioutil.ReadDir("./testdata")
+ files, err := os.ReadDir("./testdata")
if err != nil {
t.Fatalf("failed to read ./testdata: %v", err)
}
for _, f := range files {
- name := filepath.Join("./testdata", f.Name())
- info, err := os.Stat(name)
+ info, err := f.Info()
if err != nil {
t.Fatal(err)
}
if testing.Short() && info.Size() > 10000 {
continue
}
+ name := filepath.Join("./testdata", f.Name())
data, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
diff --git a/src/os/exec/exec_test.go b/src/os/exec/exec_test.go
index 92429f63a5..8b0c93f382 100644
--- a/src/os/exec/exec_test.go
+++ b/src/os/exec/exec_test.go
@@ -15,7 +15,6 @@ import (
"internal/poll"
"internal/testenv"
"io"
- "io/ioutil"
"log"
"net"
"net/http"
@@ -386,7 +385,7 @@ func TestPipeLookPathLeak(t *testing.T) {
// Reading /proc/self/fd is more reliable than calling lsof, so try that
// first.
numOpenFDs := func() (int, []byte, error) {
- fds, err := ioutil.ReadDir("/proc/self/fd")
+ fds, err := os.ReadDir("/proc/self/fd")
if err != nil {
return 0, nil, err
}
diff --git a/src/testing/testing_test.go b/src/testing/testing_test.go
index d665a334e4..0f096980ca 100644
--- a/src/testing/testing_test.go
+++ b/src/testing/testing_test.go
@@ -5,7 +5,6 @@
package testing_test
import (
- "io/ioutil"
"os"
"path/filepath"
"testing"
@@ -102,11 +101,11 @@ func testTempDir(t *testing.T) {
if !fi.IsDir() {
t.Errorf("dir %q is not a dir", dir)
}
- fis, err := ioutil.ReadDir(dir)
+ files, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
- if len(fis) > 0 {
- t.Errorf("unexpected %d files in TempDir: %v", len(fis), fis)
+ if len(files) > 0 {
+ t.Errorf("unexpected %d files in TempDir: %v", len(files), files)
}
}
--
cgit v1.3