From a413908dd064de6e3ea5b8d95d707a532bd3f4c8 Mon Sep 17 00:00:00 2001 From: Cherry Zhang Date: Wed, 16 Sep 2020 16:59:58 -0400 Subject: all: add GOOS=ios Introduce GOOS=ios for iOS systems. GOOS=ios matches "darwin" build tag, like GOOS=android matches "linux" and GOOS=illumos matches "solaris". Only ios/arm64 is supported (ios/amd64 is not). GOOS=ios and GOOS=darwin remain essentially the same at this point. They will diverge at later time, to differentiate macOS and iOS. Uses of GOOS=="darwin" are changed to (GOOS=="darwin" || GOOS=="ios"), except if it clearly means macOS (e.g. GOOS=="darwin" && GOARCH=="amd64"), it remains GOOS=="darwin". Updates #38485. Change-Id: I4faacdc1008f42434599efb3c3ad90763a83b67c Reviewed-on: https://go-review.googlesource.com/c/go/+/254740 Trust: Cherry Zhang Run-TryBot: Cherry Zhang TryBot-Result: Go Bot Reviewed-by: Austin Clements --- src/path/filepath/path_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/path/filepath') diff --git a/src/path/filepath/path_test.go b/src/path/filepath/path_test.go index d6f680556c..ca100ff071 100644 --- a/src/path/filepath/path_test.go +++ b/src/path/filepath/path_test.go @@ -431,7 +431,7 @@ func chtmpdir(t *testing.T) (restore func()) { } func TestWalk(t *testing.T) { - if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" { + if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { restore := chtmpdir(t) defer restore() } @@ -1278,7 +1278,7 @@ func TestDriveLetterInEvalSymlinks(t *testing.T) { } func TestBug3486(t *testing.T) { // https://golang.org/issue/3486 - if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" { + if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { t.Skipf("skipping on %s/%s", runtime.GOOS, runtime.GOARCH) } root, err := filepath.EvalSymlinks(runtime.GOROOT() + "/test") -- cgit v1.3 From db428ad7b61ed757671162054252b4326045e96c Mon Sep 17 00:00:00 2001 From: Cherry Zhang Date: Thu, 17 Sep 2020 15:02:26 -0400 Subject: all: enable more tests on macOS/ARM64 Updates #38485. Change-Id: Iac96f5ffe88521fcb11eab306d0df6463bdce046 Reviewed-on: https://go-review.googlesource.com/c/go/+/256920 Trust: Cherry Zhang Reviewed-by: Dmitri Shuralyov Reviewed-by: Ian Lance Taylor --- misc/cgo/testcarchive/carchive_test.go | 2 +- src/cmd/doc/doc_test.go | 2 +- src/cmd/go/internal/work/build_test.go | 6 ++---- src/go/build/build_test.go | 4 ++-- src/log/syslog/syslog_test.go | 7 +------ src/net/dial_test.go | 2 +- src/net/platform_test.go | 2 +- src/path/filepath/path_test.go | 4 ++-- src/runtime/debug/panic_test.go | 4 ++-- src/syscall/syscall_unix_test.go | 2 +- 10 files changed, 14 insertions(+), 21 deletions(-) (limited to 'src/path/filepath') diff --git a/misc/cgo/testcarchive/carchive_test.go b/misc/cgo/testcarchive/carchive_test.go index 2e223ea369..6ed25d8948 100644 --- a/misc/cgo/testcarchive/carchive_test.go +++ b/misc/cgo/testcarchive/carchive_test.go @@ -603,7 +603,7 @@ func TestExtar(t *testing.T) { if runtime.Compiler == "gccgo" { t.Skip("skipping -extar test when using gccgo") } - if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { + if runtime.GOOS == "ios" { t.Skip("shell scripts are not executable on iOS hosts") } diff --git a/src/cmd/doc/doc_test.go b/src/cmd/doc/doc_test.go index 47602833d3..39530e3c2d 100644 --- a/src/cmd/doc/doc_test.go +++ b/src/cmd/doc/doc_test.go @@ -36,7 +36,7 @@ func TestMain(m *testing.M) { } func maybeSkip(t *testing.T) { - if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { + if runtime.GOOS == "ios" { t.Skip("iOS does not have a full file tree") } } diff --git a/src/cmd/go/internal/work/build_test.go b/src/cmd/go/internal/work/build_test.go index afed0fba72..904aee0684 100644 --- a/src/cmd/go/internal/work/build_test.go +++ b/src/cmd/go/internal/work/build_test.go @@ -221,10 +221,8 @@ func pkgImportPath(pkgpath string) *load.Package { // See https://golang.org/issue/18878. func TestRespectSetgidDir(t *testing.T) { switch runtime.GOOS { - case "darwin", "ios": - if runtime.GOARCH == "arm64" { - t.Skip("can't set SetGID bit with chmod on iOS") - } + case "ios": + t.Skip("can't set SetGID bit with chmod on iOS") case "windows", "plan9": t.Skip("chown/chmod setgid are not supported on Windows or Plan 9") } diff --git a/src/go/build/build_test.go b/src/go/build/build_test.go index 22c62ce87d..2f2e80b5a8 100644 --- a/src/go/build/build_test.go +++ b/src/go/build/build_test.go @@ -120,7 +120,7 @@ func TestMultiplePackageImport(t *testing.T) { } func TestLocalDirectory(t *testing.T) { - if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { + if runtime.GOOS == "ios" { t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH) } @@ -250,7 +250,7 @@ func TestMatchFile(t *testing.T) { } func TestImportCmd(t *testing.T) { - if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { + if runtime.GOOS == "ios" { t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH) } diff --git a/src/log/syslog/syslog_test.go b/src/log/syslog/syslog_test.go index dd2f83e04f..30abfae550 100644 --- a/src/log/syslog/syslog_test.go +++ b/src/log/syslog/syslog_test.go @@ -51,12 +51,7 @@ func testableNetwork(network string) bool { switch network { case "unix", "unixgram": switch runtime.GOOS { - case "darwin", "ios": - switch runtime.GOARCH { - case "arm64": - return false - } - case "android": + case "ios", "android": return false } } diff --git a/src/net/dial_test.go b/src/net/dial_test.go index 2706de4442..57cf5554ad 100644 --- a/src/net/dial_test.go +++ b/src/net/dial_test.go @@ -990,7 +990,7 @@ func TestDialerControl(t *testing.T) { // except that it won't skip testing on non-mobile builders. func mustHaveExternalNetwork(t *testing.T) { t.Helper() - mobile := runtime.GOOS == "android" || (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" + mobile := runtime.GOOS == "android" || runtime.GOOS == "ios" if testenv.Builder() == "" || mobile { testenv.MustHaveExternalNetwork(t) } diff --git a/src/net/platform_test.go b/src/net/platform_test.go index 4b92bb6df0..2da23dedce 100644 --- a/src/net/platform_test.go +++ b/src/net/platform_test.go @@ -82,7 +82,7 @@ func testableNetwork(network string) bool { } func iOS() bool { - return (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" + return runtime.GOOS == "ios" } // testableAddress reports whether address of network is testable on diff --git a/src/path/filepath/path_test.go b/src/path/filepath/path_test.go index ca100ff071..6a8700e413 100644 --- a/src/path/filepath/path_test.go +++ b/src/path/filepath/path_test.go @@ -431,7 +431,7 @@ func chtmpdir(t *testing.T) (restore func()) { } func TestWalk(t *testing.T) { - if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { + if runtime.GOOS == "ios" { restore := chtmpdir(t) defer restore() } @@ -1278,7 +1278,7 @@ func TestDriveLetterInEvalSymlinks(t *testing.T) { } func TestBug3486(t *testing.T) { // https://golang.org/issue/3486 - if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { + if runtime.GOOS == "ios" { t.Skipf("skipping on %s/%s", runtime.GOOS, runtime.GOARCH) } root, err := filepath.EvalSymlinks(runtime.GOROOT() + "/test") diff --git a/src/runtime/debug/panic_test.go b/src/runtime/debug/panic_test.go index 93be216985..b67a3de4f9 100644 --- a/src/runtime/debug/panic_test.go +++ b/src/runtime/debug/panic_test.go @@ -20,8 +20,8 @@ func TestPanicOnFault(t *testing.T) { if runtime.GOARCH == "s390x" { t.Skip("s390x fault addresses are missing the low order bits") } - if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { - t.Skip("darwin/arm64 doesn't provide fault addresses") + if runtime.GOOS == "ios" { + t.Skip("iOS doesn't provide fault addresses") } m, err := syscall.Mmap(-1, 0, 0x1000, syscall.PROT_READ /* Note: no PROT_WRITE */, syscall.MAP_SHARED|syscall.MAP_ANON) if err != nil { diff --git a/src/syscall/syscall_unix_test.go b/src/syscall/syscall_unix_test.go index 7e9bb0c3ac..d754c075f1 100644 --- a/src/syscall/syscall_unix_test.go +++ b/src/syscall/syscall_unix_test.go @@ -70,7 +70,7 @@ func _() { // Thus this test also verifies that the Flock_t structure can be // roundtripped with F_SETLK and F_GETLK. func TestFcntlFlock(t *testing.T) { - if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" { + if runtime.GOOS == "ios" { t.Skip("skipping; no child processes allowed on iOS") } flock := syscall.Flock_t{ -- cgit v1.3 From 7bb721b9384bdd196befeaed593b185f7f2a5589 Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Tue, 7 Jul 2020 13:49:21 -0400 Subject: all: update references to symbols moved from os to io/fs The old os 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. For #41190. Change-Id: I8f9526977867c10a221e2f392f78d7dec073f1bd Reviewed-on: https://go-review.googlesource.com/c/go/+/243907 Trust: Russ Cox Run-TryBot: Russ Cox TryBot-Result: Go Bot Reviewed-by: Rob Pike --- src/archive/tar/common.go | 68 ++++++++++---------- src/archive/tar/stat_unix.go | 4 +- src/archive/tar/tar_test.go | 19 +++--- src/archive/zip/reader_test.go | 11 ++-- src/archive/zip/struct.go | 72 +++++++++++----------- src/archive/zip/writer_test.go | 10 +-- src/cmd/doc/pkg.go | 10 +-- src/cmd/fix/main.go | 5 +- src/cmd/go/go_test.go | 7 ++- src/cmd/go/internal/cache/cache.go | 3 +- src/cmd/go/internal/fsys/fsys.go | 41 ++++++------ src/cmd/go/internal/fsys/fsys_test.go | 39 ++++++------ src/cmd/go/internal/imports/scan.go | 3 +- src/cmd/go/internal/load/pkg.go | 5 +- .../lockedfile/internal/filelock/filelock.go | 5 +- .../lockedfile/internal/filelock/filelock_fcntl.go | 6 +- .../lockedfile/internal/filelock/filelock_other.go | 6 +- .../lockedfile/internal/filelock/filelock_plan9.go | 8 +-- .../lockedfile/internal/filelock/filelock_unix.go | 4 +- .../internal/filelock/filelock_windows.go | 6 +- src/cmd/go/internal/lockedfile/lockedfile.go | 9 +-- .../go/internal/lockedfile/lockedfile_filelock.go | 3 +- src/cmd/go/internal/lockedfile/lockedfile_plan9.go | 9 +-- src/cmd/go/internal/modcmd/vendor.go | 7 ++- src/cmd/go/internal/modcmd/verify.go | 9 +-- src/cmd/go/internal/modfetch/cache.go | 7 ++- src/cmd/go/internal/modfetch/codehost/codehost.go | 9 +-- src/cmd/go/internal/modfetch/codehost/git.go | 15 ++--- src/cmd/go/internal/modfetch/codehost/git_test.go | 3 +- src/cmd/go/internal/modfetch/codehost/vcs.go | 3 +- src/cmd/go/internal/modfetch/coderepo.go | 7 ++- src/cmd/go/internal/modfetch/fetch.go | 11 ++-- src/cmd/go/internal/modfetch/proxy.go | 8 +-- src/cmd/go/internal/modfetch/repo.go | 5 +- src/cmd/go/internal/modfetch/sumdb.go | 7 ++- src/cmd/go/internal/modload/import.go | 3 +- src/cmd/go/internal/modload/load.go | 3 +- src/cmd/go/internal/modload/query.go | 11 ++-- src/cmd/go/internal/modload/search.go | 5 +- src/cmd/go/internal/modload/stat_openfile.go | 3 +- src/cmd/go/internal/modload/stat_unix.go | 3 +- src/cmd/go/internal/modload/stat_windows.go | 6 +- src/cmd/go/internal/modload/vendor.go | 4 +- src/cmd/go/internal/renameio/renameio.go | 7 ++- src/cmd/go/internal/renameio/umask_test.go | 5 +- src/cmd/go/internal/search/search.go | 7 ++- src/cmd/go/internal/test/test.go | 3 +- src/cmd/go/internal/vcs/vcs.go | 5 +- src/cmd/go/internal/version/version.go | 11 ++-- src/cmd/go/internal/web/api.go | 6 +- src/cmd/go/internal/web/file_test.go | 5 +- src/cmd/go/internal/work/build_test.go | 3 +- src/cmd/go/internal/work/exec.go | 9 +-- src/cmd/go/proxy_test.go | 5 +- src/cmd/go/script_test.go | 7 ++- src/cmd/go/testdata/addmod.go | 3 +- src/cmd/go/testdata/savedir.go | 3 +- src/cmd/gofmt/gofmt.go | 9 +-- src/cmd/gofmt/long_test.go | 3 +- src/cmd/internal/buildid/buildid.go | 9 +-- src/cmd/internal/buildid/note.go | 7 ++- src/cmd/internal/moddeps/moddeps_test.go | 3 +- src/cmd/pack/pack.go | 3 +- src/cmd/pack/pack_test.go | 11 ++-- src/compress/gzip/issue14937_test.go | 3 +- src/crypto/rand/eagain.go | 4 +- src/crypto/x509/root_unix.go | 7 ++- src/errors/errors.go | 12 ++-- src/errors/wrap.go | 4 +- src/errors/wrap_test.go | 11 ++-- src/go/build/build.go | 9 +-- src/go/build/deps_test.go | 3 +- src/go/doc/doc_test.go | 6 +- src/go/doc/headscan.go | 5 +- src/go/parser/interface.go | 6 +- src/go/parser/parser_test.go | 4 +- src/index/suffixarray/suffixarray_test.go | 4 +- src/internal/poll/error_test.go | 3 +- src/internal/reflectlite/reflect_mirror_test.go | 3 +- src/io/ioutil/ioutil.go | 5 +- src/io/ioutil/tempfile_test.go | 3 +- src/net/conf_test.go | 8 +-- src/net/dnsconfig_unix_test.go | 3 +- src/net/error_test.go | 13 ++-- src/net/http/example_filesystem_test.go | 14 ++--- src/net/http/fs.go | 9 +-- src/net/http/fs_test.go | 27 ++++---- src/net/ipsock_plan9.go | 3 +- src/os/error_test.go | 55 +++++++++-------- src/os/error_unix_test.go | 11 ++-- src/os/error_windows_test.go | 11 ++-- src/os/example_test.go | 5 +- src/os/exec/exec_plan9.go | 4 +- src/os/exec/exec_unix.go | 4 +- src/os/exec/exec_windows.go | 4 +- src/os/exec/lp_plan9.go | 3 +- src/os/exec/lp_unix.go | 3 +- src/os/exec/lp_windows.go | 5 +- src/os/os_test.go | 2 +- src/os/os_windows_test.go | 11 ++-- src/os/pipe_test.go | 17 ++--- src/os/removeall_test.go | 2 +- src/os/signal/signal_cgo_test.go | 3 +- src/os/stat_test.go | 19 +++--- src/path/filepath/example_unix_walk_test.go | 3 +- src/path/filepath/path.go | 7 ++- src/path/filepath/path_test.go | 15 ++--- src/path/filepath/path_windows_test.go | 3 +- src/path/filepath/symlink.go | 3 +- src/runtime/testdata/testprogcgo/exec.go | 3 +- src/syscall/syscall_js.go | 2 +- src/syscall/syscall_linux_test.go | 3 +- src/syscall/syscall_plan9.go | 2 +- src/syscall/syscall_unix.go | 2 +- src/syscall/syscall_windows.go | 2 +- 115 files changed, 529 insertions(+), 450 deletions(-) (limited to 'src/path/filepath') diff --git a/src/archive/tar/common.go b/src/archive/tar/common.go index dee9e47e4a..c667cfc872 100644 --- a/src/archive/tar/common.go +++ b/src/archive/tar/common.go @@ -13,8 +13,8 @@ package tar import ( "errors" "fmt" + "io/fs" "math" - "os" "path" "reflect" "strconv" @@ -525,12 +525,12 @@ func (h Header) allowedFormats() (format Format, paxHdrs map[string]string, err return format, paxHdrs, err } -// FileInfo returns an os.FileInfo for the Header. -func (h *Header) FileInfo() os.FileInfo { +// FileInfo returns an fs.FileInfo for the Header. +func (h *Header) FileInfo() fs.FileInfo { return headerFileInfo{h} } -// headerFileInfo implements os.FileInfo. +// headerFileInfo implements fs.FileInfo. type headerFileInfo struct { h *Header } @@ -549,57 +549,57 @@ func (fi headerFileInfo) Name() string { } // Mode returns the permission and mode bits for the headerFileInfo. -func (fi headerFileInfo) Mode() (mode os.FileMode) { +func (fi headerFileInfo) Mode() (mode fs.FileMode) { // Set file permission bits. - mode = os.FileMode(fi.h.Mode).Perm() + mode = fs.FileMode(fi.h.Mode).Perm() // Set setuid, setgid and sticky bits. if fi.h.Mode&c_ISUID != 0 { - mode |= os.ModeSetuid + mode |= fs.ModeSetuid } if fi.h.Mode&c_ISGID != 0 { - mode |= os.ModeSetgid + mode |= fs.ModeSetgid } if fi.h.Mode&c_ISVTX != 0 { - mode |= os.ModeSticky + mode |= fs.ModeSticky } // Set file mode bits; clear perm, setuid, setgid, and sticky bits. - switch m := os.FileMode(fi.h.Mode) &^ 07777; m { + switch m := fs.FileMode(fi.h.Mode) &^ 07777; m { case c_ISDIR: - mode |= os.ModeDir + mode |= fs.ModeDir case c_ISFIFO: - mode |= os.ModeNamedPipe + mode |= fs.ModeNamedPipe case c_ISLNK: - mode |= os.ModeSymlink + mode |= fs.ModeSymlink case c_ISBLK: - mode |= os.ModeDevice + mode |= fs.ModeDevice case c_ISCHR: - mode |= os.ModeDevice - mode |= os.ModeCharDevice + mode |= fs.ModeDevice + mode |= fs.ModeCharDevice case c_ISSOCK: - mode |= os.ModeSocket + mode |= fs.ModeSocket } switch fi.h.Typeflag { case TypeSymlink: - mode |= os.ModeSymlink + mode |= fs.ModeSymlink case TypeChar: - mode |= os.ModeDevice - mode |= os.ModeCharDevice + mode |= fs.ModeDevice + mode |= fs.ModeCharDevice case TypeBlock: - mode |= os.ModeDevice + mode |= fs.ModeDevice case TypeDir: - mode |= os.ModeDir + mode |= fs.ModeDir case TypeFifo: - mode |= os.ModeNamedPipe + mode |= fs.ModeNamedPipe } return mode } // sysStat, if non-nil, populates h from system-dependent fields of fi. -var sysStat func(fi os.FileInfo, h *Header) error +var sysStat func(fi fs.FileInfo, h *Header) error const ( // Mode constants from the USTAR spec: @@ -623,10 +623,10 @@ const ( // If fi describes a symlink, FileInfoHeader records link as the link target. // If fi describes a directory, a slash is appended to the name. // -// Since os.FileInfo's Name method only returns the base name of +// Since fs.FileInfo's Name method only returns the base name of // the file it describes, it may be necessary to modify Header.Name // to provide the full path name of the file. -func FileInfoHeader(fi os.FileInfo, link string) (*Header, error) { +func FileInfoHeader(fi fs.FileInfo, link string) (*Header, error) { if fi == nil { return nil, errors.New("archive/tar: FileInfo is nil") } @@ -643,29 +643,29 @@ func FileInfoHeader(fi os.FileInfo, link string) (*Header, error) { case fi.IsDir(): h.Typeflag = TypeDir h.Name += "/" - case fm&os.ModeSymlink != 0: + case fm&fs.ModeSymlink != 0: h.Typeflag = TypeSymlink h.Linkname = link - case fm&os.ModeDevice != 0: - if fm&os.ModeCharDevice != 0 { + case fm&fs.ModeDevice != 0: + if fm&fs.ModeCharDevice != 0 { h.Typeflag = TypeChar } else { h.Typeflag = TypeBlock } - case fm&os.ModeNamedPipe != 0: + case fm&fs.ModeNamedPipe != 0: h.Typeflag = TypeFifo - case fm&os.ModeSocket != 0: + case fm&fs.ModeSocket != 0: return nil, fmt.Errorf("archive/tar: sockets not supported") default: return nil, fmt.Errorf("archive/tar: unknown file mode %v", fm) } - if fm&os.ModeSetuid != 0 { + if fm&fs.ModeSetuid != 0 { h.Mode |= c_ISUID } - if fm&os.ModeSetgid != 0 { + if fm&fs.ModeSetgid != 0 { h.Mode |= c_ISGID } - if fm&os.ModeSticky != 0 { + if fm&fs.ModeSticky != 0 { h.Mode |= c_ISVTX } // If possible, populate additional fields from OS-specific diff --git a/src/archive/tar/stat_unix.go b/src/archive/tar/stat_unix.go index 8df3616990..581d87dca9 100644 --- a/src/archive/tar/stat_unix.go +++ b/src/archive/tar/stat_unix.go @@ -7,7 +7,7 @@ package tar import ( - "os" + "io/fs" "os/user" "runtime" "strconv" @@ -23,7 +23,7 @@ func init() { // The downside is that renaming uname or gname by the OS never takes effect. var userMap, groupMap sync.Map // map[int]string -func statUnix(fi os.FileInfo, h *Header) error { +func statUnix(fi fs.FileInfo, h *Header) error { sys, ok := fi.Sys().(*syscall.Stat_t) if !ok { return nil diff --git a/src/archive/tar/tar_test.go b/src/archive/tar/tar_test.go index 2676853122..f605dae904 100644 --- a/src/archive/tar/tar_test.go +++ b/src/archive/tar/tar_test.go @@ -10,6 +10,7 @@ import ( "fmt" "internal/testenv" "io" + "io/fs" "io/ioutil" "math" "os" @@ -338,7 +339,7 @@ func TestRoundTrip(t *testing.T) { type headerRoundTripTest struct { h *Header - fm os.FileMode + fm fs.FileMode } func TestHeaderRoundTrip(t *testing.T) { @@ -361,7 +362,7 @@ func TestHeaderRoundTrip(t *testing.T) { ModTime: time.Unix(1360600852, 0), Typeflag: TypeSymlink, }, - fm: 0777 | os.ModeSymlink, + fm: 0777 | fs.ModeSymlink, }, { // character device node. h: &Header{ @@ -371,7 +372,7 @@ func TestHeaderRoundTrip(t *testing.T) { ModTime: time.Unix(1360578951, 0), Typeflag: TypeChar, }, - fm: 0666 | os.ModeDevice | os.ModeCharDevice, + fm: 0666 | fs.ModeDevice | fs.ModeCharDevice, }, { // block device node. h: &Header{ @@ -381,7 +382,7 @@ func TestHeaderRoundTrip(t *testing.T) { ModTime: time.Unix(1360578954, 0), Typeflag: TypeBlock, }, - fm: 0660 | os.ModeDevice, + fm: 0660 | fs.ModeDevice, }, { // directory. h: &Header{ @@ -391,7 +392,7 @@ func TestHeaderRoundTrip(t *testing.T) { ModTime: time.Unix(1360601116, 0), Typeflag: TypeDir, }, - fm: 0755 | os.ModeDir, + fm: 0755 | fs.ModeDir, }, { // fifo node. h: &Header{ @@ -401,7 +402,7 @@ func TestHeaderRoundTrip(t *testing.T) { ModTime: time.Unix(1360578949, 0), Typeflag: TypeFifo, }, - fm: 0600 | os.ModeNamedPipe, + fm: 0600 | fs.ModeNamedPipe, }, { // setuid. h: &Header{ @@ -411,7 +412,7 @@ func TestHeaderRoundTrip(t *testing.T) { ModTime: time.Unix(1355405093, 0), Typeflag: TypeReg, }, - fm: 0755 | os.ModeSetuid, + fm: 0755 | fs.ModeSetuid, }, { // setguid. h: &Header{ @@ -421,7 +422,7 @@ func TestHeaderRoundTrip(t *testing.T) { ModTime: time.Unix(1360602346, 0), Typeflag: TypeReg, }, - fm: 0750 | os.ModeSetgid, + fm: 0750 | fs.ModeSetgid, }, { // sticky. h: &Header{ @@ -431,7 +432,7 @@ func TestHeaderRoundTrip(t *testing.T) { ModTime: time.Unix(1360602540, 0), Typeflag: TypeReg, }, - fm: 0600 | os.ModeSticky, + fm: 0600 | fs.ModeSticky, }, { // hard link. h: &Header{ diff --git a/src/archive/zip/reader_test.go b/src/archive/zip/reader_test.go index adca87a8b3..8a32d9c7dc 100644 --- a/src/archive/zip/reader_test.go +++ b/src/archive/zip/reader_test.go @@ -10,6 +10,7 @@ import ( "encoding/hex" "internal/obscuretestdata" "io" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -30,7 +31,7 @@ type ZipTest struct { type ZipTestFile struct { Name string - Mode os.FileMode + Mode fs.FileMode NonUTF8 bool ModTime time.Time Modified time.Time @@ -107,7 +108,7 @@ var tests = []ZipTest{ Name: "symlink", Content: []byte("../target"), Modified: time.Date(2012, 2, 3, 19, 56, 48, 0, timeZone(-2*time.Hour)), - Mode: 0777 | os.ModeSymlink, + Mode: 0777 | fs.ModeSymlink, }, }, }, @@ -149,7 +150,7 @@ var tests = []ZipTest{ Name: "dir/empty/", Content: []byte{}, Modified: time.Date(2011, 12, 8, 10, 8, 6, 0, time.UTC), - Mode: os.ModeDir | 0777, + Mode: fs.ModeDir | 0777, }, { Name: "readonly", @@ -179,7 +180,7 @@ var tests = []ZipTest{ Name: "dir/empty/", Content: []byte{}, Modified: time.Date(2011, 12, 8, 10, 8, 6, 0, timeZone(0)), - Mode: os.ModeDir | 0777, + Mode: fs.ModeDir | 0777, }, { Name: "readonly", @@ -645,7 +646,7 @@ func readTestFile(t *testing.T, zt ZipTest, ft ZipTestFile, f *File) { } } -func testFileMode(t *testing.T, f *File, want os.FileMode) { +func testFileMode(t *testing.T, f *File, want fs.FileMode) { mode := f.Mode() if want == 0 { t.Errorf("%s mode: got %v, want none", f.Name, mode) diff --git a/src/archive/zip/struct.go b/src/archive/zip/struct.go index 686e79781a..355c57051b 100644 --- a/src/archive/zip/struct.go +++ b/src/archive/zip/struct.go @@ -20,7 +20,7 @@ fields must be used instead. package zip import ( - "os" + "io/fs" "path" "time" ) @@ -137,12 +137,12 @@ type FileHeader struct { ExternalAttrs uint32 // Meaning depends on CreatorVersion } -// FileInfo returns an os.FileInfo for the FileHeader. -func (h *FileHeader) FileInfo() os.FileInfo { +// FileInfo returns an fs.FileInfo for the FileHeader. +func (h *FileHeader) FileInfo() fs.FileInfo { return headerFileInfo{h} } -// headerFileInfo implements os.FileInfo. +// headerFileInfo implements fs.FileInfo. type headerFileInfo struct { fh *FileHeader } @@ -161,17 +161,17 @@ func (fi headerFileInfo) ModTime() time.Time { } return fi.fh.Modified.UTC() } -func (fi headerFileInfo) Mode() os.FileMode { return fi.fh.Mode() } +func (fi headerFileInfo) Mode() fs.FileMode { return fi.fh.Mode() } func (fi headerFileInfo) Sys() interface{} { return fi.fh } // FileInfoHeader creates a partially-populated FileHeader from an -// os.FileInfo. -// Because os.FileInfo's Name method returns only the base name of +// fs.FileInfo. +// Because fs.FileInfo's Name method returns only the base name of // the file it describes, it may be necessary to modify the Name field // of the returned header to provide the full path name of the file. // If compression is desired, callers should set the FileHeader.Method // field; it is unset by default. -func FileInfoHeader(fi os.FileInfo) (*FileHeader, error) { +func FileInfoHeader(fi fs.FileInfo) (*FileHeader, error) { size := fi.Size() fh := &FileHeader{ Name: fi.Name(), @@ -280,7 +280,7 @@ const ( ) // Mode returns the permission and mode bits for the FileHeader. -func (h *FileHeader) Mode() (mode os.FileMode) { +func (h *FileHeader) Mode() (mode fs.FileMode) { switch h.CreatorVersion >> 8 { case creatorUnix, creatorMacOSX: mode = unixModeToFileMode(h.ExternalAttrs >> 16) @@ -288,18 +288,18 @@ func (h *FileHeader) Mode() (mode os.FileMode) { mode = msdosModeToFileMode(h.ExternalAttrs) } if len(h.Name) > 0 && h.Name[len(h.Name)-1] == '/' { - mode |= os.ModeDir + mode |= fs.ModeDir } return mode } // SetMode changes the permission and mode bits for the FileHeader. -func (h *FileHeader) SetMode(mode os.FileMode) { +func (h *FileHeader) SetMode(mode fs.FileMode) { h.CreatorVersion = h.CreatorVersion&0xff | creatorUnix<<8 h.ExternalAttrs = fileModeToUnixMode(mode) << 16 // set MSDOS attributes too, as the original zip does. - if mode&os.ModeDir != 0 { + if mode&fs.ModeDir != 0 { h.ExternalAttrs |= msdosDir } if mode&0200 == 0 { @@ -312,9 +312,9 @@ func (h *FileHeader) isZip64() bool { return h.CompressedSize64 >= uint32max || h.UncompressedSize64 >= uint32max } -func msdosModeToFileMode(m uint32) (mode os.FileMode) { +func msdosModeToFileMode(m uint32) (mode fs.FileMode) { if m&msdosDir != 0 { - mode = os.ModeDir | 0777 + mode = fs.ModeDir | 0777 } else { mode = 0666 } @@ -324,64 +324,64 @@ func msdosModeToFileMode(m uint32) (mode os.FileMode) { return mode } -func fileModeToUnixMode(mode os.FileMode) uint32 { +func fileModeToUnixMode(mode fs.FileMode) uint32 { var m uint32 - switch mode & os.ModeType { + switch mode & fs.ModeType { default: m = s_IFREG - case os.ModeDir: + case fs.ModeDir: m = s_IFDIR - case os.ModeSymlink: + case fs.ModeSymlink: m = s_IFLNK - case os.ModeNamedPipe: + case fs.ModeNamedPipe: m = s_IFIFO - case os.ModeSocket: + case fs.ModeSocket: m = s_IFSOCK - case os.ModeDevice: - if mode&os.ModeCharDevice != 0 { + case fs.ModeDevice: + if mode&fs.ModeCharDevice != 0 { m = s_IFCHR } else { m = s_IFBLK } } - if mode&os.ModeSetuid != 0 { + if mode&fs.ModeSetuid != 0 { m |= s_ISUID } - if mode&os.ModeSetgid != 0 { + if mode&fs.ModeSetgid != 0 { m |= s_ISGID } - if mode&os.ModeSticky != 0 { + if mode&fs.ModeSticky != 0 { m |= s_ISVTX } return m | uint32(mode&0777) } -func unixModeToFileMode(m uint32) os.FileMode { - mode := os.FileMode(m & 0777) +func unixModeToFileMode(m uint32) fs.FileMode { + mode := fs.FileMode(m & 0777) switch m & s_IFMT { case s_IFBLK: - mode |= os.ModeDevice + mode |= fs.ModeDevice case s_IFCHR: - mode |= os.ModeDevice | os.ModeCharDevice + mode |= fs.ModeDevice | fs.ModeCharDevice case s_IFDIR: - mode |= os.ModeDir + mode |= fs.ModeDir case s_IFIFO: - mode |= os.ModeNamedPipe + mode |= fs.ModeNamedPipe case s_IFLNK: - mode |= os.ModeSymlink + mode |= fs.ModeSymlink case s_IFREG: // nothing to do case s_IFSOCK: - mode |= os.ModeSocket + mode |= fs.ModeSocket } if m&s_ISGID != 0 { - mode |= os.ModeSetgid + mode |= fs.ModeSetgid } if m&s_ISUID != 0 { - mode |= os.ModeSetuid + mode |= fs.ModeSetuid } if m&s_ISVTX != 0 { - mode |= os.ModeSticky + mode |= fs.ModeSticky } return mode } diff --git a/src/archive/zip/writer_test.go b/src/archive/zip/writer_test.go index 1fedfd85e8..282f9ec216 100644 --- a/src/archive/zip/writer_test.go +++ b/src/archive/zip/writer_test.go @@ -9,9 +9,9 @@ import ( "encoding/binary" "fmt" "io" + "io/fs" "io/ioutil" "math/rand" - "os" "strings" "testing" "time" @@ -23,7 +23,7 @@ type WriteTest struct { Name string Data []byte Method uint16 - Mode os.FileMode + Mode fs.FileMode } var writeTests = []WriteTest{ @@ -43,19 +43,19 @@ var writeTests = []WriteTest{ Name: "setuid", Data: []byte("setuid file"), Method: Deflate, - Mode: 0755 | os.ModeSetuid, + Mode: 0755 | fs.ModeSetuid, }, { Name: "setgid", Data: []byte("setgid file"), Method: Deflate, - Mode: 0755 | os.ModeSetgid, + Mode: 0755 | fs.ModeSetgid, }, { Name: "symlink", Data: []byte("../link/target"), Method: Deflate, - Mode: 0755 | os.ModeSymlink, + Mode: 0755 | fs.ModeSymlink, }, } diff --git a/src/cmd/doc/pkg.go b/src/cmd/doc/pkg.go index ffc302c78c..c2e06ebc8b 100644 --- a/src/cmd/doc/pkg.go +++ b/src/cmd/doc/pkg.go @@ -16,8 +16,8 @@ import ( "go/printer" "go/token" "io" + "io/fs" "log" - "os" "path/filepath" "strings" "unicode" @@ -129,11 +129,10 @@ func (pkg *Package) Fatalf(format string, args ...interface{}) { // parsePackage turns the build package we found into a parsed package // we can then use to generate documentation. func parsePackage(writer io.Writer, pkg *build.Package, userPath string) *Package { - fs := token.NewFileSet() // include tells parser.ParseDir which files to include. // That means the file must be in the build package's GoFiles or CgoFiles // list only (no tag-ignored files, tests, swig or other non-Go files). - include := func(info os.FileInfo) bool { + include := func(info fs.FileInfo) bool { for _, name := range pkg.GoFiles { if name == info.Name() { return true @@ -146,7 +145,8 @@ func parsePackage(writer io.Writer, pkg *build.Package, userPath string) *Packag } return false } - pkgs, err := parser.ParseDir(fs, pkg.Dir, include, parser.ParseComments) + fset := token.NewFileSet() + pkgs, err := parser.ParseDir(fset, pkg.Dir, include, parser.ParseComments) if err != nil { log.Fatal(err) } @@ -203,7 +203,7 @@ func parsePackage(writer io.Writer, pkg *build.Package, userPath string) *Packag typedValue: typedValue, constructor: constructor, build: pkg, - fs: fs, + fs: fset, } p.buf.pkg = p return p diff --git a/src/cmd/fix/main.go b/src/cmd/fix/main.go index d19dde6b4a..dfba902f48 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/fs" "io/ioutil" "os" "path/filepath" @@ -235,7 +236,7 @@ func walkDir(path string) { filepath.Walk(path, visitFile) } -func visitFile(path string, f os.FileInfo, err error) error { +func visitFile(path string, f fs.FileInfo, err error) error { if err == nil && isGoFile(f) { err = processFile(path, false) } @@ -245,7 +246,7 @@ func visitFile(path string, f os.FileInfo, err error) error { return nil } -func isGoFile(f os.FileInfo) bool { +func isGoFile(f fs.FileInfo) bool { // ignore non-Go files name := f.Name() return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") diff --git a/src/cmd/go/go_test.go b/src/cmd/go/go_test.go index 093ea2ffa1..2c11d16959 100644 --- a/src/cmd/go/go_test.go +++ b/src/cmd/go/go_test.go @@ -15,6 +15,7 @@ import ( "internal/race" "internal/testenv" "io" + "io/fs" "io/ioutil" "log" "os" @@ -813,7 +814,7 @@ func (tg *testgoData) cleanup() { func removeAll(dir string) error { // module cache has 0444 directories; // make them writable in order to remove content. - filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error { // chmod not only directories, but also things that we couldn't even stat // due to permission errors: they may also be unreadable directories. if err != nil || info.IsDir() { @@ -860,7 +861,7 @@ func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) { srcdir := filepath.Join(testGOROOT, copydir) tg.tempDir(filepath.Join("goroot", copydir)) err := filepath.Walk(srcdir, - func(path string, info os.FileInfo, err error) error { + func(path string, info fs.FileInfo, err error) error { if err != nil { return err } @@ -2018,7 +2019,7 @@ func main() { tg.run("build", "-o", exe, "p") } -func copyFile(src, dst string, perm os.FileMode) error { +func copyFile(src, dst string, perm fs.FileMode) error { sf, err := os.Open(src) if err != nil { return err diff --git a/src/cmd/go/internal/cache/cache.go b/src/cmd/go/internal/cache/cache.go index 15545ac31f..5464fe5685 100644 --- a/src/cmd/go/internal/cache/cache.go +++ b/src/cmd/go/internal/cache/cache.go @@ -12,6 +12,7 @@ import ( "errors" "fmt" "io" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -54,7 +55,7 @@ func Open(dir string) (*Cache, error) { return nil, err } if !info.IsDir() { - return nil, &os.PathError{Op: "open", Path: dir, Err: fmt.Errorf("not a directory")} + return nil, &fs.PathError{Op: "open", Path: dir, Err: fmt.Errorf("not a directory")} } for i := 0; i < 256; i++ { name := filepath.Join(dir, fmt.Sprintf("%02x", i)) diff --git a/src/cmd/go/internal/fsys/fsys.go b/src/cmd/go/internal/fsys/fsys.go index 489af93496..67359ffb6d 100644 --- a/src/cmd/go/internal/fsys/fsys.go +++ b/src/cmd/go/internal/fsys/fsys.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -240,7 +241,7 @@ var errNotDir = errors.New("not a directory") // readDir reads a dir on disk, returning an error that is errNotDir if the dir is not a directory. // Unfortunately, the error returned by ioutil.ReadDir if dir is not a directory // can vary depending on the OS (Linux, Mac, Windows return ENOTDIR; BSD returns EINVAL). -func readDir(dir string) ([]os.FileInfo, error) { +func readDir(dir string) ([]fs.FileInfo, error) { fis, err := ioutil.ReadDir(dir) if err == nil { return fis, nil @@ -249,25 +250,25 @@ func readDir(dir string) ([]os.FileInfo, error) { if os.IsNotExist(err) { return nil, err } else if dirfi, staterr := os.Stat(dir); staterr == nil && !dirfi.IsDir() { - return nil, &os.PathError{Op: "ReadDir", Path: dir, Err: errNotDir} + return nil, &fs.PathError{Op: "ReadDir", Path: dir, Err: errNotDir} } else { return nil, err } } -// ReadDir provides a slice of os.FileInfo entries corresponding +// ReadDir provides a slice of fs.FileInfo entries corresponding // to the overlaid files in the directory. -func ReadDir(dir string) ([]os.FileInfo, error) { +func ReadDir(dir string) ([]fs.FileInfo, error) { dir = canonicalize(dir) if _, ok := parentIsOverlayFile(dir); ok { - return nil, &os.PathError{Op: "ReadDir", Path: dir, Err: errNotDir} + return nil, &fs.PathError{Op: "ReadDir", Path: dir, Err: errNotDir} } dirNode := overlay[dir] if dirNode == nil { return readDir(dir) } else if dirNode.isDeleted() { - return nil, &os.PathError{Op: "ReadDir", Path: dir, Err: os.ErrNotExist} + return nil, &fs.PathError{Op: "ReadDir", Path: dir, Err: fs.ErrNotExist} } diskfis, err := readDir(dir) if err != nil && !os.IsNotExist(err) && !errors.Is(err, errNotDir) { @@ -275,7 +276,7 @@ func ReadDir(dir string) ([]os.FileInfo, error) { } // Stat files in overlay to make composite list of fileinfos - files := make(map[string]os.FileInfo) + files := make(map[string]fs.FileInfo) for _, f := range diskfis { files[f.Name()] = f } @@ -327,14 +328,14 @@ func Open(path string) (*os.File, error) { cpath := canonicalize(path) if node, ok := overlay[cpath]; ok { if node.isDir() { - return nil, &os.PathError{Op: "Open", Path: path, Err: errors.New("fsys.Open doesn't support opening directories yet")} + return nil, &fs.PathError{Op: "Open", Path: path, Err: errors.New("fsys.Open doesn't support opening directories yet")} } return os.Open(node.actualFilePath) } else if parent, ok := parentIsOverlayFile(filepath.Dir(cpath)); ok { // The file is deleted explicitly in the Replace map, // or implicitly because one of its parent directories was // replaced by a file. - return nil, &os.PathError{ + return nil, &fs.PathError{ Op: "Open", Path: path, Err: fmt.Errorf("file %s does not exist: parent directory %s is replaced by a file in overlay", path, parent)} @@ -387,7 +388,7 @@ func IsDirWithGoFiles(dir string) (bool, error) { // walk recursively descends path, calling walkFn. Copied, with some // modifications from path/filepath.walk. -func walk(path string, info os.FileInfo, walkFn filepath.WalkFunc) error { +func walk(path string, info fs.FileInfo, walkFn filepath.WalkFunc) error { if !info.IsDir() { return walkFn(path, info, nil) } @@ -432,11 +433,11 @@ func Walk(root string, walkFn filepath.WalkFunc) error { } // lstat implements a version of os.Lstat that operates on the overlay filesystem. -func lstat(path string) (os.FileInfo, error) { +func lstat(path string) (fs.FileInfo, error) { cpath := canonicalize(path) if _, ok := parentIsOverlayFile(filepath.Dir(cpath)); ok { - return nil, &os.PathError{Op: "lstat", Path: cpath, Err: os.ErrNotExist} + return nil, &fs.PathError{Op: "lstat", Path: cpath, Err: fs.ErrNotExist} } node, ok := overlay[cpath] @@ -447,7 +448,7 @@ func lstat(path string) (os.FileInfo, error) { switch { case node.isDeleted(): - return nil, &os.PathError{Op: "lstat", Path: cpath, Err: os.ErrNotExist} + return nil, &fs.PathError{Op: "lstat", Path: cpath, Err: fs.ErrNotExist} case node.isDir(): return fakeDir(filepath.Base(cpath)), nil default: @@ -459,22 +460,22 @@ func lstat(path string) (os.FileInfo, error) { } } -// fakeFile provides an os.FileInfo implementation for an overlaid file, +// fakeFile provides an fs.FileInfo implementation for an overlaid file, // so that the file has the name of the overlaid file, but takes all // other characteristics of the replacement file. type fakeFile struct { name string - real os.FileInfo + real fs.FileInfo } func (f fakeFile) Name() string { return f.name } func (f fakeFile) Size() int64 { return f.real.Size() } -func (f fakeFile) Mode() os.FileMode { return f.real.Mode() } +func (f fakeFile) Mode() fs.FileMode { return f.real.Mode() } func (f fakeFile) ModTime() time.Time { return f.real.ModTime() } func (f fakeFile) IsDir() bool { return f.real.IsDir() } func (f fakeFile) Sys() interface{} { return f.real.Sys() } -// missingFile provides an os.FileInfo for an overlaid file where the +// missingFile provides an fs.FileInfo for an overlaid file where the // destination file in the overlay doesn't exist. It returns zero values // for the fileInfo methods other than Name, set to the file's name, and Mode // set to ModeIrregular. @@ -482,19 +483,19 @@ type missingFile string func (f missingFile) Name() string { return string(f) } func (f missingFile) Size() int64 { return 0 } -func (f missingFile) Mode() os.FileMode { return os.ModeIrregular } +func (f missingFile) Mode() fs.FileMode { return fs.ModeIrregular } func (f missingFile) ModTime() time.Time { return time.Unix(0, 0) } func (f missingFile) IsDir() bool { return false } func (f missingFile) Sys() interface{} { return nil } -// fakeDir provides an os.FileInfo implementation for directories that are +// fakeDir provides an fs.FileInfo implementation for directories that are // implicitly created by overlaid files. Each directory in the // path of an overlaid file is considered to exist in the overlay filesystem. type fakeDir string func (f fakeDir) Name() string { return string(f) } func (f fakeDir) Size() int64 { return 0 } -func (f fakeDir) Mode() os.FileMode { return os.ModeDir | 0500 } +func (f fakeDir) Mode() fs.FileMode { return fs.ModeDir | 0500 } func (f fakeDir) ModTime() time.Time { return time.Unix(0, 0) } func (f fakeDir) IsDir() bool { return true } func (f fakeDir) Sys() interface{} { return nil } diff --git a/src/cmd/go/internal/fsys/fsys_test.go b/src/cmd/go/internal/fsys/fsys_test.go index 6cf59fba47..ba9f05d00b 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/fs" "io/ioutil" "os" "path/filepath" @@ -291,8 +292,8 @@ x _, gotErr := ReadDir(dir) if gotErr == nil { t.Errorf("ReadDir(%q): got no error, want error", dir) - } else if _, ok := gotErr.(*os.PathError); !ok { - t.Errorf("ReadDir(%q): got error with string %q and type %T, want os.PathError", dir, gotErr.Error(), gotErr) + } else if _, ok := gotErr.(*fs.PathError); !ok { + t.Errorf("ReadDir(%q): got error with string %q and type %T, want fs.PathError", dir, gotErr.Error(), gotErr) } } } @@ -489,7 +490,7 @@ func TestWalk(t *testing.T) { path string name string size int64 - mode os.FileMode + mode fs.FileMode isDir bool } testCases := []struct { @@ -504,7 +505,7 @@ func TestWalk(t *testing.T) { `, ".", []file{ - {".", "root", 0, os.ModeDir | 0700, true}, + {".", "root", 0, fs.ModeDir | 0700, true}, {"file.txt", "file.txt", 0, 0600, false}, }, }, @@ -520,7 +521,7 @@ contents of other file `, ".", []file{ - {".", "root", 0, os.ModeDir | 0500, true}, + {".", "root", 0, fs.ModeDir | 0500, true}, {"file.txt", "file.txt", 23, 0600, false}, {"other.txt", "other.txt", 23, 0600, false}, }, @@ -536,7 +537,7 @@ contents of other file `, ".", []file{ - {".", "root", 0, os.ModeDir | 0500, true}, + {".", "root", 0, fs.ModeDir | 0500, true}, {"file.txt", "file.txt", 23, 0600, false}, {"other.txt", "other.txt", 23, 0600, false}, }, @@ -552,8 +553,8 @@ contents of other file `, ".", []file{ - {".", "root", 0, os.ModeDir | 0500, true}, - {"dir", "dir", 0, os.ModeDir | 0500, true}, + {".", "root", 0, fs.ModeDir | 0500, true}, + {"dir", "dir", 0, fs.ModeDir | 0500, true}, {"dir" + string(filepath.Separator) + "file.txt", "file.txt", 23, 0600, false}, {"other.txt", "other.txt", 23, 0600, false}, }, @@ -565,7 +566,7 @@ contents of other file initOverlay(t, tc.overlay) var got []file - Walk(tc.root, func(path string, info os.FileInfo, err error) error { + Walk(tc.root, func(path string, info fs.FileInfo, err error) error { got = append(got, file{path, info.Name(), info.Size(), info.Mode(), info.IsDir()}) return nil }) @@ -580,8 +581,8 @@ contents of other file if got[i].name != tc.wantFiles[i].name { t.Errorf("name of file #%v in walk, got %q, want %q", i, got[i].name, tc.wantFiles[i].name) } - if got[i].mode&(os.ModeDir|0700) != tc.wantFiles[i].mode { - t.Errorf("mode&(os.ModeDir|0700) for mode of file #%v in walk, got %v, want %v", i, got[i].mode&(os.ModeDir|0700), tc.wantFiles[i].mode) + if got[i].mode&(fs.ModeDir|0700) != tc.wantFiles[i].mode { + t.Errorf("mode&(fs.ModeDir|0700) for mode of file #%v in walk, got %v, want %v", i, got[i].mode&(fs.ModeDir|0700), tc.wantFiles[i].mode) } if got[i].isDir != tc.wantFiles[i].isDir { t.Errorf("isDir for file #%v in walk, got %v, want %v", i, got[i].isDir, tc.wantFiles[i].isDir) @@ -610,7 +611,7 @@ func TestWalk_SkipDir(t *testing.T) { `) var seen []string - Walk(".", func(path string, info os.FileInfo, err error) error { + Walk(".", func(path string, info fs.FileInfo, err error) error { seen = append(seen, path) if path == "skipthisdir" || path == filepath.Join("dontskip", "skip") { return filepath.SkipDir @@ -635,7 +636,7 @@ func TestWalk_Error(t *testing.T) { initOverlay(t, "{}") alreadyCalled := false - err := Walk("foo", func(path string, info os.FileInfo, err error) error { + err := Walk("foo", func(path string, info fs.FileInfo, err error) error { if alreadyCalled { t.Fatal("expected walk function to be called exactly once, but it was called more than once") } @@ -683,7 +684,7 @@ func TestWalk_Symlink(t *testing.T) { t.Run(tc.name, func(t *testing.T) { var got []string - err := Walk(tc.dir, func(path string, info os.FileInfo, err error) error { + err := Walk(tc.dir, func(path string, info fs.FileInfo, err error) error { got = append(got, path) if err != nil { t.Errorf("walkfn: got non nil err argument: %v, want nil err argument", err) @@ -706,7 +707,7 @@ func TestLstat(t *testing.T) { type file struct { name string size int64 - mode os.FileMode // mode & (os.ModeDir|0x700): only check 'user' permissions + mode fs.FileMode // mode & (fs.ModeDir|0x700): only check 'user' permissions isDir bool } @@ -771,7 +772,7 @@ contents`, -- dir/foo.txt -- `, "dir", - file{"dir", 0, 0700 | os.ModeDir, true}, + file{"dir", 0, 0700 | fs.ModeDir, true}, false, }, { @@ -780,7 +781,7 @@ contents`, -- dummy.txt -- `, "dir", - file{"dir", 0, 0500 | os.ModeDir, true}, + file{"dir", 0, 0500 | fs.ModeDir, true}, false, }, } @@ -801,8 +802,8 @@ contents`, if got.Name() != tc.want.name { t.Errorf("lstat(%q).Name(): got %q, want %q", tc.path, got.Name(), tc.want.name) } - if got.Mode()&(os.ModeDir|0700) != tc.want.mode { - t.Errorf("lstat(%q).Mode()&(os.ModeDir|0700): got %v, want %v", tc.path, got.Mode()&(os.ModeDir|0700), tc.want.mode) + if got.Mode()&(fs.ModeDir|0700) != tc.want.mode { + t.Errorf("lstat(%q).Mode()&(fs.ModeDir|0700): got %v, want %v", tc.path, got.Mode()&(fs.ModeDir|0700), tc.want.mode) } if got.IsDir() != tc.want.isDir { t.Errorf("lstat(%q).IsDir(): got %v, want %v", tc.path, got.IsDir(), tc.want.isDir) diff --git a/src/cmd/go/internal/imports/scan.go b/src/cmd/go/internal/imports/scan.go index 42ee49aaaa..d45393f36c 100644 --- a/src/cmd/go/internal/imports/scan.go +++ b/src/cmd/go/internal/imports/scan.go @@ -6,6 +6,7 @@ package imports import ( "fmt" + "io/fs" "os" "path/filepath" "sort" @@ -26,7 +27,7 @@ func ScanDir(dir string, tags map[string]bool) ([]string, []string, error) { // If the directory entry is a symlink, stat it to obtain the info for the // link target instead of the link itself. - if info.Mode()&os.ModeSymlink != 0 { + if info.Mode()&fs.ModeSymlink != 0 { info, err = os.Stat(filepath.Join(dir, name)) if err != nil { continue // Ignore broken symlinks. diff --git a/src/cmd/go/internal/load/pkg.go b/src/cmd/go/internal/load/pkg.go index f73b79d089..066ff6c981 100644 --- a/src/cmd/go/internal/load/pkg.go +++ b/src/cmd/go/internal/load/pkg.go @@ -14,6 +14,7 @@ import ( "go/build" "go/scanner" "go/token" + "io/fs" "io/ioutil" "os" pathpkg "path" @@ -2300,7 +2301,7 @@ func GoFilesPackage(ctx context.Context, gofiles []string) *Package { // to make it look like this is a standard package or // command directory. So that local imports resolve // consistently, the files must all be in the same directory. - var dirent []os.FileInfo + var dirent []fs.FileInfo var dir string for _, file := range gofiles { fi, err := os.Stat(file) @@ -2321,7 +2322,7 @@ func GoFilesPackage(ctx context.Context, gofiles []string) *Package { } dirent = append(dirent, fi) } - ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil } + ctxt.ReadDir = func(string) ([]fs.FileInfo, error) { return dirent, nil } if cfg.ModulesEnabled { modload.ImportFromFiles(ctx, gofiles) diff --git a/src/cmd/go/internal/lockedfile/internal/filelock/filelock.go b/src/cmd/go/internal/lockedfile/internal/filelock/filelock.go index aba3eed776..05f27c321a 100644 --- a/src/cmd/go/internal/lockedfile/internal/filelock/filelock.go +++ b/src/cmd/go/internal/lockedfile/internal/filelock/filelock.go @@ -9,6 +9,7 @@ package filelock import ( "errors" + "io/fs" "os" ) @@ -24,7 +25,7 @@ type File interface { Fd() uintptr // Stat returns the FileInfo structure describing file. - Stat() (os.FileInfo, error) + Stat() (fs.FileInfo, error) } // Lock places an advisory write lock on the file, blocking until it can be @@ -87,7 +88,7 @@ var ErrNotSupported = errors.New("operation not supported") // underlyingError returns the underlying error for known os error types. func underlyingError(err error) error { switch err := err.(type) { - case *os.PathError: + case *fs.PathError: return err.Err case *os.LinkError: return err.Err diff --git a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go index 8776c5741c..1fa4327a89 100644 --- a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go +++ b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go @@ -18,8 +18,8 @@ package filelock import ( "errors" "io" + "io/fs" "math/rand" - "os" "sync" "syscall" "time" @@ -61,7 +61,7 @@ func lock(f File, lt lockType) (err error) { mu.Lock() if i, dup := inodes[f]; dup && i != ino { mu.Unlock() - return &os.PathError{ + return &fs.PathError{ Op: lt.String(), Path: f.Name(), Err: errors.New("inode for file changed since last Lock or RLock"), @@ -152,7 +152,7 @@ func lock(f File, lt lockType) (err error) { if err != nil { unlock(f) - return &os.PathError{ + return &fs.PathError{ Op: lt.String(), Path: f.Name(), Err: err, diff --git a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_other.go b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_other.go index 107611e1ce..bc480343fc 100644 --- a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_other.go +++ b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_other.go @@ -6,7 +6,7 @@ package filelock -import "os" +import "io/fs" type lockType int8 @@ -16,7 +16,7 @@ const ( ) func lock(f File, lt lockType) error { - return &os.PathError{ + return &fs.PathError{ Op: lt.String(), Path: f.Name(), Err: ErrNotSupported, @@ -24,7 +24,7 @@ func lock(f File, lt lockType) error { } func unlock(f File) error { - return &os.PathError{ + return &fs.PathError{ Op: "Unlock", Path: f.Name(), Err: ErrNotSupported, diff --git a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_plan9.go b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_plan9.go index afdffe323f..0798ee469a 100644 --- a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_plan9.go +++ b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_plan9.go @@ -6,9 +6,7 @@ package filelock -import ( - "os" -) +import "io/fs" type lockType int8 @@ -18,7 +16,7 @@ const ( ) func lock(f File, lt lockType) error { - return &os.PathError{ + return &fs.PathError{ Op: lt.String(), Path: f.Name(), Err: ErrNotSupported, @@ -26,7 +24,7 @@ func lock(f File, lt lockType) error { } func unlock(f File) error { - return &os.PathError{ + return &fs.PathError{ Op: "Unlock", Path: f.Name(), Err: ErrNotSupported, diff --git a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_unix.go b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_unix.go index 78f2c51129..ed07bac608 100644 --- a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_unix.go +++ b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_unix.go @@ -7,7 +7,7 @@ package filelock import ( - "os" + "io/fs" "syscall" ) @@ -26,7 +26,7 @@ func lock(f File, lt lockType) (err error) { } } if err != nil { - return &os.PathError{ + return &fs.PathError{ Op: lt.String(), Path: f.Name(), Err: err, diff --git a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_windows.go b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_windows.go index 43e85e450e..19de27eb9b 100644 --- a/src/cmd/go/internal/lockedfile/internal/filelock/filelock_windows.go +++ b/src/cmd/go/internal/lockedfile/internal/filelock/filelock_windows.go @@ -8,7 +8,7 @@ package filelock import ( "internal/syscall/windows" - "os" + "io/fs" "syscall" ) @@ -34,7 +34,7 @@ func lock(f File, lt lockType) error { err := windows.LockFileEx(syscall.Handle(f.Fd()), uint32(lt), reserved, allBytes, allBytes, ol) if err != nil { - return &os.PathError{ + return &fs.PathError{ Op: lt.String(), Path: f.Name(), Err: err, @@ -47,7 +47,7 @@ func unlock(f File) error { ol := new(syscall.Overlapped) err := windows.UnlockFileEx(syscall.Handle(f.Fd()), reserved, allBytes, allBytes, ol) if err != nil { - return &os.PathError{ + return &fs.PathError{ Op: "Unlock", Path: f.Name(), Err: err, diff --git a/src/cmd/go/internal/lockedfile/lockedfile.go b/src/cmd/go/internal/lockedfile/lockedfile.go index 59b2dba44c..503024da4b 100644 --- a/src/cmd/go/internal/lockedfile/lockedfile.go +++ b/src/cmd/go/internal/lockedfile/lockedfile.go @@ -9,6 +9,7 @@ package lockedfile import ( "fmt" "io" + "io/fs" "io/ioutil" "os" "runtime" @@ -35,7 +36,7 @@ type osFile struct { // OpenFile is like os.OpenFile, but returns a locked file. // If flag includes os.O_WRONLY or os.O_RDWR, the file is write-locked; // otherwise, it is read-locked. -func OpenFile(name string, flag int, perm os.FileMode) (*File, error) { +func OpenFile(name string, flag int, perm fs.FileMode) (*File, error) { var ( f = new(File) err error @@ -82,10 +83,10 @@ func Edit(name string) (*File, error) { // non-nil error. func (f *File) Close() error { if f.closed { - return &os.PathError{ + return &fs.PathError{ Op: "close", Path: f.Name(), - Err: os.ErrClosed, + Err: fs.ErrClosed, } } f.closed = true @@ -108,7 +109,7 @@ func Read(name string) ([]byte, error) { // Write opens the named file (creating it with the given permissions if needed), // then write-locks it and overwrites it with the given content. -func Write(name string, content io.Reader, perm os.FileMode) (err error) { +func Write(name string, content io.Reader, perm fs.FileMode) (err error) { f, err := OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) if err != nil { return err diff --git a/src/cmd/go/internal/lockedfile/lockedfile_filelock.go b/src/cmd/go/internal/lockedfile/lockedfile_filelock.go index f63dd8664b..10e1240efd 100644 --- a/src/cmd/go/internal/lockedfile/lockedfile_filelock.go +++ b/src/cmd/go/internal/lockedfile/lockedfile_filelock.go @@ -7,12 +7,13 @@ package lockedfile import ( + "io/fs" "os" "cmd/go/internal/lockedfile/internal/filelock" ) -func openFile(name string, flag int, perm os.FileMode) (*os.File, error) { +func openFile(name string, flag int, perm fs.FileMode) (*os.File, error) { // On BSD systems, we could add the O_SHLOCK or O_EXLOCK flag to the OpenFile // call instead of locking separately, but we have to support separate locking // calls for Linux and Windows anyway, so it's simpler to use that approach diff --git a/src/cmd/go/internal/lockedfile/lockedfile_plan9.go b/src/cmd/go/internal/lockedfile/lockedfile_plan9.go index 4a52c94976..51681381d7 100644 --- a/src/cmd/go/internal/lockedfile/lockedfile_plan9.go +++ b/src/cmd/go/internal/lockedfile/lockedfile_plan9.go @@ -7,6 +7,7 @@ package lockedfile import ( + "io/fs" "math/rand" "os" "strings" @@ -41,7 +42,7 @@ func isLocked(err error) bool { return false } -func openFile(name string, flag int, perm os.FileMode) (*os.File, error) { +func openFile(name string, flag int, perm fs.FileMode) (*os.File, error) { // Plan 9 uses a mode bit instead of explicit lock/unlock syscalls. // // Per http://man.cat-v.org/plan_9/5/stat: “Exclusive use files may be open @@ -56,8 +57,8 @@ func openFile(name string, flag int, perm os.FileMode) (*os.File, error) { // have the ModeExclusive bit set. Set it before we call OpenFile, so that we // can be confident that a successful OpenFile implies exclusive use. if fi, err := os.Stat(name); err == nil { - if fi.Mode()&os.ModeExclusive == 0 { - if err := os.Chmod(name, fi.Mode()|os.ModeExclusive); err != nil { + if fi.Mode()&fs.ModeExclusive == 0 { + if err := os.Chmod(name, fi.Mode()|fs.ModeExclusive); err != nil { return nil, err } } @@ -68,7 +69,7 @@ func openFile(name string, flag int, perm os.FileMode) (*os.File, error) { nextSleep := 1 * time.Millisecond const maxSleep = 500 * time.Millisecond for { - f, err := os.OpenFile(name, flag, perm|os.ModeExclusive) + f, err := os.OpenFile(name, flag, perm|fs.ModeExclusive) if err == nil { return f, nil } diff --git a/src/cmd/go/internal/modcmd/vendor.go b/src/cmd/go/internal/modcmd/vendor.go index 1bc4ab3def..1b9ce60529 100644 --- a/src/cmd/go/internal/modcmd/vendor.go +++ b/src/cmd/go/internal/modcmd/vendor.go @@ -9,6 +9,7 @@ import ( "context" "fmt" "io" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -232,7 +233,7 @@ var metaPrefixes = []string{ } // matchMetadata reports whether info is a metadata file. -func matchMetadata(dir string, info os.FileInfo) bool { +func matchMetadata(dir string, info fs.FileInfo) bool { name := info.Name() for _, p := range metaPrefixes { if strings.HasPrefix(name, p) { @@ -243,7 +244,7 @@ func matchMetadata(dir string, info os.FileInfo) bool { } // matchPotentialSourceFile reports whether info may be relevant to a build operation. -func matchPotentialSourceFile(dir string, info os.FileInfo) bool { +func matchPotentialSourceFile(dir string, info fs.FileInfo) bool { if strings.HasSuffix(info.Name(), "_test.go") { return false } @@ -269,7 +270,7 @@ func matchPotentialSourceFile(dir string, info os.FileInfo) bool { } // copyDir copies all regular files satisfying match(info) from src to dst. -func copyDir(dst, src string, match func(dir string, info os.FileInfo) bool) { +func copyDir(dst, src string, match func(dir string, info fs.FileInfo) bool) { files, err := ioutil.ReadDir(src) if 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 bd591d3f32..ce24793929 100644 --- a/src/cmd/go/internal/modcmd/verify.go +++ b/src/cmd/go/internal/modcmd/verify.go @@ -9,6 +9,7 @@ import ( "context" "errors" "fmt" + "io/fs" "io/ioutil" "os" "runtime" @@ -88,8 +89,8 @@ func verifyMod(mod module.Version) []error { dir, dirErr := modfetch.DownloadDir(mod) data, err := ioutil.ReadFile(zip + "hash") if err != nil { - if zipErr != nil && errors.Is(zipErr, os.ErrNotExist) && - dirErr != nil && errors.Is(dirErr, os.ErrNotExist) { + if zipErr != nil && errors.Is(zipErr, fs.ErrNotExist) && + dirErr != nil && errors.Is(dirErr, fs.ErrNotExist) { // Nothing downloaded yet. Nothing to verify. return nil } @@ -98,7 +99,7 @@ func verifyMod(mod module.Version) []error { } h := string(bytes.TrimSpace(data)) - if zipErr != nil && errors.Is(zipErr, os.ErrNotExist) { + if zipErr != nil && errors.Is(zipErr, fs.ErrNotExist) { // ok } else { hZ, err := dirhash.HashZip(zip, dirhash.DefaultHash) @@ -109,7 +110,7 @@ func verifyMod(mod module.Version) []error { errs = append(errs, fmt.Errorf("%s %s: zip has been modified (%v)", mod.Path, mod.Version, zip)) } } - if dirErr != nil && errors.Is(dirErr, os.ErrNotExist) { + if dirErr != nil && errors.Is(dirErr, fs.ErrNotExist) { // ok } else { hD, err := dirhash.HashDir(dir, mod.Path+"@"+mod.Version, dirhash.DefaultHash) diff --git a/src/cmd/go/internal/modfetch/cache.go b/src/cmd/go/internal/modfetch/cache.go index 6eadb026c9..b7aa670250 100644 --- a/src/cmd/go/internal/modfetch/cache.go +++ b/src/cmd/go/internal/modfetch/cache.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "io" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -60,7 +61,7 @@ func CachePath(m module.Version, suffix string) (string, error) { // DownloadDir returns the directory to which m should have been downloaded. // An error will be returned if the module path or version cannot be escaped. -// An error satisfying errors.Is(err, os.ErrNotExist) will be returned +// An error satisfying errors.Is(err, fs.ErrNotExist) will be returned // along with the directory if the directory does not exist or if the directory // is not completely populated. func DownloadDir(m module.Version) (string, error) { @@ -107,14 +108,14 @@ func DownloadDir(m module.Version) (string, error) { // DownloadDirPartialError is returned by DownloadDir if a module directory // exists but was not completely populated. // -// DownloadDirPartialError is equivalent to os.ErrNotExist. +// DownloadDirPartialError is equivalent to fs.ErrNotExist. type DownloadDirPartialError struct { Dir string Err error } func (e *DownloadDirPartialError) Error() string { return fmt.Sprintf("%s: %v", e.Dir, e.Err) } -func (e *DownloadDirPartialError) Is(err error) bool { return err == os.ErrNotExist } +func (e *DownloadDirPartialError) Is(err error) bool { return err == fs.ErrNotExist } // lockVersion locks a file within the module cache that guards the downloading // and extraction of the zipfile for the given module version. diff --git a/src/cmd/go/internal/modfetch/codehost/codehost.go b/src/cmd/go/internal/modfetch/codehost/codehost.go index df4cfdab1a..c5fbb31b2b 100644 --- a/src/cmd/go/internal/modfetch/codehost/codehost.go +++ b/src/cmd/go/internal/modfetch/codehost/codehost.go @@ -11,6 +11,7 @@ import ( "crypto/sha256" "fmt" "io" + "io/fs" "io/ioutil" "os" "os/exec" @@ -105,7 +106,7 @@ type FileRev struct { Err error // error if any; os.IsNotExist(Err)==true if rev exists but file does not exist in that rev } -// UnknownRevisionError is an error equivalent to os.ErrNotExist, but for a +// UnknownRevisionError is an error equivalent to fs.ErrNotExist, but for a // revision rather than a file. type UnknownRevisionError struct { Rev string @@ -115,10 +116,10 @@ func (e *UnknownRevisionError) Error() string { return "unknown revision " + e.Rev } func (UnknownRevisionError) Is(err error) bool { - return err == os.ErrNotExist + return err == fs.ErrNotExist } -// ErrNoCommits is an error equivalent to os.ErrNotExist indicating that a given +// ErrNoCommits is an error equivalent to fs.ErrNotExist indicating that a given // repository or module contains no commits. var ErrNoCommits error = noCommitsError{} @@ -128,7 +129,7 @@ func (noCommitsError) Error() string { return "no commits" } func (noCommitsError) Is(err error) bool { - return err == os.ErrNotExist + return err == fs.ErrNotExist } // AllHex reports whether the revision rev is entirely lower-case hexadecimal digits. diff --git a/src/cmd/go/internal/modfetch/codehost/git.go b/src/cmd/go/internal/modfetch/codehost/git.go index 5a35829c98..58b4b2f2d3 100644 --- a/src/cmd/go/internal/modfetch/codehost/git.go +++ b/src/cmd/go/internal/modfetch/codehost/git.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "io" + "io/fs" "io/ioutil" "net/url" "os" @@ -34,13 +35,13 @@ func LocalGitRepo(remote string) (Repo, error) { } // A notExistError wraps another error to retain its original text -// but makes it opaquely equivalent to os.ErrNotExist. +// but makes it opaquely equivalent to fs.ErrNotExist. type notExistError struct { err error } func (e notExistError) Error() string { return e.err.Error() } -func (notExistError) Is(err error) bool { return err == os.ErrNotExist } +func (notExistError) Is(err error) bool { return err == fs.ErrNotExist } const gitWorkDirType = "git3" @@ -188,7 +189,7 @@ func (r *gitRepo) loadRefs() { // For HTTP and HTTPS, that's easy to detect: we'll try to fetch the URL // ourselves and see what code it serves. if u, err := url.Parse(r.remoteURL); err == nil && (u.Scheme == "http" || u.Scheme == "https") { - if _, err := web.GetBytes(u); errors.Is(err, os.ErrNotExist) { + if _, err := web.GetBytes(u); errors.Is(err, fs.ErrNotExist) { gitErr = notExistError{gitErr} } } @@ -505,7 +506,7 @@ func (r *gitRepo) ReadFile(rev, file string, maxSize int64) ([]byte, error) { } out, err := Run(r.dir, "git", "cat-file", "blob", info.Name+":"+file) if err != nil { - return nil, os.ErrNotExist + return nil, fs.ErrNotExist } return out, nil } @@ -629,9 +630,9 @@ func (r *gitRepo) readFileRevs(tags []string, file string, fileMap map[string]*F case "tag", "commit": switch fileType { default: - f.Err = &os.PathError{Path: tag + ":" + file, Op: "read", Err: fmt.Errorf("unexpected non-blob type %q", fileType)} + f.Err = &fs.PathError{Path: tag + ":" + file, Op: "read", Err: fmt.Errorf("unexpected non-blob type %q", fileType)} case "missing": - f.Err = &os.PathError{Path: tag + ":" + file, Op: "read", Err: os.ErrNotExist} + f.Err = &fs.PathError{Path: tag + ":" + file, Op: "read", Err: fs.ErrNotExist} case "blob": f.Data = fileData } @@ -826,7 +827,7 @@ func (r *gitRepo) ReadZip(rev, subdir string, maxSize int64) (zip io.ReadCloser, archive, err := Run(r.dir, "git", "-c", "core.autocrlf=input", "-c", "core.eol=lf", "archive", "--format=zip", "--prefix=prefix/", info.Name, args) if err != nil { if bytes.Contains(err.(*RunError).Stderr, []byte("did not match any files")) { - return nil, os.ErrNotExist + return nil, fs.ErrNotExist } return nil, err } diff --git a/src/cmd/go/internal/modfetch/codehost/git_test.go b/src/cmd/go/internal/modfetch/codehost/git_test.go index ba27c70f5a..16908b3e84 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/fs" "io/ioutil" "log" "os" @@ -210,7 +211,7 @@ var readFileTests = []struct { repo: gitrepo1, rev: "v2.3.4", file: "another.txt", - err: os.ErrNotExist.Error(), + err: fs.ErrNotExist.Error(), }, } diff --git a/src/cmd/go/internal/modfetch/codehost/vcs.go b/src/cmd/go/internal/modfetch/codehost/vcs.go index 6278cb21e1..ec97fc7e1b 100644 --- a/src/cmd/go/internal/modfetch/codehost/vcs.go +++ b/src/cmd/go/internal/modfetch/codehost/vcs.go @@ -9,6 +9,7 @@ import ( "fmt" "internal/lazyregexp" "io" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -377,7 +378,7 @@ func (r *vcsRepo) ReadFile(rev, file string, maxSize int64) ([]byte, error) { out, err := Run(r.dir, r.cmd.readFile(rev, file, r.remote)) if err != nil { - return nil, os.ErrNotExist + return nil, fs.ErrNotExist } return out, nil } diff --git a/src/cmd/go/internal/modfetch/coderepo.go b/src/cmd/go/internal/modfetch/coderepo.go index d99a31d360..7f44e18a70 100644 --- a/src/cmd/go/internal/modfetch/coderepo.go +++ b/src/cmd/go/internal/modfetch/coderepo.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "io" + "io/fs" "io/ioutil" "os" "path" @@ -1040,7 +1041,7 @@ type zipFile struct { } func (f zipFile) Path() string { return f.name } -func (f zipFile) Lstat() (os.FileInfo, error) { return f.f.FileInfo(), nil } +func (f zipFile) Lstat() (fs.FileInfo, error) { return f.f.FileInfo(), nil } func (f zipFile) Open() (io.ReadCloser, error) { return f.f.Open() } type dataFile struct { @@ -1049,7 +1050,7 @@ type dataFile struct { } func (f dataFile) Path() string { return f.name } -func (f dataFile) Lstat() (os.FileInfo, error) { return dataFileInfo{f}, nil } +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 } @@ -1060,7 +1061,7 @@ type dataFileInfo struct { func (fi dataFileInfo) Name() string { return path.Base(fi.f.name) } func (fi dataFileInfo) Size() int64 { return int64(len(fi.f.data)) } -func (fi dataFileInfo) Mode() os.FileMode { return 0644 } +func (fi dataFileInfo) Mode() fs.FileMode { return 0644 } func (fi dataFileInfo) ModTime() time.Time { return time.Time{} } func (fi dataFileInfo) IsDir() bool { return false } func (fi dataFileInfo) Sys() interface{} { return nil } diff --git a/src/cmd/go/internal/modfetch/fetch.go b/src/cmd/go/internal/modfetch/fetch.go index 599419977a..6ff455e89c 100644 --- a/src/cmd/go/internal/modfetch/fetch.go +++ b/src/cmd/go/internal/modfetch/fetch.go @@ -11,6 +11,7 @@ import ( "errors" "fmt" "io" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -67,7 +68,7 @@ func download(ctx context.Context, mod module.Version) (dir string, err error) { if err == nil { // The directory has already been completely extracted (no .partial file exists). return dir, nil - } else if dir == "" || !errors.Is(err, os.ErrNotExist) { + } else if dir == "" || !errors.Is(err, fs.ErrNotExist) { return "", err } @@ -314,10 +315,10 @@ func downloadZip(ctx context.Context, mod module.Version, zipfile string) (err e func makeDirsReadOnly(dir string) { type pathMode struct { path string - mode os.FileMode + mode fs.FileMode } var dirs []pathMode // in lexical order - filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error { if err == nil && info.Mode()&0222 != 0 { if info.IsDir() { dirs = append(dirs, pathMode{path, info.Mode()}) @@ -336,7 +337,7 @@ func makeDirsReadOnly(dir string) { // any permission changes needed to do so. func RemoveAll(dir string) error { // Module cache has 0555 directories; make them writable in order to remove content. - filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error { if err != nil { return nil // ignore errors walking in file system } @@ -441,7 +442,7 @@ func checkMod(mod module.Version) { } data, err := renameio.ReadFile(ziphash) if err != nil { - if errors.Is(err, os.ErrNotExist) { + if errors.Is(err, fs.ErrNotExist) { // This can happen if someone does rm -rf GOPATH/src/cache/download. So it goes. return } diff --git a/src/cmd/go/internal/modfetch/proxy.go b/src/cmd/go/internal/modfetch/proxy.go index 4ac26650a9..819990b403 100644 --- a/src/cmd/go/internal/modfetch/proxy.go +++ b/src/cmd/go/internal/modfetch/proxy.go @@ -9,9 +9,9 @@ import ( "errors" "fmt" "io" + "io/fs" "io/ioutil" "net/url" - "os" "path" pathpkg "path" "path/filepath" @@ -186,7 +186,7 @@ func proxyList() ([]proxySpec, error) { // TryProxies iterates f over each configured proxy (including "noproxy" and // "direct" if applicable) until f returns no error or until f returns an -// error that is not equivalent to os.ErrNotExist on a proxy configured +// error that is not equivalent to fs.ErrNotExist on a proxy configured // not to fall back on errors. // // TryProxies then returns that final error. @@ -222,7 +222,7 @@ func TryProxies(f func(proxy string) error) error { if err == nil { return nil } - isNotExistErr := errors.Is(err, os.ErrNotExist) + isNotExistErr := errors.Is(err, fs.ErrNotExist) if proxy.url == "direct" || (proxy.url == "noproxy" && err != errUseProxy) { bestErr = err @@ -428,7 +428,7 @@ func (p *proxyRepo) Stat(rev string) (*RevInfo, error) { func (p *proxyRepo) Latest() (*RevInfo, error) { data, err := p.getBytes("@latest") if err != nil { - if !errors.Is(err, os.ErrNotExist) { + if !errors.Is(err, fs.ErrNotExist) { return nil, p.versionError("", err) } return p.latest() diff --git a/src/cmd/go/internal/modfetch/repo.go b/src/cmd/go/internal/modfetch/repo.go index c7cf5595bd..af9e24cefd 100644 --- a/src/cmd/go/internal/modfetch/repo.go +++ b/src/cmd/go/internal/modfetch/repo.go @@ -7,6 +7,7 @@ package modfetch import ( "fmt" "io" + "io/fs" "os" "sort" "strconv" @@ -432,7 +433,7 @@ func (r errRepo) Latest() (*RevInfo, error) { return nil func (r errRepo) GoMod(version string) ([]byte, error) { return nil, r.err } func (r errRepo) Zip(dst io.Writer, version string) error { return r.err } -// A notExistError is like os.ErrNotExist, but with a custom message +// A notExistError is like fs.ErrNotExist, but with a custom message type notExistError struct { err error } @@ -446,7 +447,7 @@ func (e notExistError) Error() string { } func (notExistError) Is(target error) bool { - return target == os.ErrNotExist + return target == fs.ErrNotExist } func (e notExistError) Unwrap() error { diff --git a/src/cmd/go/internal/modfetch/sumdb.go b/src/cmd/go/internal/modfetch/sumdb.go index 47a2571531..5108961a33 100644 --- a/src/cmd/go/internal/modfetch/sumdb.go +++ b/src/cmd/go/internal/modfetch/sumdb.go @@ -12,6 +12,7 @@ import ( "bytes" "errors" "fmt" + "io/fs" "io/ioutil" "net/url" "os" @@ -182,7 +183,7 @@ func (c *dbClient) initBase() { return nil } }) - if errors.Is(err, os.ErrNotExist) { + if errors.Is(err, fs.ErrNotExist) { // No proxies, or all proxies failed (with 404, 410, or were were allowed // to fall back), or we reached an explicit "direct" or "off". c.base = c.direct @@ -203,7 +204,7 @@ func (c *dbClient) ReadConfig(file string) (data []byte, err error) { } targ := filepath.Join(cfg.SumdbDir, file) data, err = lockedfile.Read(targ) - if errors.Is(err, os.ErrNotExist) { + if errors.Is(err, fs.ErrNotExist) { // Treat non-existent as empty, to bootstrap the "latest" file // the first time we connect to a given database. return []byte{}, nil @@ -257,7 +258,7 @@ func (*dbClient) ReadCache(file string) ([]byte, error) { // during which the empty file can be locked for reading. // Treat observing an empty file as file not found. if err == nil && len(data) == 0 { - err = &os.PathError{Op: "read", Path: targ, Err: os.ErrNotExist} + err = &fs.PathError{Op: "read", Path: targ, Err: fs.ErrNotExist} } return data, err } diff --git a/src/cmd/go/internal/modload/import.go b/src/cmd/go/internal/modload/import.go index 6d0d8de944..bcbc9b0c3a 100644 --- a/src/cmd/go/internal/modload/import.go +++ b/src/cmd/go/internal/modload/import.go @@ -10,6 +10,7 @@ import ( "fmt" "go/build" "internal/goroot" + "io/fs" "os" "path/filepath" "sort" @@ -347,7 +348,7 @@ func queryImport(ctx context.Context, path string) (module.Version, error) { candidates, err := QueryPattern(ctx, path, "latest", Selected, CheckAllowed) if err != nil { - if errors.Is(err, os.ErrNotExist) { + if errors.Is(err, fs.ErrNotExist) { // Return "cannot find module providing package […]" instead of whatever // low-level error QueryPattern produced. return module.Version{}, &ImportMissingError{Path: path, QueryErr: err} diff --git a/src/cmd/go/internal/modload/load.go b/src/cmd/go/internal/modload/load.go index 4ddb817cf1..4b3ded8326 100644 --- a/src/cmd/go/internal/modload/load.go +++ b/src/cmd/go/internal/modload/load.go @@ -98,6 +98,7 @@ import ( "errors" "fmt" "go/build" + "io/fs" "os" "path" pathpkg "path" @@ -364,7 +365,7 @@ func resolveLocalPackage(dir string) (string, error) { if os.IsNotExist(err) { // Canonicalize OS-specific errors to errDirectoryNotFound so that error // messages will be easier for users to search for. - return "", &os.PathError{Op: "stat", Path: absDir, Err: errDirectoryNotFound} + return "", &fs.PathError{Op: "stat", Path: absDir, Err: errDirectoryNotFound} } return "", err } diff --git a/src/cmd/go/internal/modload/query.go b/src/cmd/go/internal/modload/query.go index 3b27e66d01..6b14768388 100644 --- a/src/cmd/go/internal/modload/query.go +++ b/src/cmd/go/internal/modload/query.go @@ -8,6 +8,7 @@ import ( "context" "errors" "fmt" + "io/fs" "os" pathpkg "path" "path/filepath" @@ -145,7 +146,7 @@ func queryProxy(ctx context.Context, proxy, path, query, current string, allowed canonicalQuery := module.CanonicalVersion(query) if canonicalQuery != "" && query != canonicalQuery { info, err = repo.Stat(canonicalQuery) - if err != nil && !errors.Is(err, os.ErrNotExist) { + if err != nil && !errors.Is(err, fs.ErrNotExist) { return info, err } } @@ -230,7 +231,7 @@ func queryProxy(ctx context.Context, proxy, path, query, current string, allowed if qm.allowsVersion(ctx, latest.Version) { return lookup(latest.Version) } - } else if !errors.Is(err, os.ErrNotExist) { + } else if !errors.Is(err, fs.ErrNotExist) { return nil, err } } @@ -701,7 +702,7 @@ func queryPrefixModules(ctx context.Context, candidateModules []string, queryMod noVersion = rErr } default: - if errors.Is(rErr, os.ErrNotExist) { + if errors.Is(rErr, fs.ErrNotExist) { if notExistErr == nil { notExistErr = rErr } @@ -744,7 +745,7 @@ func queryPrefixModules(ctx context.Context, candidateModules []string, queryMod // A NoMatchingVersionError indicates that Query found a module at the requested // path, but not at any versions satisfying the query string and allow-function. // -// NOTE: NoMatchingVersionError MUST NOT implement Is(os.ErrNotExist). +// NOTE: NoMatchingVersionError MUST NOT implement Is(fs.ErrNotExist). // // If the module came from a proxy, that proxy had to return a successful status // code for the versions it knows about, and thus did not have the opportunity @@ -765,7 +766,7 @@ func (e *NoMatchingVersionError) Error() string { // module at the requested version, but that module did not contain any packages // matching the requested pattern. // -// NOTE: PackageNotInModuleError MUST NOT implement Is(os.ErrNotExist). +// NOTE: PackageNotInModuleError MUST NOT implement Is(fs.ErrNotExist). // // If the module came from a proxy, that proxy had to return a successful status // code for the versions it knows about, and thus did not have the opportunity diff --git a/src/cmd/go/internal/modload/search.go b/src/cmd/go/internal/modload/search.go index 0f82026732..19289ceb9c 100644 --- a/src/cmd/go/internal/modload/search.go +++ b/src/cmd/go/internal/modload/search.go @@ -7,6 +7,7 @@ package modload import ( "context" "fmt" + "io/fs" "os" "path/filepath" "strings" @@ -54,7 +55,7 @@ func matchPackages(ctx context.Context, m *search.Match, tags map[string]bool, f walkPkgs := func(root, importPathRoot string, prune pruning) { root = filepath.Clean(root) - err := fsys.Walk(root, func(path string, fi os.FileInfo, err error) error { + err := fsys.Walk(root, func(path string, fi fs.FileInfo, err error) error { if err != nil { m.AddError(err) return nil @@ -85,7 +86,7 @@ func matchPackages(ctx context.Context, m *search.Match, tags map[string]bool, f } if !fi.IsDir() { - if fi.Mode()&os.ModeSymlink != 0 && want { + if fi.Mode()&fs.ModeSymlink != 0 && want { if target, err := os.Stat(path); err == nil && target.IsDir() { fmt.Fprintf(os.Stderr, "warning: ignoring symlink %s\n", path) } diff --git a/src/cmd/go/internal/modload/stat_openfile.go b/src/cmd/go/internal/modload/stat_openfile.go index 931aaf1577..7cdeaf47a2 100644 --- a/src/cmd/go/internal/modload/stat_openfile.go +++ b/src/cmd/go/internal/modload/stat_openfile.go @@ -13,12 +13,13 @@ package modload import ( + "io/fs" "os" ) // hasWritePerm reports whether the current user has permission to write to the // file with the given info. -func hasWritePerm(path string, _ os.FileInfo) bool { +func hasWritePerm(path string, _ fs.FileInfo) bool { if f, err := os.OpenFile(path, os.O_WRONLY, 0); err == nil { f.Close() return true diff --git a/src/cmd/go/internal/modload/stat_unix.go b/src/cmd/go/internal/modload/stat_unix.go index ea3b801f2c..65068444d0 100644 --- a/src/cmd/go/internal/modload/stat_unix.go +++ b/src/cmd/go/internal/modload/stat_unix.go @@ -7,6 +7,7 @@ package modload import ( + "io/fs" "os" "syscall" ) @@ -17,7 +18,7 @@ import ( // Although the root user on most Unix systems can write to files even without // permission, hasWritePerm reports false if no appropriate permission bit is // set even if the current user is root. -func hasWritePerm(path string, fi os.FileInfo) bool { +func hasWritePerm(path string, fi fs.FileInfo) bool { if os.Getuid() == 0 { // The root user can access any file, but we still want to default to // read-only mode if the go.mod file is marked as globally non-writable. diff --git a/src/cmd/go/internal/modload/stat_windows.go b/src/cmd/go/internal/modload/stat_windows.go index d7826cfc6b..0ac2391347 100644 --- a/src/cmd/go/internal/modload/stat_windows.go +++ b/src/cmd/go/internal/modload/stat_windows.go @@ -6,13 +6,11 @@ package modload -import ( - "os" -) +import "io/fs" // hasWritePerm reports whether the current user has permission to write to the // file with the given info. -func hasWritePerm(_ string, fi os.FileInfo) bool { +func hasWritePerm(_ string, fi fs.FileInfo) bool { // Windows has a read-only attribute independent of ACLs, so use that to // determine whether the file is intended to be overwritten. // diff --git a/src/cmd/go/internal/modload/vendor.go b/src/cmd/go/internal/modload/vendor.go index 9f34b829fc..ab29d4d014 100644 --- a/src/cmd/go/internal/modload/vendor.go +++ b/src/cmd/go/internal/modload/vendor.go @@ -7,8 +7,8 @@ package modload import ( "errors" "fmt" + "io/fs" "io/ioutil" - "os" "path/filepath" "strings" "sync" @@ -42,7 +42,7 @@ func readVendorList() { vendorMeta = make(map[module.Version]vendorMetadata) data, err := ioutil.ReadFile(filepath.Join(ModRoot(), "vendor/modules.txt")) if err != nil { - if !errors.Is(err, os.ErrNotExist) { + if !errors.Is(err, fs.ErrNotExist) { base.Fatalf("go: %s", err) } return diff --git a/src/cmd/go/internal/renameio/renameio.go b/src/cmd/go/internal/renameio/renameio.go index d573cc690d..60a7138a76 100644 --- a/src/cmd/go/internal/renameio/renameio.go +++ b/src/cmd/go/internal/renameio/renameio.go @@ -8,6 +8,7 @@ package renameio import ( "bytes" "io" + "io/fs" "math/rand" "os" "path/filepath" @@ -29,13 +30,13 @@ func Pattern(filename string) string { // final name. // // That ensures that the final location, if it exists, is always a complete file. -func WriteFile(filename string, data []byte, perm os.FileMode) (err error) { +func WriteFile(filename string, data []byte, perm fs.FileMode) (err error) { return WriteToFile(filename, bytes.NewReader(data), perm) } // WriteToFile is a variant of WriteFile that accepts the data as an io.Reader // instead of a slice. -func WriteToFile(filename string, data io.Reader, perm os.FileMode) (err error) { +func WriteToFile(filename string, data io.Reader, perm fs.FileMode) (err error) { f, err := tempFile(filepath.Dir(filename), filepath.Base(filename), perm) if err != nil { return err @@ -80,7 +81,7 @@ func ReadFile(filename string) ([]byte, error) { } // tempFile creates a new temporary file with given permission bits. -func tempFile(dir, prefix string, perm os.FileMode) (f *os.File, err error) { +func tempFile(dir, prefix string, perm fs.FileMode) (f *os.File, err error) { for i := 0; i < 10000; i++ { name := filepath.Join(dir, prefix+strconv.Itoa(rand.Intn(1000000000))+patternSuffix) f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, perm) diff --git a/src/cmd/go/internal/renameio/umask_test.go b/src/cmd/go/internal/renameio/umask_test.go index d75d67c9a9..19e217c548 100644 --- a/src/cmd/go/internal/renameio/umask_test.go +++ b/src/cmd/go/internal/renameio/umask_test.go @@ -7,6 +7,7 @@ package renameio import ( + "io/fs" "io/ioutil" "os" "path/filepath" @@ -36,7 +37,7 @@ func TestWriteFileModeAppliesUmask(t *testing.T) { t.Fatalf("Stat %q (looking for mode %#o): %s", file, mode, err) } - if fi.Mode()&os.ModePerm != 0640 { - t.Errorf("Stat %q: mode %#o want %#o", file, fi.Mode()&os.ModePerm, 0640) + if fi.Mode()&fs.ModePerm != 0640 { + t.Errorf("Stat %q: mode %#o want %#o", file, fi.Mode()&fs.ModePerm, 0640) } } diff --git a/src/cmd/go/internal/search/search.go b/src/cmd/go/internal/search/search.go index b1d2a9376b..e4784e9478 100644 --- a/src/cmd/go/internal/search/search.go +++ b/src/cmd/go/internal/search/search.go @@ -10,6 +10,7 @@ import ( "cmd/go/internal/fsys" "fmt" "go/build" + "io/fs" "os" "path" "path/filepath" @@ -128,7 +129,7 @@ func (m *Match) MatchPackages() { if m.pattern == "cmd" { root += "cmd" + string(filepath.Separator) } - err := fsys.Walk(root, func(path string, fi os.FileInfo, err error) error { + err := fsys.Walk(root, func(path string, fi fs.FileInfo, err error) error { if err != nil { return err // Likely a permission error, which could interfere with matching. } @@ -154,7 +155,7 @@ func (m *Match) MatchPackages() { } if !fi.IsDir() { - if fi.Mode()&os.ModeSymlink != 0 && want { + if fi.Mode()&fs.ModeSymlink != 0 && want { if target, err := os.Stat(path); err == nil && target.IsDir() { fmt.Fprintf(os.Stderr, "warning: ignoring symlink %s\n", path) } @@ -264,7 +265,7 @@ func (m *Match) MatchDirs() { } } - err := fsys.Walk(dir, func(path string, fi os.FileInfo, err error) error { + err := fsys.Walk(dir, func(path string, fi fs.FileInfo, err error) error { if err != nil { return err // Likely a permission error, which could interfere with matching. } diff --git a/src/cmd/go/internal/test/test.go b/src/cmd/go/internal/test/test.go index 51d333d866..00da9770df 100644 --- a/src/cmd/go/internal/test/test.go +++ b/src/cmd/go/internal/test/test.go @@ -12,6 +12,7 @@ import ( "fmt" "go/build" "io" + "io/fs" "io/ioutil" "os" "os/exec" @@ -1598,7 +1599,7 @@ func hashStat(name string) cache.ActionID { return h.Sum() } -func hashWriteStat(h io.Writer, info os.FileInfo) { +func hashWriteStat(h io.Writer, info fs.FileInfo) { fmt.Fprintf(h, "stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir()) } diff --git a/src/cmd/go/internal/vcs/vcs.go b/src/cmd/go/internal/vcs/vcs.go index 90bf10244d..7812afd488 100644 --- a/src/cmd/go/internal/vcs/vcs.go +++ b/src/cmd/go/internal/vcs/vcs.go @@ -10,6 +10,7 @@ import ( "fmt" "internal/lazyregexp" "internal/singleflight" + "io/fs" "log" urlpkg "net/url" "os" @@ -404,9 +405,9 @@ func (v *Cmd) run1(dir string, cmdline string, keyval []string, verbose bool) ([ if len(args) >= 2 && args[0] == "-go-internal-mkdir" { var err error if filepath.IsAbs(args[1]) { - err = os.Mkdir(args[1], os.ModePerm) + err = os.Mkdir(args[1], fs.ModePerm) } else { - err = os.Mkdir(filepath.Join(dir, args[1]), os.ModePerm) + err = os.Mkdir(filepath.Join(dir, args[1]), fs.ModePerm) } if err != nil { return nil, err diff --git a/src/cmd/go/internal/version/version.go b/src/cmd/go/internal/version/version.go index 5aa0f8e7ed..44ac24c62d 100644 --- a/src/cmd/go/internal/version/version.go +++ b/src/cmd/go/internal/version/version.go @@ -10,6 +10,7 @@ import ( "context" "encoding/binary" "fmt" + "io/fs" "os" "path/filepath" "runtime" @@ -87,8 +88,8 @@ func runVersion(ctx context.Context, cmd *base.Command, args []string) { // scanDir scans a directory for executables to run scanFile on. func scanDir(dir string) { - filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { - if info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { + filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error { + if info.Mode().IsRegular() || info.Mode()&fs.ModeSymlink != 0 { scanFile(path, info, *versionV) } return nil @@ -96,7 +97,7 @@ func scanDir(dir string) { } // isExe reports whether the file should be considered executable. -func isExe(file string, info os.FileInfo) bool { +func isExe(file string, info fs.FileInfo) bool { if runtime.GOOS == "windows" { return strings.HasSuffix(strings.ToLower(file), ".exe") } @@ -107,8 +108,8 @@ func isExe(file string, info os.FileInfo) bool { // If mustPrint is true, scanFile will report any error reading file. // Otherwise (mustPrint is false, because scanFile is being called // by scanDir) scanFile prints nothing for non-Go executables. -func scanFile(file string, info os.FileInfo, mustPrint bool) { - if info.Mode()&os.ModeSymlink != 0 { +func scanFile(file string, info fs.FileInfo, mustPrint bool) { + if info.Mode()&fs.ModeSymlink != 0 { // Accept file symlinks only. i, err := os.Stat(file) if err != nil || !i.Mode().IsRegular() { diff --git a/src/cmd/go/internal/web/api.go b/src/cmd/go/internal/web/api.go index 570818843b..f7d3ed60f6 100644 --- a/src/cmd/go/internal/web/api.go +++ b/src/cmd/go/internal/web/api.go @@ -13,9 +13,9 @@ import ( "bytes" "fmt" "io" + "io/fs" "io/ioutil" "net/url" - "os" "strings" "unicode" "unicode/utf8" @@ -56,7 +56,7 @@ func (e *HTTPError) Error() string { } if err := e.Err; err != nil { - if pErr, ok := e.Err.(*os.PathError); ok && strings.HasSuffix(e.URL, pErr.Path) { + if pErr, ok := e.Err.(*fs.PathError); ok && strings.HasSuffix(e.URL, pErr.Path) { // Remove the redundant copy of the path. err = pErr.Err } @@ -67,7 +67,7 @@ func (e *HTTPError) Error() string { } func (e *HTTPError) Is(target error) bool { - return target == os.ErrNotExist && (e.StatusCode == 404 || e.StatusCode == 410) + return target == fs.ErrNotExist && (e.StatusCode == 404 || e.StatusCode == 410) } func (e *HTTPError) Unwrap() error { diff --git a/src/cmd/go/internal/web/file_test.go b/src/cmd/go/internal/web/file_test.go index 6339469045..a1bb080e07 100644 --- a/src/cmd/go/internal/web/file_test.go +++ b/src/cmd/go/internal/web/file_test.go @@ -6,6 +6,7 @@ package web import ( "errors" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -54,7 +55,7 @@ func TestGetNonexistentFile(t *testing.T) { } b, err := GetBytes(u) - if !errors.Is(err, os.ErrNotExist) { - t.Fatalf("GetBytes(%v) = %q, %v; want _, os.ErrNotExist", u, b, err) + if !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("GetBytes(%v) = %q, %v; want _, fs.ErrNotExist", u, b, err) } } diff --git a/src/cmd/go/internal/work/build_test.go b/src/cmd/go/internal/work/build_test.go index 904aee0684..e941729734 100644 --- a/src/cmd/go/internal/work/build_test.go +++ b/src/cmd/go/internal/work/build_test.go @@ -7,6 +7,7 @@ package work import ( "bytes" "fmt" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -253,7 +254,7 @@ func TestRespectSetgidDir(t *testing.T) { } // Change setgiddir's permissions to include the SetGID bit. - if err := os.Chmod(setgiddir, 0755|os.ModeSetgid); err != nil { + if err := os.Chmod(setgiddir, 0755|fs.ModeSetgid); err != nil { t.Fatal(err) } diff --git a/src/cmd/go/internal/work/exec.go b/src/cmd/go/internal/work/exec.go index 824a4b5a0a..717b0cc3af 100644 --- a/src/cmd/go/internal/work/exec.go +++ b/src/cmd/go/internal/work/exec.go @@ -14,6 +14,7 @@ import ( "fmt" "internal/lazyregexp" "io" + "io/fs" "io/ioutil" "log" "math/rand" @@ -1560,7 +1561,7 @@ func BuildInstallFunc(b *Builder, ctx context.Context, a *Action) (err error) { return err } - perm := os.FileMode(0666) + perm := fs.FileMode(0666) if a1.Mode == "link" { switch cfg.BuildBuildmode { case "c-archive", "c-shared", "plugin": @@ -1609,7 +1610,7 @@ func (b *Builder) cleanup(a *Action) { } // moveOrCopyFile is like 'mv src dst' or 'cp src dst'. -func (b *Builder) moveOrCopyFile(dst, src string, perm os.FileMode, force bool) error { +func (b *Builder) moveOrCopyFile(dst, src string, perm fs.FileMode, force bool) error { if cfg.BuildN { b.Showcmd("", "mv %s %s", src, dst) return nil @@ -1635,7 +1636,7 @@ func (b *Builder) moveOrCopyFile(dst, src string, perm os.FileMode, force bool) // we have to copy the file to retain the correct permissions. // https://golang.org/issue/18878 if fi, err := os.Stat(filepath.Dir(dst)); err == nil { - if fi.IsDir() && (fi.Mode()&os.ModeSetgid) != 0 { + if fi.IsDir() && (fi.Mode()&fs.ModeSetgid) != 0 { return b.copyFile(dst, src, perm, force) } } @@ -1670,7 +1671,7 @@ func (b *Builder) moveOrCopyFile(dst, src string, perm os.FileMode, force bool) } // copyFile is like 'cp src dst'. -func (b *Builder) copyFile(dst, src string, perm os.FileMode, force bool) error { +func (b *Builder) copyFile(dst, src string, perm fs.FileMode, force bool) error { if cfg.BuildN || cfg.BuildX { b.Showcmd("", "cp %s %s", src, dst) if cfg.BuildN { diff --git a/src/cmd/go/proxy_test.go b/src/cmd/go/proxy_test.go index 42972f5b2a..8b0dbb74b2 100644 --- a/src/cmd/go/proxy_test.go +++ b/src/cmd/go/proxy_test.go @@ -12,6 +12,7 @@ import ( "flag" "fmt" "io" + "io/fs" "io/ioutil" "log" "net" @@ -335,7 +336,7 @@ func proxyHandler(w http.ResponseWriter, r *http.Request) { if testing.Verbose() { fmt.Fprintf(os.Stderr, "go proxy: no archive %s %s: %v\n", path, vers, err) } - if errors.Is(err, os.ErrNotExist) { + if errors.Is(err, fs.ErrNotExist) { http.NotFound(w, r) } else { http.Error(w, "cannot load archive", 500) @@ -443,7 +444,7 @@ func readArchive(path, vers string) (*txtar.Archive, error) { return a }).(*txtar.Archive) if a == nil { - return nil, os.ErrNotExist + return nil, fs.ErrNotExist } return a, nil } diff --git a/src/cmd/go/script_test.go b/src/cmd/go/script_test.go index 986646252a..a31561cd86 100644 --- a/src/cmd/go/script_test.go +++ b/src/cmd/go/script_test.go @@ -14,6 +14,7 @@ import ( "fmt" "go/build" "internal/testenv" + "io/fs" "io/ioutil" "os" "os/exec" @@ -500,7 +501,7 @@ func (ts *testScript) cmdChmod(want simpleStatus, args []string) { ts.fatalf("usage: chmod perm paths...") } perm, err := strconv.ParseUint(args[0], 0, 32) - if err != nil || perm&uint64(os.ModePerm) != perm { + if err != nil || perm&uint64(fs.ModePerm) != perm { ts.fatalf("invalid mode: %s", args[0]) } for _, arg := range args[1:] { @@ -508,7 +509,7 @@ func (ts *testScript) cmdChmod(want simpleStatus, args []string) { if !filepath.IsAbs(path) { path = filepath.Join(ts.cd, arg) } - err := os.Chmod(path, os.FileMode(perm)) + err := os.Chmod(path, fs.FileMode(perm)) ts.check(err) } } @@ -595,7 +596,7 @@ func (ts *testScript) cmdCp(want simpleStatus, args []string) { var ( src string data []byte - mode os.FileMode + mode fs.FileMode ) switch arg { case "stdout": diff --git a/src/cmd/go/testdata/addmod.go b/src/cmd/go/testdata/addmod.go index d9c3aab9c4..d1b6467c5d 100644 --- a/src/cmd/go/testdata/addmod.go +++ b/src/cmd/go/testdata/addmod.go @@ -22,6 +22,7 @@ import ( "bytes" "flag" "fmt" + "io/fs" "io/ioutil" "log" "os" @@ -121,7 +122,7 @@ func main() { {Name: ".info", Data: info}, } dir = filepath.Clean(dir) - err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + err = filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error { if !info.Mode().IsRegular() { return nil } diff --git a/src/cmd/go/testdata/savedir.go b/src/cmd/go/testdata/savedir.go index 48a6318860..04902df61e 100644 --- a/src/cmd/go/testdata/savedir.go +++ b/src/cmd/go/testdata/savedir.go @@ -17,6 +17,7 @@ package main import ( "flag" "fmt" + "io/fs" "io/ioutil" "log" "os" @@ -48,7 +49,7 @@ func main() { a := new(txtar.Archive) dir = filepath.Clean(dir) - filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error { if path == dir { return nil } diff --git a/src/cmd/gofmt/gofmt.go b/src/cmd/gofmt/gofmt.go index 8c56af7559..48b6ad6f53 100644 --- a/src/cmd/gofmt/gofmt.go +++ b/src/cmd/gofmt/gofmt.go @@ -14,6 +14,7 @@ import ( "go/scanner" "go/token" "io" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -73,7 +74,7 @@ func initParserMode() { } } -func isGoFile(f os.FileInfo) bool { +func isGoFile(f fs.FileInfo) bool { // ignore non-Go files name := f.Name() return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") @@ -81,7 +82,7 @@ func isGoFile(f os.FileInfo) bool { // If in == nil, the source is the contents of the file with the given filename. func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error { - var perm os.FileMode = 0644 + var perm fs.FileMode = 0644 if in == nil { f, err := os.Open(filename) if err != nil { @@ -163,7 +164,7 @@ func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error return err } -func visitFile(path string, f os.FileInfo, err error) error { +func visitFile(path string, f fs.FileInfo, err error) error { if err == nil && isGoFile(f) { err = processFile(path, nil, os.Stdout, false) } @@ -275,7 +276,7 @@ const chmodSupported = runtime.GOOS != "windows" // backupFile writes data to a new file named filename with permissions perm, // with 0 && name[0] != '.' && // ignore .files @@ -86,7 +86,7 @@ func test(t *testing.T, mode Mode) { if err != nil { t.Fatal(err) } - filter = func(fi os.FileInfo) bool { + filter = func(fi fs.FileInfo) bool { return isGoFile(fi) && rx.MatchString(fi.Name()) } } diff --git a/src/go/doc/headscan.go b/src/go/doc/headscan.go index 3f782cc1b4..8ea462366e 100644 --- a/src/go/doc/headscan.go +++ b/src/go/doc/headscan.go @@ -23,6 +23,7 @@ import ( "go/parser" "go/token" "internal/lazyregexp" + "io/fs" "os" "path/filepath" "runtime" @@ -39,7 +40,7 @@ var html_h = lazyregexp.New(`

`) const html_endh = "

\n" -func isGoFile(fi os.FileInfo) bool { +func isGoFile(fi fs.FileInfo) bool { return strings.HasSuffix(fi.Name(), ".go") && !strings.HasSuffix(fi.Name(), "_test.go") } @@ -68,7 +69,7 @@ func main() { flag.Parse() fset := token.NewFileSet() nheadings := 0 - err := filepath.Walk(*root, func(path string, fi os.FileInfo, err error) error { + err := filepath.Walk(*root, func(path string, fi fs.FileInfo, err error) error { if !fi.IsDir() { return nil } diff --git a/src/go/parser/interface.go b/src/go/parser/interface.go index 54f9d7b80a..b2d834fdec 100644 --- a/src/go/parser/interface.go +++ b/src/go/parser/interface.go @@ -12,8 +12,8 @@ import ( "go/ast" "go/token" "io" + "io/fs" "io/ioutil" - "os" "path/filepath" "strings" ) @@ -123,7 +123,7 @@ func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode) // directory specified by path and returns a map of package name -> package // AST with all the packages found. // -// If filter != nil, only the files with os.FileInfo entries passing through +// If filter != nil, only the files with fs.FileInfo entries passing through // the filter (and ending in ".go") are considered. The mode bits are passed // to ParseFile unchanged. Position information is recorded in fset, which // must not be nil. @@ -132,7 +132,7 @@ func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode) // returned. If a parse error occurred, a non-nil but incomplete map and the // first error encountered are returned. // -func ParseDir(fset *token.FileSet, path string, filter func(os.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error) { +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) if err != nil { return nil, err diff --git a/src/go/parser/parser_test.go b/src/go/parser/parser_test.go index 25a374eeef..7193a329fe 100644 --- a/src/go/parser/parser_test.go +++ b/src/go/parser/parser_test.go @@ -9,7 +9,7 @@ import ( "fmt" "go/ast" "go/token" - "os" + "io/fs" "strings" "testing" ) @@ -40,7 +40,7 @@ func nameFilter(filename string) bool { return false } -func dirFilter(f os.FileInfo) bool { return nameFilter(f.Name()) } +func dirFilter(f fs.FileInfo) bool { return nameFilter(f.Name()) } func TestParseFile(t *testing.T) { src := "package p\nvar _=s[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]" diff --git a/src/index/suffixarray/suffixarray_test.go b/src/index/suffixarray/suffixarray_test.go index 28090de9aa..b6a81123b7 100644 --- a/src/index/suffixarray/suffixarray_test.go +++ b/src/index/suffixarray/suffixarray_test.go @@ -7,9 +7,9 @@ package suffixarray import ( "bytes" "fmt" + "io/fs" "io/ioutil" "math/rand" - "os" "path/filepath" "regexp" "sort" @@ -503,7 +503,7 @@ func makeText(name string) ([]byte, error) { return nil, err } case "go": - err := filepath.Walk("../..", func(path string, info os.FileInfo, err error) error { + err := filepath.Walk("../..", func(path string, info fs.FileInfo, err error) error { if err == nil && strings.HasSuffix(path, ".go") && !info.IsDir() { file, err := ioutil.ReadFile(path) if err != nil { diff --git a/src/internal/poll/error_test.go b/src/internal/poll/error_test.go index 06b96f635a..abc8b1684f 100644 --- a/src/internal/poll/error_test.go +++ b/src/internal/poll/error_test.go @@ -6,6 +6,7 @@ package poll_test import ( "fmt" + "io/fs" "net" "os" "testing" @@ -37,7 +38,7 @@ func parseReadError(nestedErr error, verify func(error) (string, bool)) error { if nerr, ok := err.(*net.OpError); ok { err = nerr.Err } - if nerr, ok := err.(*os.PathError); ok { + if nerr, ok := err.(*fs.PathError); ok { err = nerr.Err } if nerr, ok := err.(*os.SyscallError); ok { diff --git a/src/internal/reflectlite/reflect_mirror_test.go b/src/internal/reflectlite/reflect_mirror_test.go index fbb6fb397e..9b28b13550 100644 --- a/src/internal/reflectlite/reflect_mirror_test.go +++ b/src/internal/reflectlite/reflect_mirror_test.go @@ -9,6 +9,7 @@ import ( "go/ast" "go/parser" "go/token" + "io/fs" "os" "path/filepath" "runtime" @@ -71,7 +72,7 @@ func (v visitor) Visit(n ast.Node) ast.Visitor { func loadTypes(path, pkgName string, v visitor) { fset := token.NewFileSet() - filter := func(fi os.FileInfo) bool { + filter := func(fi fs.FileInfo) bool { return strings.HasSuffix(fi.Name(), ".go") } pkgs, err := parser.ParseDir(fset, path, filter, 0) diff --git a/src/io/ioutil/ioutil.go b/src/io/ioutil/ioutil.go index acc6ec3a40..cae41f0018 100644 --- a/src/io/ioutil/ioutil.go +++ b/src/io/ioutil/ioutil.go @@ -8,6 +8,7 @@ package ioutil import ( "bytes" "io" + "io/fs" "os" "sort" "sync" @@ -76,7 +77,7 @@ func ReadFile(filename string) ([]byte, error) { // WriteFile writes data to a file named by filename. // If the file does not exist, WriteFile creates it with permissions perm // (before umask); otherwise WriteFile truncates it before writing, without changing permissions. -func WriteFile(filename string, data []byte, perm os.FileMode) error { +func WriteFile(filename string, data []byte, perm fs.FileMode) error { f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) if err != nil { return err @@ -90,7 +91,7 @@ func WriteFile(filename string, data []byte, perm os.FileMode) error { // ReadDir reads the directory named by dirname and returns // a list of directory entries sorted by filename. -func ReadDir(dirname string) ([]os.FileInfo, error) { +func ReadDir(dirname string) ([]fs.FileInfo, error) { f, err := os.Open(dirname) if err != nil { return nil, err diff --git a/src/io/ioutil/tempfile_test.go b/src/io/ioutil/tempfile_test.go index fcc5101fcc..440c7cffc6 100644 --- a/src/io/ioutil/tempfile_test.go +++ b/src/io/ioutil/tempfile_test.go @@ -5,6 +5,7 @@ package ioutil_test import ( + "io/fs" . "io/ioutil" "os" "path/filepath" @@ -151,7 +152,7 @@ func TestTempDir_BadDir(t *testing.T) { badDir := filepath.Join(dir, "not-exist") _, err = TempDir(badDir, "foo") - if pe, ok := err.(*os.PathError); !ok || !os.IsNotExist(err) || pe.Path != badDir { + if pe, ok := err.(*fs.PathError); !ok || !os.IsNotExist(err) || pe.Path != badDir { t.Errorf("TempDir error = %#v; want PathError for path %q satisifying os.IsNotExist", err, badDir) } } diff --git a/src/net/conf_test.go b/src/net/conf_test.go index 3c7403eccc..4c21d56ba0 100644 --- a/src/net/conf_test.go +++ b/src/net/conf_test.go @@ -7,7 +7,7 @@ package net import ( - "os" + "io/fs" "strings" "testing" ) @@ -26,7 +26,7 @@ var defaultResolvConf = &dnsConfig{ ndots: 1, timeout: 5, attempts: 2, - err: os.ErrNotExist, + err: fs.ErrNotExist, } func TestConfHostLookupOrder(t *testing.T) { @@ -106,7 +106,7 @@ func TestConfHostLookupOrder(t *testing.T) { name: "solaris_no_nsswitch", c: &conf{ goos: "solaris", - nss: &nssConf{err: os.ErrNotExist}, + nss: &nssConf{err: fs.ErrNotExist}, resolv: defaultResolvConf, }, hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupCgo}}, @@ -176,7 +176,7 @@ func TestConfHostLookupOrder(t *testing.T) { name: "linux_no_nsswitch.conf", c: &conf{ goos: "linux", - nss: &nssConf{err: os.ErrNotExist}, + nss: &nssConf{err: fs.ErrNotExist}, resolv: defaultResolvConf, }, hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupDNSFiles}}, diff --git a/src/net/dnsconfig_unix_test.go b/src/net/dnsconfig_unix_test.go index 42880123c5..0d7897a813 100644 --- a/src/net/dnsconfig_unix_test.go +++ b/src/net/dnsconfig_unix_test.go @@ -8,6 +8,7 @@ package net import ( "errors" + "io/fs" "os" "reflect" "strings" @@ -183,7 +184,7 @@ func TestDNSReadMissingFile(t *testing.T) { conf := dnsReadConfig("a-nonexistent-file") if !os.IsNotExist(conf.err) { - t.Errorf("missing resolv.conf:\ngot: %v\nwant: %v", conf.err, os.ErrNotExist) + t.Errorf("missing resolv.conf:\ngot: %v\nwant: %v", conf.err, fs.ErrNotExist) } conf.err = nil want := &dnsConfig{ diff --git a/src/net/error_test.go b/src/net/error_test.go index 62dfb9c15d..7823fdf9d8 100644 --- a/src/net/error_test.go +++ b/src/net/error_test.go @@ -12,6 +12,7 @@ import ( "fmt" "internal/poll" "io" + "io/fs" "io/ioutil" "net/internal/socktest" "os" @@ -97,7 +98,7 @@ second: case *os.SyscallError: nestedErr = err.Err goto third - case *os.PathError: // for Plan 9 + case *fs.PathError: // for Plan 9 nestedErr = err.Err goto third } @@ -531,7 +532,7 @@ second: case *os.SyscallError: nestedErr = err.Err goto third - case *os.PathError: // for Plan 9 + case *fs.PathError: // for Plan 9 nestedErr = err.Err goto third } @@ -546,7 +547,7 @@ third: return nil } switch nestedErr { - case os.ErrClosed: // for Plan 9 + case fs.ErrClosed: // for Plan 9 return nil } return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr) @@ -627,7 +628,7 @@ second: case *os.SyscallError: nestedErr = err.Err goto third - case *os.PathError: // for Plan 9 + case *fs.PathError: // for Plan 9 nestedErr = err.Err goto third } @@ -706,7 +707,7 @@ second: case *os.LinkError: nestedErr = err.Err goto third - case *os.PathError: + case *fs.PathError: nestedErr = err.Err goto third } @@ -799,7 +800,7 @@ func parseLookupPortError(nestedErr error) error { switch nestedErr.(type) { case *AddrError, *DNSError: return nil - case *os.PathError: // for Plan 9 + case *fs.PathError: // for Plan 9 return nil } return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr) diff --git a/src/net/http/example_filesystem_test.go b/src/net/http/example_filesystem_test.go index e1fd42d049..0e81458a07 100644 --- a/src/net/http/example_filesystem_test.go +++ b/src/net/http/example_filesystem_test.go @@ -5,9 +5,9 @@ package http_test import ( + "io/fs" "log" "net/http" - "os" "strings" ) @@ -33,7 +33,7 @@ type dotFileHidingFile struct { // Readdir is a wrapper around the Readdir method of the embedded File // that filters out all files that start with a period in their name. -func (f dotFileHidingFile) Readdir(n int) (fis []os.FileInfo, err error) { +func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) { files, err := f.File.Readdir(n) for _, file := range files { // Filters out the dot files if !strings.HasPrefix(file.Name(), ".") { @@ -52,12 +52,12 @@ type dotFileHidingFileSystem struct { // Open is a wrapper around the Open method of the embedded FileSystem // that serves a 403 permission error when name has a file or directory // with whose name starts with a period in its path. -func (fs dotFileHidingFileSystem) Open(name string) (http.File, error) { +func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) { if containsDotFile(name) { // If dot file, return 403 response - return nil, os.ErrPermission + return nil, fs.ErrPermission } - file, err := fs.FileSystem.Open(name) + file, err := fsys.FileSystem.Open(name) if err != nil { return nil, err } @@ -65,7 +65,7 @@ func (fs dotFileHidingFileSystem) Open(name string) (http.File, error) { } func ExampleFileServer_dotFileHiding() { - fs := dotFileHidingFileSystem{http.Dir(".")} - http.Handle("/", http.FileServer(fs)) + fsys := dotFileHidingFileSystem{http.Dir(".")} + http.Handle("/", http.FileServer(fsys)) log.Fatal(http.ListenAndServe(":8080", nil)) } diff --git a/src/net/http/fs.go b/src/net/http/fs.go index d718fffba0..0743b5b621 100644 --- a/src/net/http/fs.go +++ b/src/net/http/fs.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "io" + "io/fs" "mime" "mime/multipart" "net/textproto" @@ -43,7 +44,7 @@ type Dir string // mapDirOpenError maps the provided non-nil error from opening name // to a possibly better non-nil error. In particular, it turns OS-specific errors -// about opening files in non-directories into os.ErrNotExist. See Issue 18984. +// about opening files in non-directories into fs.ErrNotExist. See Issue 18984. func mapDirOpenError(originalErr error, name string) error { if os.IsNotExist(originalErr) || os.IsPermission(originalErr) { return originalErr @@ -59,7 +60,7 @@ func mapDirOpenError(originalErr error, name string) error { return originalErr } if !fi.IsDir() { - return os.ErrNotExist + return fs.ErrNotExist } } return originalErr @@ -98,8 +99,8 @@ type File interface { io.Closer io.Reader io.Seeker - Readdir(count int) ([]os.FileInfo, error) - Stat() (os.FileInfo, error) + Readdir(count int) ([]fs.FileInfo, error) + Stat() (fs.FileInfo, error) } func dirList(w ResponseWriter, r *Request, f File) { diff --git a/src/net/http/fs_test.go b/src/net/http/fs_test.go index 4ac73b728f..de793b331e 100644 --- a/src/net/http/fs_test.go +++ b/src/net/http/fs_test.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "io" + "io/fs" "io/ioutil" "mime" "mime/multipart" @@ -629,9 +630,9 @@ func (f *fakeFileInfo) Sys() interface{} { return nil } func (f *fakeFileInfo) ModTime() time.Time { return f.modtime } func (f *fakeFileInfo) IsDir() bool { return f.dir } func (f *fakeFileInfo) Size() int64 { return int64(len(f.contents)) } -func (f *fakeFileInfo) Mode() os.FileMode { +func (f *fakeFileInfo) Mode() fs.FileMode { if f.dir { - return 0755 | os.ModeDir + return 0755 | fs.ModeDir } return 0644 } @@ -644,12 +645,12 @@ type fakeFile struct { } func (f *fakeFile) Close() error { return nil } -func (f *fakeFile) Stat() (os.FileInfo, error) { return f.fi, nil } -func (f *fakeFile) Readdir(count int) ([]os.FileInfo, error) { +func (f *fakeFile) Stat() (fs.FileInfo, error) { return f.fi, nil } +func (f *fakeFile) Readdir(count int) ([]fs.FileInfo, error) { if !f.fi.dir { - return nil, os.ErrInvalid + return nil, fs.ErrInvalid } - var fis []os.FileInfo + var fis []fs.FileInfo limit := f.entpos + count if count <= 0 || limit > len(f.fi.ents) { @@ -668,11 +669,11 @@ func (f *fakeFile) Readdir(count int) ([]os.FileInfo, error) { type fakeFS map[string]*fakeFileInfo -func (fs fakeFS) Open(name string) (File, error) { +func (fsys fakeFS) Open(name string) (File, error) { name = path.Clean(name) - f, ok := fs[name] + f, ok := fsys[name] if !ok { - return nil, os.ErrNotExist + return nil, fs.ErrNotExist } if f.err != nil { return nil, f.err @@ -747,7 +748,7 @@ func TestDirectoryIfNotModified(t *testing.T) { res.Body.Close() } -func mustStat(t *testing.T, fileName string) os.FileInfo { +func mustStat(t *testing.T, fileName string) fs.FileInfo { fi, err := os.Stat(fileName) if err != nil { t.Fatal(err) @@ -1081,7 +1082,7 @@ func (issue12991FS) Open(string) (File, error) { return issue12991File{}, nil } type issue12991File struct{ File } -func (issue12991File) Stat() (os.FileInfo, error) { return nil, os.ErrPermission } +func (issue12991File) Stat() (fs.FileInfo, error) { return nil, fs.ErrPermission } func (issue12991File) Close() error { return nil } func TestServeContentErrorMessages(t *testing.T) { @@ -1091,7 +1092,7 @@ func TestServeContentErrorMessages(t *testing.T) { err: errors.New("random error"), }, "/403": &fakeFileInfo{ - err: &os.PathError{Err: os.ErrPermission}, + err: &fs.PathError{Err: fs.ErrPermission}, }, } ts := httptest.NewServer(FileServer(fs)) @@ -1289,7 +1290,7 @@ func (d fileServerCleanPathDir) Open(path string) (File, error) { // Just return back something that's a directory. return Dir(".").Open(".") } - return nil, os.ErrNotExist + return nil, fs.ErrNotExist } type panicOnSeek struct{ io.ReadSeeker } diff --git a/src/net/ipsock_plan9.go b/src/net/ipsock_plan9.go index 23082366aa..7a4b7a6041 100644 --- a/src/net/ipsock_plan9.go +++ b/src/net/ipsock_plan9.go @@ -7,6 +7,7 @@ package net import ( "context" "internal/bytealg" + "io/fs" "os" "syscall" ) @@ -164,7 +165,7 @@ func fixErr(err error) { if nonNilInterface(oe.Addr) { oe.Addr = nil } - if pe, ok := oe.Err.(*os.PathError); ok { + if pe, ok := oe.Err.(*fs.PathError); ok { if _, ok = pe.Err.(syscall.ErrorString); ok { oe.Err = pe.Err } diff --git a/src/os/error_test.go b/src/os/error_test.go index 3d921578fd..060cf59875 100644 --- a/src/os/error_test.go +++ b/src/os/error_test.go @@ -7,6 +7,7 @@ package os_test import ( "errors" "fmt" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -27,7 +28,7 @@ func TestErrIsExist(t *testing.T) { t.Fatal("Open should have failed") return } - if s := checkErrorPredicate("os.IsExist", os.IsExist, err, os.ErrExist); s != "" { + if s := checkErrorPredicate("os.IsExist", os.IsExist, err, fs.ErrExist); s != "" { t.Fatal(s) return } @@ -39,7 +40,7 @@ func testErrNotExist(name string) string { f.Close() return "Open should have failed" } - if s := checkErrorPredicate("os.IsNotExist", os.IsNotExist, err, os.ErrNotExist); s != "" { + if s := checkErrorPredicate("os.IsNotExist", os.IsNotExist, err, fs.ErrNotExist); s != "" { return s } @@ -47,7 +48,7 @@ func testErrNotExist(name string) string { if err == nil { return "Chdir should have failed" } - if s := checkErrorPredicate("os.IsNotExist", os.IsNotExist, err, os.ErrNotExist); s != "" { + if s := checkErrorPredicate("os.IsNotExist", os.IsNotExist, err, fs.ErrNotExist); s != "" { return s } return "" @@ -91,18 +92,18 @@ type isExistTest struct { } var isExistTests = []isExistTest{ - {&os.PathError{Err: os.ErrInvalid}, false, false}, - {&os.PathError{Err: os.ErrPermission}, false, false}, - {&os.PathError{Err: os.ErrExist}, true, false}, - {&os.PathError{Err: os.ErrNotExist}, false, true}, - {&os.PathError{Err: os.ErrClosed}, false, false}, - {&os.LinkError{Err: os.ErrInvalid}, false, false}, - {&os.LinkError{Err: os.ErrPermission}, false, false}, - {&os.LinkError{Err: os.ErrExist}, true, false}, - {&os.LinkError{Err: os.ErrNotExist}, false, true}, - {&os.LinkError{Err: os.ErrClosed}, false, false}, - {&os.SyscallError{Err: os.ErrNotExist}, false, true}, - {&os.SyscallError{Err: os.ErrExist}, true, false}, + {&fs.PathError{Err: fs.ErrInvalid}, false, false}, + {&fs.PathError{Err: fs.ErrPermission}, false, false}, + {&fs.PathError{Err: fs.ErrExist}, true, false}, + {&fs.PathError{Err: fs.ErrNotExist}, false, true}, + {&fs.PathError{Err: fs.ErrClosed}, false, false}, + {&os.LinkError{Err: fs.ErrInvalid}, false, false}, + {&os.LinkError{Err: fs.ErrPermission}, false, false}, + {&os.LinkError{Err: fs.ErrExist}, true, false}, + {&os.LinkError{Err: fs.ErrNotExist}, false, true}, + {&os.LinkError{Err: fs.ErrClosed}, false, false}, + {&os.SyscallError{Err: fs.ErrNotExist}, false, true}, + {&os.SyscallError{Err: fs.ErrExist}, true, false}, {nil, false, false}, } @@ -111,14 +112,14 @@ func TestIsExist(t *testing.T) { if is := os.IsExist(tt.err); is != tt.is { t.Errorf("os.IsExist(%T %v) = %v, want %v", tt.err, tt.err, is, tt.is) } - if is := errors.Is(tt.err, os.ErrExist); is != tt.is { - t.Errorf("errors.Is(%T %v, os.ErrExist) = %v, want %v", tt.err, tt.err, is, tt.is) + if is := errors.Is(tt.err, fs.ErrExist); is != tt.is { + t.Errorf("errors.Is(%T %v, fs.ErrExist) = %v, want %v", tt.err, tt.err, is, tt.is) } if isnot := os.IsNotExist(tt.err); isnot != tt.isnot { t.Errorf("os.IsNotExist(%T %v) = %v, want %v", tt.err, tt.err, isnot, tt.isnot) } - if isnot := errors.Is(tt.err, os.ErrNotExist); isnot != tt.isnot { - t.Errorf("errors.Is(%T %v, os.ErrNotExist) = %v, want %v", tt.err, tt.err, isnot, tt.isnot) + if isnot := errors.Is(tt.err, fs.ErrNotExist); isnot != tt.isnot { + t.Errorf("errors.Is(%T %v, fs.ErrNotExist) = %v, want %v", tt.err, tt.err, isnot, tt.isnot) } } } @@ -130,8 +131,8 @@ type isPermissionTest struct { var isPermissionTests = []isPermissionTest{ {nil, false}, - {&os.PathError{Err: os.ErrPermission}, true}, - {&os.SyscallError{Err: os.ErrPermission}, true}, + {&fs.PathError{Err: fs.ErrPermission}, true}, + {&os.SyscallError{Err: fs.ErrPermission}, true}, } func TestIsPermission(t *testing.T) { @@ -139,8 +140,8 @@ func TestIsPermission(t *testing.T) { if got := os.IsPermission(tt.err); got != tt.want { t.Errorf("os.IsPermission(%#v) = %v; want %v", tt.err, got, tt.want) } - if got := errors.Is(tt.err, os.ErrPermission); got != tt.want { - t.Errorf("errors.Is(%#v, os.ErrPermission) = %v; want %v", tt.err, got, tt.want) + if got := errors.Is(tt.err, fs.ErrPermission); got != tt.want { + t.Errorf("errors.Is(%#v, fs.ErrPermission) = %v; want %v", tt.err, got, tt.want) } } } @@ -170,8 +171,8 @@ func TestErrPathNUL(t *testing.T) { } func TestPathErrorUnwrap(t *testing.T) { - pe := &os.PathError{Err: os.ErrInvalid} - if !errors.Is(pe, os.ErrInvalid) { + pe := &fs.PathError{Err: fs.ErrInvalid} + if !errors.Is(pe, fs.ErrInvalid) { t.Error("errors.Is failed, wanted success") } } @@ -181,7 +182,7 @@ type myErrorIs struct{ error } func (e myErrorIs) Is(target error) bool { return target == e.error } func TestErrorIsMethods(t *testing.T) { - if os.IsPermission(myErrorIs{os.ErrPermission}) { - t.Error("os.IsPermission(err) = true when err.Is(os.ErrPermission), wanted false") + if os.IsPermission(myErrorIs{fs.ErrPermission}) { + t.Error("os.IsPermission(err) = true when err.Is(fs.ErrPermission), wanted false") } } diff --git a/src/os/error_unix_test.go b/src/os/error_unix_test.go index bfc83c9867..18bcf3f4e4 100644 --- a/src/os/error_unix_test.go +++ b/src/os/error_unix_test.go @@ -7,14 +7,15 @@ package os_test import ( + "io/fs" "os" "syscall" ) func init() { isExistTests = append(isExistTests, - isExistTest{err: &os.PathError{Err: syscall.EEXIST}, is: true, isnot: false}, - isExistTest{err: &os.PathError{Err: syscall.ENOTEMPTY}, is: true, isnot: false}, + isExistTest{err: &fs.PathError{Err: syscall.EEXIST}, is: true, isnot: false}, + isExistTest{err: &fs.PathError{Err: syscall.ENOTEMPTY}, is: true, isnot: false}, isExistTest{err: &os.LinkError{Err: syscall.EEXIST}, is: true, isnot: false}, isExistTest{err: &os.LinkError{Err: syscall.ENOTEMPTY}, is: true, isnot: false}, @@ -23,9 +24,9 @@ func init() { isExistTest{err: &os.SyscallError{Err: syscall.ENOTEMPTY}, is: true, isnot: false}, ) isPermissionTests = append(isPermissionTests, - isPermissionTest{err: &os.PathError{Err: syscall.EACCES}, want: true}, - isPermissionTest{err: &os.PathError{Err: syscall.EPERM}, want: true}, - isPermissionTest{err: &os.PathError{Err: syscall.EEXIST}, want: false}, + isPermissionTest{err: &fs.PathError{Err: syscall.EACCES}, want: true}, + isPermissionTest{err: &fs.PathError{Err: syscall.EPERM}, want: true}, + isPermissionTest{err: &fs.PathError{Err: syscall.EEXIST}, want: false}, isPermissionTest{err: &os.LinkError{Err: syscall.EACCES}, want: true}, isPermissionTest{err: &os.LinkError{Err: syscall.EPERM}, want: true}, diff --git a/src/os/error_windows_test.go b/src/os/error_windows_test.go index 1635c1088e..b8191c5ebc 100644 --- a/src/os/error_windows_test.go +++ b/src/os/error_windows_test.go @@ -7,6 +7,7 @@ package os_test import ( + "io/fs" "os" "syscall" ) @@ -15,24 +16,24 @@ func init() { const _ERROR_BAD_NETPATH = syscall.Errno(53) isExistTests = append(isExistTests, - isExistTest{err: &os.PathError{Err: syscall.ERROR_FILE_NOT_FOUND}, is: false, isnot: true}, + isExistTest{err: &fs.PathError{Err: syscall.ERROR_FILE_NOT_FOUND}, is: false, isnot: true}, isExistTest{err: &os.LinkError{Err: syscall.ERROR_FILE_NOT_FOUND}, is: false, isnot: true}, isExistTest{err: &os.SyscallError{Err: syscall.ERROR_FILE_NOT_FOUND}, is: false, isnot: true}, - isExistTest{err: &os.PathError{Err: _ERROR_BAD_NETPATH}, is: false, isnot: true}, + isExistTest{err: &fs.PathError{Err: _ERROR_BAD_NETPATH}, is: false, isnot: true}, isExistTest{err: &os.LinkError{Err: _ERROR_BAD_NETPATH}, is: false, isnot: true}, isExistTest{err: &os.SyscallError{Err: _ERROR_BAD_NETPATH}, is: false, isnot: true}, - isExistTest{err: &os.PathError{Err: syscall.ERROR_PATH_NOT_FOUND}, is: false, isnot: true}, + isExistTest{err: &fs.PathError{Err: syscall.ERROR_PATH_NOT_FOUND}, is: false, isnot: true}, isExistTest{err: &os.LinkError{Err: syscall.ERROR_PATH_NOT_FOUND}, is: false, isnot: true}, isExistTest{err: &os.SyscallError{Err: syscall.ERROR_PATH_NOT_FOUND}, is: false, isnot: true}, - isExistTest{err: &os.PathError{Err: syscall.ERROR_DIR_NOT_EMPTY}, is: true, isnot: false}, + isExistTest{err: &fs.PathError{Err: syscall.ERROR_DIR_NOT_EMPTY}, is: true, isnot: false}, isExistTest{err: &os.LinkError{Err: syscall.ERROR_DIR_NOT_EMPTY}, is: true, isnot: false}, isExistTest{err: &os.SyscallError{Err: syscall.ERROR_DIR_NOT_EMPTY}, is: true, isnot: false}, ) isPermissionTests = append(isPermissionTests, - isPermissionTest{err: &os.PathError{Err: syscall.ERROR_ACCESS_DENIED}, want: true}, + isPermissionTest{err: &fs.PathError{Err: syscall.ERROR_ACCESS_DENIED}, want: true}, isPermissionTest{err: &os.LinkError{Err: syscall.ERROR_ACCESS_DENIED}, want: true}, isPermissionTest{err: &os.SyscallError{Err: syscall.ERROR_ACCESS_DENIED}, want: true}, ) diff --git a/src/os/example_test.go b/src/os/example_test.go index 822886f70c..fbb277b6f1 100644 --- a/src/os/example_test.go +++ b/src/os/example_test.go @@ -6,6 +6,7 @@ package os_test import ( "fmt" + "io/fs" "log" "os" "time" @@ -62,9 +63,9 @@ func ExampleFileMode() { fmt.Println("regular file") case mode.IsDir(): fmt.Println("directory") - case mode&os.ModeSymlink != 0: + case mode&fs.ModeSymlink != 0: fmt.Println("symbolic link") - case mode&os.ModeNamedPipe != 0: + case mode&fs.ModeNamedPipe != 0: fmt.Println("named pipe") } } diff --git a/src/os/exec/exec_plan9.go b/src/os/exec/exec_plan9.go index d90bd04399..21ac7b765f 100644 --- a/src/os/exec/exec_plan9.go +++ b/src/os/exec/exec_plan9.go @@ -4,14 +4,14 @@ package exec -import "os" +import "io/fs" func init() { skipStdinCopyError = func(err error) bool { // Ignore hungup errors copying to stdin if the program // completed successfully otherwise. // See Issue 35753. - pe, ok := err.(*os.PathError) + pe, ok := err.(*fs.PathError) return ok && pe.Op == "write" && pe.Path == "|1" && pe.Err.Error() == "i/o on hungup channel" diff --git a/src/os/exec/exec_unix.go b/src/os/exec/exec_unix.go index 9c3e17d23a..51c52427c2 100644 --- a/src/os/exec/exec_unix.go +++ b/src/os/exec/exec_unix.go @@ -7,7 +7,7 @@ package exec import ( - "os" + "io/fs" "syscall" ) @@ -16,7 +16,7 @@ func init() { // Ignore EPIPE errors copying to stdin if the program // completed successfully otherwise. // See Issue 9173. - pe, ok := err.(*os.PathError) + pe, ok := err.(*fs.PathError) return ok && pe.Op == "write" && pe.Path == "|1" && pe.Err == syscall.EPIPE diff --git a/src/os/exec/exec_windows.go b/src/os/exec/exec_windows.go index af8cd97218..bb937f8aed 100644 --- a/src/os/exec/exec_windows.go +++ b/src/os/exec/exec_windows.go @@ -5,7 +5,7 @@ package exec import ( - "os" + "io/fs" "syscall" ) @@ -15,7 +15,7 @@ func init() { // to stdin if the program completed successfully otherwise. // See Issue 20445. const _ERROR_NO_DATA = syscall.Errno(0xe8) - pe, ok := err.(*os.PathError) + pe, ok := err.(*fs.PathError) return ok && pe.Op == "write" && pe.Path == "|1" && (pe.Err == syscall.ERROR_BROKEN_PIPE || pe.Err == _ERROR_NO_DATA) diff --git a/src/os/exec/lp_plan9.go b/src/os/exec/lp_plan9.go index 5860cbca4d..e8826a5083 100644 --- a/src/os/exec/lp_plan9.go +++ b/src/os/exec/lp_plan9.go @@ -6,6 +6,7 @@ package exec import ( "errors" + "io/fs" "os" "path/filepath" "strings" @@ -22,7 +23,7 @@ func findExecutable(file string) error { if m := d.Mode(); !m.IsDir() && m&0111 != 0 { return nil } - return os.ErrPermission + return fs.ErrPermission } // LookPath searches for an executable named file in the diff --git a/src/os/exec/lp_unix.go b/src/os/exec/lp_unix.go index 93793e0eee..66c1df76fb 100644 --- a/src/os/exec/lp_unix.go +++ b/src/os/exec/lp_unix.go @@ -8,6 +8,7 @@ package exec import ( "errors" + "io/fs" "os" "path/filepath" "strings" @@ -24,7 +25,7 @@ func findExecutable(file string) error { if m := d.Mode(); !m.IsDir() && m&0111 != 0 { return nil } - return os.ErrPermission + return fs.ErrPermission } // LookPath searches for an executable named file in the diff --git a/src/os/exec/lp_windows.go b/src/os/exec/lp_windows.go index 9ea3d76575..e7a2cdf142 100644 --- a/src/os/exec/lp_windows.go +++ b/src/os/exec/lp_windows.go @@ -6,6 +6,7 @@ package exec import ( "errors" + "io/fs" "os" "path/filepath" "strings" @@ -20,7 +21,7 @@ func chkStat(file string) error { return err } if d.IsDir() { - return os.ErrPermission + return fs.ErrPermission } return nil } @@ -47,7 +48,7 @@ func findExecutable(file string, exts []string) (string, error) { return f, nil } } - return "", os.ErrNotExist + return "", fs.ErrNotExist } // LookPath searches for an executable named file in the diff --git a/src/os/os_test.go b/src/os/os_test.go index c692ba099f..8f14263401 100644 --- a/src/os/os_test.go +++ b/src/os/os_test.go @@ -2526,7 +2526,7 @@ func testDoubleCloseError(t *testing.T, path string) { if err := file.Close(); err == nil { t.Error("second Close did not fail") } else if pe, ok := err.(*PathError); !ok { - t.Errorf("second Close returned unexpected error type %T; expected os.PathError", pe) + t.Errorf("second Close returned unexpected error type %T; expected fs.PathError", pe) } else if pe.Err != ErrClosed { t.Errorf("second Close returned %q, wanted %q", err, ErrClosed) } else { diff --git a/src/os/os_windows_test.go b/src/os/os_windows_test.go index f03ec750d0..e002774844 100644 --- a/src/os/os_windows_test.go +++ b/src/os/os_windows_test.go @@ -12,6 +12,7 @@ import ( "internal/syscall/windows/registry" "internal/testenv" "io" + "io/fs" "io/ioutil" "os" osexec "os/exec" @@ -164,11 +165,11 @@ func testDirLinks(t *testing.T, tests []dirLinkTest) { t.Errorf("failed to lstat link %v: %v", link, err) continue } - if m := fi2.Mode(); m&os.ModeSymlink == 0 { + if m := fi2.Mode(); m&fs.ModeSymlink == 0 { t.Errorf("%q should be a link, but is not (mode=0x%x)", link, uint32(m)) continue } - if m := fi2.Mode(); m&os.ModeDir != 0 { + if m := fi2.Mode(); m&fs.ModeDir != 0 { t.Errorf("%q should be a link, not a directory (mode=0x%x)", link, uint32(m)) continue } @@ -681,7 +682,7 @@ func TestStatSymlinkLoop(t *testing.T) { defer os.Remove("x") _, err = os.Stat("x") - if _, ok := err.(*os.PathError); !ok { + if _, ok := err.(*fs.PathError); !ok { t.Errorf("expected *PathError, got %T: %v\n", err, err) } } @@ -1291,9 +1292,9 @@ func TestWindowsReadlink(t *testing.T) { // os.Mkdir(os.DevNull) fails. func TestMkdirDevNull(t *testing.T) { err := os.Mkdir(os.DevNull, 777) - oserr, ok := err.(*os.PathError) + oserr, ok := err.(*fs.PathError) if !ok { - t.Fatalf("error (%T) is not *os.PathError", err) + t.Fatalf("error (%T) is not *fs.PathError", err) } errno, ok := oserr.Err.(syscall.Errno) if !ok { diff --git a/src/os/pipe_test.go b/src/os/pipe_test.go index 429bd813c2..0593efec75 100644 --- a/src/os/pipe_test.go +++ b/src/os/pipe_test.go @@ -13,6 +13,7 @@ import ( "fmt" "internal/testenv" "io" + "io/fs" "io/ioutil" "os" osexec "os/exec" @@ -46,7 +47,7 @@ func TestEPIPE(t *testing.T) { if err == nil { t.Fatal("unexpected success of Write to broken pipe") } - if pe, ok := err.(*os.PathError); ok { + if pe, ok := err.(*fs.PathError); ok { err = pe.Err } if se, ok := err.(*os.SyscallError); ok { @@ -202,10 +203,10 @@ func testClosedPipeRace(t *testing.T, read bool) { } if err == nil { t.Error("I/O on closed pipe unexpectedly succeeded") - } else if pe, ok := err.(*os.PathError); !ok { - t.Errorf("I/O on closed pipe returned unexpected error type %T; expected os.PathError", pe) - } else if pe.Err != os.ErrClosed { - t.Errorf("got error %q but expected %q", pe.Err, os.ErrClosed) + } else if pe, ok := err.(*fs.PathError); !ok { + t.Errorf("I/O on closed pipe returned unexpected error type %T; expected fs.PathError", pe) + } else if pe.Err != fs.ErrClosed { + t.Errorf("got error %q but expected %q", pe.Err, fs.ErrClosed) } else { t.Logf("I/O returned expected error %q", err) } @@ -233,7 +234,7 @@ func TestReadNonblockingFd(t *testing.T) { defer syscall.SetNonblock(fd, false) _, err := os.Stdin.Read(make([]byte, 1)) if err != nil { - if perr, ok := err.(*os.PathError); !ok || perr.Err != syscall.EAGAIN { + if perr, ok := err.(*fs.PathError); !ok || perr.Err != syscall.EAGAIN { t.Fatalf("read on nonblocking stdin got %q, should have gotten EAGAIN", err) } } @@ -308,10 +309,10 @@ func testCloseWithBlockingRead(t *testing.T, r, w *os.File) { if err == nil { t.Error("I/O on closed pipe unexpectedly succeeded") } - if pe, ok := err.(*os.PathError); ok { + if pe, ok := err.(*fs.PathError); ok { err = pe.Err } - if err != io.EOF && err != os.ErrClosed { + if err != io.EOF && err != fs.ErrClosed { t.Errorf("got %v, expected EOF or closed", err) } }(c2) diff --git a/src/os/removeall_test.go b/src/os/removeall_test.go index 1e5c650fe1..bc9c468ce3 100644 --- a/src/os/removeall_test.go +++ b/src/os/removeall_test.go @@ -359,7 +359,7 @@ func TestRemoveAllButReadOnlyAndPathError(t *testing.T) { t.Errorf("got %q, expected pathErr.path %q", g, w) } } else { - t.Errorf("got %T, expected *os.PathError", err) + t.Errorf("got %T, expected *fs.PathError", err) } for _, dir := range dirs { diff --git a/src/os/signal/signal_cgo_test.go b/src/os/signal/signal_cgo_test.go index a117221400..a8a485613f 100644 --- a/src/os/signal/signal_cgo_test.go +++ b/src/os/signal/signal_cgo_test.go @@ -17,6 +17,7 @@ import ( "context" "fmt" "io" + "io/fs" "os" "os/exec" ptypkg "os/signal/internal/pty" @@ -127,7 +128,7 @@ func TestTerminalSignal(t *testing.T) { if len(line) > 0 || len(handled) > 0 { t.Logf("%q", append(handled, line...)) } - if perr, ok := err.(*os.PathError); ok { + if perr, ok := err.(*fs.PathError); ok { err = perr.Err } // EOF means pty is closed. diff --git a/src/os/stat_test.go b/src/os/stat_test.go index 60f3b4c587..88b789080e 100644 --- a/src/os/stat_test.go +++ b/src/os/stat_test.go @@ -6,6 +6,7 @@ package os_test import ( "internal/testenv" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -14,7 +15,7 @@ import ( ) // testStatAndLstat verifies that all os.Stat, os.Lstat os.File.Stat and os.Readdir work. -func testStatAndLstat(t *testing.T, path string, isLink bool, statCheck, lstatCheck func(*testing.T, string, os.FileInfo)) { +func testStatAndLstat(t *testing.T, path string, isLink bool, statCheck, lstatCheck func(*testing.T, string, fs.FileInfo)) { // test os.Stat sfi, err := os.Stat(path) if err != nil { @@ -70,7 +71,7 @@ func testStatAndLstat(t *testing.T, path string, isLink bool, statCheck, lstatCh } } - // test os.FileInfo returned by os.Readdir + // test fs.FileInfo returned by os.Readdir if len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) { // skip os.Readdir test of directories with slash at the end return @@ -88,7 +89,7 @@ func testStatAndLstat(t *testing.T, path string, isLink bool, statCheck, lstatCh t.Error(err) return } - var lsfi2 os.FileInfo + var lsfi2 fs.FileInfo base := filepath.Base(path) for _, fi2 := range fis { if fi2.Name() == base { @@ -108,34 +109,34 @@ func testStatAndLstat(t *testing.T, path string, isLink bool, statCheck, lstatCh } // testIsDir verifies that fi refers to directory. -func testIsDir(t *testing.T, path string, fi os.FileInfo) { +func testIsDir(t *testing.T, path string, fi fs.FileInfo) { t.Helper() if !fi.IsDir() { t.Errorf("%q should be a directory", path) } - if fi.Mode()&os.ModeSymlink != 0 { + if fi.Mode()&fs.ModeSymlink != 0 { t.Errorf("%q should not be a symlink", path) } } // testIsSymlink verifies that fi refers to symlink. -func testIsSymlink(t *testing.T, path string, fi os.FileInfo) { +func testIsSymlink(t *testing.T, path string, fi fs.FileInfo) { t.Helper() if fi.IsDir() { t.Errorf("%q should not be a directory", path) } - if fi.Mode()&os.ModeSymlink == 0 { + if fi.Mode()&fs.ModeSymlink == 0 { t.Errorf("%q should be a symlink", path) } } // testIsFile verifies that fi refers to file. -func testIsFile(t *testing.T, path string, fi os.FileInfo) { +func testIsFile(t *testing.T, path string, fi fs.FileInfo) { t.Helper() if fi.IsDir() { t.Errorf("%q should not be a directory", path) } - if fi.Mode()&os.ModeSymlink != 0 { + if fi.Mode()&fs.ModeSymlink != 0 { t.Errorf("%q should not be a symlink", path) } } diff --git a/src/path/filepath/example_unix_walk_test.go b/src/path/filepath/example_unix_walk_test.go index fa8b8e393b..66dc7f6b53 100644 --- a/src/path/filepath/example_unix_walk_test.go +++ b/src/path/filepath/example_unix_walk_test.go @@ -8,6 +8,7 @@ package filepath_test import ( "fmt" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -40,7 +41,7 @@ func ExampleWalk() { subDirToSkip := "skip" fmt.Println("On Unix:") - err = filepath.Walk(".", func(path string, info os.FileInfo, err error) error { + err = filepath.Walk(".", func(path string, info fs.FileInfo, err error) error { if err != nil { fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err) return err diff --git a/src/path/filepath/path.go b/src/path/filepath/path.go index 26f1833189..dffd27db14 100644 --- a/src/path/filepath/path.go +++ b/src/path/filepath/path.go @@ -13,6 +13,7 @@ package filepath import ( "errors" + "io/fs" "os" "sort" "strings" @@ -339,7 +340,7 @@ var SkipDir = errors.New("skip this directory") // visited by Walk. The path argument contains the argument to Walk as a // prefix; that is, if Walk is called with "dir", which is a directory // containing the file "a", the walk function will be called with argument -// "dir/a". The info argument is the os.FileInfo for the named path. +// "dir/a". The info argument is the fs.FileInfo for the named path. // // If there was a problem walking to the file or directory named by path, the // incoming error will describe the problem and the function can decide how @@ -350,12 +351,12 @@ var SkipDir = errors.New("skip this directory") // Walk skips the directory's contents entirely. If the function returns SkipDir // when invoked on a non-directory file, Walk skips the remaining files in the // containing directory. -type WalkFunc func(path string, info os.FileInfo, err error) error +type WalkFunc func(path string, info fs.FileInfo, err error) error var lstat = os.Lstat // for testing // walk recursively descends path, calling walkFn. -func walk(path string, info os.FileInfo, walkFn WalkFunc) error { +func walk(path string, info fs.FileInfo, walkFn WalkFunc) error { if !info.IsDir() { return walkFn(path, info, nil) } diff --git a/src/path/filepath/path_test.go b/src/path/filepath/path_test.go index 6a8700e413..7dc8b60c28 100644 --- a/src/path/filepath/path_test.go +++ b/src/path/filepath/path_test.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "internal/testenv" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -393,7 +394,7 @@ func checkMarks(t *testing.T, report bool) { // Assumes that each node name is unique. Good enough for a test. // If clear is true, any incoming error is cleared before return. The errors // are always accumulated, though. -func mark(info os.FileInfo, err error, errors *[]error, clear bool) error { +func mark(info fs.FileInfo, err error, errors *[]error, clear bool) error { name := info.Name() walkTree(tree, tree.name, func(path string, n *Node) { if n.name == name { @@ -454,7 +455,7 @@ func TestWalk(t *testing.T) { makeTree(t) errors := make([]error, 0, 10) clear := true - markFn := func(path string, info os.FileInfo, err error) error { + markFn := func(path string, info fs.FileInfo, err error) error { return mark(info, err, &errors, clear) } // Expect no errors. @@ -543,7 +544,7 @@ func TestWalkSkipDirOnFile(t *testing.T) { touch(t, filepath.Join(td, "dir/foo2")) sawFoo2 := false - walker := func(path string, info os.FileInfo, err error) error { + walker := func(path string, info fs.FileInfo, err error) error { if strings.HasSuffix(path, "foo2") { sawFoo2 = true } @@ -589,14 +590,14 @@ func TestWalkFileError(t *testing.T) { *filepath.LstatP = os.Lstat }() statErr := errors.New("some stat error") - *filepath.LstatP = func(path string) (os.FileInfo, error) { + *filepath.LstatP = func(path string) (fs.FileInfo, error) { if strings.HasSuffix(path, "stat-error") { return nil, statErr } return os.Lstat(path) } got := map[string]error{} - err = filepath.Walk(td, func(path string, fi os.FileInfo, err error) error { + err = filepath.Walk(td, func(path string, fi fs.FileInfo, err error) error { rel, _ := filepath.Rel(td, path) got[filepath.ToSlash(rel)] = err return nil @@ -1289,7 +1290,7 @@ func TestBug3486(t *testing.T) { // https://golang.org/issue/3486 ken := filepath.Join(root, "ken") seenBugs := false seenKen := false - err = filepath.Walk(root, func(pth string, info os.FileInfo, err error) error { + err = filepath.Walk(root, func(pth string, info fs.FileInfo, err error) error { if err != nil { t.Fatal(err) } @@ -1338,7 +1339,7 @@ func testWalkSymlink(t *testing.T, mklink func(target, link string) error) { } var visited []string - err = filepath.Walk(tmpdir, func(path string, info os.FileInfo, err error) error { + err = filepath.Walk(tmpdir, func(path string, info fs.FileInfo, err error) error { if err != nil { t.Fatal(err) } diff --git a/src/path/filepath/path_windows_test.go b/src/path/filepath/path_windows_test.go index f7c454bf65..990f18614d 100644 --- a/src/path/filepath/path_windows_test.go +++ b/src/path/filepath/path_windows_test.go @@ -8,6 +8,7 @@ import ( "flag" "fmt" "internal/testenv" + "io/fs" "io/ioutil" "os" "os/exec" @@ -34,7 +35,7 @@ func testWinSplitListTestIsValid(t *testing.T, ti int, tt SplitListTest, const ( cmdfile = `printdir.cmd` - perm os.FileMode = 0700 + perm fs.FileMode = 0700 ) tmp, err := ioutil.TempDir("", "testWinSplitListTestIsValid") diff --git a/src/path/filepath/symlink.go b/src/path/filepath/symlink.go index 335b315a20..6fefd15977 100644 --- a/src/path/filepath/symlink.go +++ b/src/path/filepath/symlink.go @@ -6,6 +6,7 @@ package filepath import ( "errors" + "io/fs" "os" "runtime" "syscall" @@ -85,7 +86,7 @@ func walkSymlinks(path string) (string, error) { return "", err } - if fi.Mode()&os.ModeSymlink == 0 { + if fi.Mode()&fs.ModeSymlink == 0 { if !fi.Mode().IsDir() && end < len(path) { return "", syscall.ENOTDIR } diff --git a/src/runtime/testdata/testprogcgo/exec.go b/src/runtime/testdata/testprogcgo/exec.go index 94da5dc526..15723c7369 100644 --- a/src/runtime/testdata/testprogcgo/exec.go +++ b/src/runtime/testdata/testprogcgo/exec.go @@ -31,6 +31,7 @@ import "C" import ( "fmt" + "io/fs" "os" "os/exec" "os/signal" @@ -98,7 +99,7 @@ func CgoExecSignalMask() { // isEAGAIN reports whether err is an EAGAIN error from a process execution. func isEAGAIN(err error) bool { - if p, ok := err.(*os.PathError); ok { + if p, ok := err.(*fs.PathError); ok { err = p.Err } return err == syscall.EAGAIN diff --git a/src/syscall/syscall_js.go b/src/syscall/syscall_js.go index dfb4a275e3..0ab8c3fba4 100644 --- a/src/syscall/syscall_js.go +++ b/src/syscall/syscall_js.go @@ -49,7 +49,7 @@ const PathMax = 256 // using errors.Is. For example: // // _, _, err := syscall.Syscall(...) -// if errors.Is(err, os.ErrNotExist) ... +// if errors.Is(err, fs.ErrNotExist) ... type Errno uintptr func (e Errno) Error() string { diff --git a/src/syscall/syscall_linux_test.go b/src/syscall/syscall_linux_test.go index c5008f2913..93a4d236d8 100644 --- a/src/syscall/syscall_linux_test.go +++ b/src/syscall/syscall_linux_test.go @@ -8,6 +8,7 @@ import ( "bufio" "fmt" "io" + "io/fs" "io/ioutil" "os" "os/exec" @@ -353,7 +354,7 @@ func TestSyscallNoError(t *testing.T) { t.Fatalf("failed to chown test binary %q, %v", tmpBinary, err) } - err = os.Chmod(tmpBinary, 0755|os.ModeSetuid) + err = os.Chmod(tmpBinary, 0755|fs.ModeSetuid) if err != nil { t.Fatalf("failed to set setuid bit on test binary %q, %v", tmpBinary, err) } diff --git a/src/syscall/syscall_plan9.go b/src/syscall/syscall_plan9.go index 1648e409b0..d16cad45d8 100644 --- a/src/syscall/syscall_plan9.go +++ b/src/syscall/syscall_plan9.go @@ -25,7 +25,7 @@ const bitSize16 = 2 // using errors.Is. For example: // // _, _, err := syscall.Syscall(...) -// if errors.Is(err, os.ErrNotExist) ... +// if errors.Is(err, fs.ErrNotExist) ... type ErrorString string func (e ErrorString) Error() string { return string(e) } diff --git a/src/syscall/syscall_unix.go b/src/syscall/syscall_unix.go index 91c939e0ea..786ad34170 100644 --- a/src/syscall/syscall_unix.go +++ b/src/syscall/syscall_unix.go @@ -110,7 +110,7 @@ func (m *mmapper) Munmap(data []byte) (err error) { // using errors.Is. For example: // // _, _, err := syscall.Syscall(...) -// if errors.Is(err, os.ErrNotExist) ... +// if errors.Is(err, fs.ErrNotExist) ... type Errno uintptr func (e Errno) Error() string { diff --git a/src/syscall/syscall_windows.go b/src/syscall/syscall_windows.go index f62c00d72f..40c43de84c 100644 --- a/src/syscall/syscall_windows.go +++ b/src/syscall/syscall_windows.go @@ -106,7 +106,7 @@ func UTF16PtrFromString(s string) (*uint16, error) { // using errors.Is. For example: // // _, _, err := syscall.Syscall(...) -// if errors.Is(err, os.ErrNotExist) ... +// if errors.Is(err, fs.ErrNotExist) ... type Errno uintptr func langid(pri, sub uint16) uint32 { return uint32(sub)<<10 | uint32(pri) } -- 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/path/filepath') 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 94887410d41eb29ea4f2354e80a6aae4ee602fcf Mon Sep 17 00:00:00 2001 From: Kevin Parsons Date: Tue, 20 Oct 2020 15:15:23 +0000 Subject: path/filepath: allow EvalSymlinks to work on UNC share roots on Windows Fixes #42079 Previously, EvalSymlinks returned an error when called with the root of a UNC share (e.g. \\server\share). This was due to Windows's FindFirstFile function not supporting a share root path. To resolve this, now return early from toNorm in the case where the path after the volume name is empty. Skipping the later path component resolution shouldn't have any negative impact in this case, as if the path is empty, there aren't any path components to resolve anyways. The test case uses the localhost admin share (c$), as it should be present in most situations. This allows testing without setting up an external file share. However, this fix applies to all UNC share root paths. Change-Id: I05035bd86be93662d7bea34fab4b75fc8e918206 GitHub-Last-Rev: bd3db2cda65aae1cdf8d94b03bc7197dff68dc44 GitHub-Pull-Request: golang/go#42096 Reviewed-on: https://go-review.googlesource.com/c/go/+/263917 Trust: Alex Brainman Trust: Giovanni Bajo Run-TryBot: Alex Brainman Reviewed-by: Alex Brainman --- src/path/filepath/path_windows_test.go | 3 +++ src/path/filepath/symlink_windows.go | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'src/path/filepath') diff --git a/src/path/filepath/path_windows_test.go b/src/path/filepath/path_windows_test.go index 990f18614d..9309a7dc4d 100644 --- a/src/path/filepath/path_windows_test.go +++ b/src/path/filepath/path_windows_test.go @@ -413,6 +413,9 @@ func TestToNorm(t *testing.T) { {`{{tmp}}\test`, `.\foo\bar`, `foo\bar`}, {`{{tmp}}\test`, `foo\..\foo\bar`, `foo\bar`}, {`{{tmp}}\test`, `FOO\BAR`, `foo\bar`}, + + // test UNC paths + {".", `\\localhost\c$`, `\\localhost\c$`}, } tmp, err := ioutil.TempDir("", "testToNorm") diff --git a/src/path/filepath/symlink_windows.go b/src/path/filepath/symlink_windows.go index a799488c18..d72279e2bb 100644 --- a/src/path/filepath/symlink_windows.go +++ b/src/path/filepath/symlink_windows.go @@ -68,7 +68,7 @@ func toNorm(path string, normBase func(string) (string, error)) (string, error) path = path[len(volume):] // skip special cases - if path == "." || path == `\` { + if path == "" || path == "." || path == `\` { return volume + path, nil } -- cgit v1.3 From fd841f65368906923e287afab91857043036459d Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Thu, 29 Oct 2020 12:20:53 -0400 Subject: path/filepath: add WalkDir WalkDir is like Walk but can use ReadDir to read directories, instead of Readdirnames + Lstat on every entry, which is usually a significant performance improvement. (The Lstat can still happen if the walk function calls d.Info.) Fixes #42027. Change-Id: Ie11024b23be2656e320d41fd81ff0d8810aa729e Reviewed-on: https://go-review.googlesource.com/c/go/+/266240 Trust: Russ Cox Run-TryBot: Russ Cox TryBot-Result: Go Bot Reviewed-by: Rob Pike --- src/path/filepath/export_test.go | 2 + src/path/filepath/path.go | 213 ++++++++++++++++++++++++++++++++++----- src/path/filepath/path_test.go | 89 ++++++++++------ 3 files changed, 250 insertions(+), 54 deletions(-) (limited to 'src/path/filepath') diff --git a/src/path/filepath/export_test.go b/src/path/filepath/export_test.go index 0cf9e3bca1..e7ad7dd01a 100644 --- a/src/path/filepath/export_test.go +++ b/src/path/filepath/export_test.go @@ -5,3 +5,5 @@ package filepath var LstatP = &lstat + +type DirEntryFromInfo = dirEntryFromInfo diff --git a/src/path/filepath/path.go b/src/path/filepath/path.go index dffd27db14..3f7e5c713d 100644 --- a/src/path/filepath/path.go +++ b/src/path/filepath/path.go @@ -336,25 +336,130 @@ func Rel(basepath, targpath string) (string, error) { // as an error by any function. var SkipDir = errors.New("skip this directory") -// WalkFunc is the type of the function called for each file or directory -// visited by Walk. The path argument contains the argument to Walk as a -// prefix; that is, if Walk is called with "dir", which is a directory -// containing the file "a", the walk function will be called with argument -// "dir/a". The info argument is the fs.FileInfo for the named path. -// -// If there was a problem walking to the file or directory named by path, the -// incoming error will describe the problem and the function can decide how -// to handle that error (and Walk will not descend into that directory). In the -// case of an error, the info argument will be nil. If an error is returned, -// processing stops. The sole exception is when the function returns the special -// value SkipDir. If the function returns SkipDir when invoked on a directory, -// Walk skips the directory's contents entirely. If the function returns SkipDir -// when invoked on a non-directory file, Walk skips the remaining files in the -// containing directory. +// WalkDirFunc is the type of the function called by WalkDir to visit +// each each file or directory. +// +// The path argument contains the argument to Walk as a prefix. +// That is, if Walk is called with root argument "dir" and finds a file +// named "a" in that directory, the walk function will be called with +// argument "dir/a". +// +// The directory and file are joined with Join, which may clean the +// directory name: if Walk is called with the root argument "x/../dir" +// and finds a file named "a" in that directory, the walk function will +// be called with argument "dir/a", not "x/../dir/a". +// +// The d argument is the fs.DirEntry for the named path. +// +// The error result returned by the function controls how WalkDir +// continues. If the function returns the special value SkipDir, WalkDir +// skips the current directory (path if d.IsDir() is true, otherwise +// path's parent directory). Otherwise, if the function returns a non-nil +// error, WalkDir stops entirely and returns that error. +// +// The err argument reports an error related to path, signaling that +// WalkDir will not walk into that directory. The function can decide how +// to handle that error; as described earlier, returning the error will +// cause WalkDir to stop walking the entire tree. +// +// WalkDir calls the function with a non-nil err argument in two cases. +// +// First, if the initial os.Lstat on the root directory fails, WalkDir +// calls the function with path set to root, d set to nil, and err set to +// the error from os.Lstat. +// +// Second, if a directory's ReadDir method fails, WalkDir calls the +// function with path set to the directory's path, d set to an +// fs.DirEntry describing the directory, and err set to the error from +// ReadDir. In this second case, the function is called twice with the +// path of the directory: the first call is before the directory read is +// attempted and has err set to nil, giving the function a chance to +// return SkipDir and avoid the ReadDir entirely. The second call is +// after a failed ReadDir and reports the error from ReadDir. +// (If ReadDir succeeds, there is no second call.) +// +// The differences between WalkDirFunc compared to WalkFunc are: +// +// - The second argument has type fs.DirEntry instead of fs.FileInfo. +// - The function is called before reading a directory, to allow SkipDir +// to bypass the directory read entirely. +// - If a directory read fails, the function is called a second time +// for that directory to report the error. +// +type WalkDirFunc func(path string, d fs.DirEntry, err error) error + +// WalkFunc is the type of the function called by Walk to visit each each +// file or directory. +// +// The path argument contains the argument to Walk as a prefix. +// That is, if Walk is called with root argument "dir" and finds a file +// named "a" in that directory, the walk function will be called with +// argument "dir/a". +// +// The directory and file are joined with Join, which may clean the +// directory name: if Walk is called with the root argument "x/../dir" +// and finds a file named "a" in that directory, the walk function will +// be called with argument "dir/a", not "x/../dir/a". +// +// The info argument is the fs.FileInfo for the named path. +// +// The error result returned by the function controls how Walk continues. +// If the function returns the special value SkipDir, Walk skips the +// current directory (path if info.IsDir() is true, otherwise path's +// parent directory). Otherwise, if the function returns a non-nil error, +// Walk stops entirely and returns that error. +// +// The err argument reports an error related to path, signaling that Walk +// will not walk into that directory. The function can decide how to +// handle that error; as described earlier, returning the error will +// cause Walk to stop walking the entire tree. +// +// Walk calls the function with a non-nil err argument in two cases. +// +// First, if an os.Lstat on the root directory or any directory or file +// in the tree fails, Walk calls the function with path set to that +// directory or file's path, info set to nil, and err set to the error +// from os.Lstat. +// +// Second, if a directory's Readdirnames method fails, Walk calls the +// function with path set to the directory's path, info, set to an +// fs.FileInfo describing the directory, and err set to the error from +// Readdirnames. type WalkFunc func(path string, info fs.FileInfo, err error) error var lstat = os.Lstat // for testing +// walkDir recursively descends path, calling walkDirFn. +func walkDir(path string, d fs.DirEntry, walkDirFn WalkDirFunc) error { + if err := walkDirFn(path, d, nil); err != nil || !d.IsDir() { + if err == SkipDir && d.IsDir() { + // Successfully skipped directory. + err = nil + } + return err + } + + dirs, err := readDir(path) + if err != nil { + // Second call, to report ReadDir error. + err = walkDirFn(path, d, err) + if err != nil { + return err + } + } + + for _, d1 := range dirs { + path1 := Join(path, d1.Name()) + if err := walkDir(path1, d1, walkDirFn); err != nil { + if err == SkipDir { + break + } + return err + } + } + return nil +} + // walk recursively descends path, calling walkFn. func walk(path string, info fs.FileInfo, walkFn WalkFunc) error { if !info.IsDir() { @@ -393,18 +498,62 @@ func walk(path string, info fs.FileInfo, walkFn WalkFunc) error { return nil } -// Walk walks the file tree rooted at root, calling walkFn for each file or -// directory in the tree, including root. All errors that arise visiting files -// and directories are filtered by walkFn. The files are walked in lexical -// order, which makes the output deterministic but means that for very -// large directories Walk can be inefficient. +// WalkDir walks the file tree rooted at root, calling fn for each file or +// directory in the tree, including root. +// +// All errors that arise visiting files and directories are filtered by fn: +// see the WalkDirFunc documentation for details. +// +// The files are walked in lexical order, which makes the output deterministic +// but requires WalkDir to read an entire directory into memory before proceeding +// to walk that directory. +// +// WalkDir does not follow symbolic links. +func WalkDir(root string, fn WalkDirFunc) error { + info, err := os.Lstat(root) + if err != nil { + err = fn(root, nil, err) + } else { + err = walkDir(root, &dirEntryFromInfo{info}, fn) + } + if err == SkipDir { + return nil + } + return err +} + +type dirEntryFromInfo struct { + fs.FileInfo +} + +func (e *dirEntryFromInfo) Type() fs.FileMode { + return e.Mode().Type() +} + +func (e *dirEntryFromInfo) Info() (fs.FileInfo, error) { + return e.FileInfo, nil +} + +// Walk walks the file tree rooted at root, calling fn for each file or +// directory in the tree, including root. +// +// All errors that arise visiting files and directories are filtered by fn: +// see the WalkFunc documentation for details. +// +// The files are walked in lexical order, which makes the output deterministic +// but requires Walk to read an entire directory into memory before proceeding +// to walk that directory. +// // Walk does not follow symbolic links. -func Walk(root string, walkFn WalkFunc) error { +// +// Walk is less efficient than WalkDir, introduced in Go 1.16, +// which avoids calling os.Lstat on every visited file or directory. +func Walk(root string, fn WalkFunc) error { info, err := os.Lstat(root) if err != nil { - err = walkFn(root, nil, err) + err = fn(root, nil, err) } else { - err = walk(root, info, walkFn) + err = walk(root, info, fn) } if err == SkipDir { return nil @@ -412,8 +561,24 @@ func Walk(root string, walkFn WalkFunc) error { return err } -// readDirNames reads the directory named by dirname and returns +// readDir reads the directory named by dirname and returns // a sorted list of directory entries. +func readDir(dirname string) ([]fs.DirEntry, error) { + f, err := os.Open(dirname) + if err != nil { + return nil, err + } + dirs, err := f.ReadDir(-1) + f.Close() + if err != nil { + return nil, err + } + sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() }) + return dirs, nil +} + +// readDirNames reads the directory named by dirname and returns +// a sorted list of directory entry names. func readDirNames(dirname string) ([]string, error) { f, err := os.Open(dirname) if err != nil { diff --git a/src/path/filepath/path_test.go b/src/path/filepath/path_test.go index 7dc8b60c28..af6b69de09 100644 --- a/src/path/filepath/path_test.go +++ b/src/path/filepath/path_test.go @@ -394,8 +394,8 @@ func checkMarks(t *testing.T, report bool) { // Assumes that each node name is unique. Good enough for a test. // If clear is true, any incoming error is cleared before return. The errors // are always accumulated, though. -func mark(info fs.FileInfo, err error, errors *[]error, clear bool) error { - name := info.Name() +func mark(d fs.DirEntry, err error, errors *[]error, clear bool) error { + name := d.Name() walkTree(tree, tree.name, func(path string, n *Node) { if n.name == name { n.mark++ @@ -432,6 +432,19 @@ func chtmpdir(t *testing.T) (restore func()) { } func TestWalk(t *testing.T) { + walk := func(root string, fn filepath.WalkDirFunc) error { + return filepath.Walk(root, func(path string, info fs.FileInfo, err error) error { + return fn(path, &filepath.DirEntryFromInfo{info}, err) + }) + } + testWalk(t, walk, 1) +} + +func TestWalkDir(t *testing.T) { + testWalk(t, filepath.WalkDir, 2) +} + +func testWalk(t *testing.T, walk func(string, filepath.WalkDirFunc) error, errVisit int) { if runtime.GOOS == "ios" { restore := chtmpdir(t) defer restore() @@ -455,11 +468,11 @@ func TestWalk(t *testing.T) { makeTree(t) errors := make([]error, 0, 10) clear := true - markFn := func(path string, info fs.FileInfo, err error) error { - return mark(info, err, &errors, clear) + markFn := func(path string, d fs.DirEntry, err error) error { + return mark(d, err, &errors, clear) } // Expect no errors. - err = filepath.Walk(tree.name, markFn) + err = walk(tree.name, markFn) if err != nil { t.Fatalf("no error expected, found: %s", err) } @@ -469,10 +482,17 @@ func TestWalk(t *testing.T) { checkMarks(t, true) errors = errors[0:0] - // Test permission errors. Only possible if we're not root - // and only on some file systems (AFS, FAT). To avoid errors during - // all.bash on those file systems, skip during go test -short. - if os.Getuid() > 0 && !testing.Short() { + t.Run("PermErr", func(t *testing.T) { + // Test permission errors. Only possible if we're not root + // and only on some file systems (AFS, FAT). To avoid errors during + // all.bash on those file systems, skip during go test -short. + if os.Getuid() == 0 { + t.Skip("skipping as root") + } + if testing.Short() { + t.Skip("skipping in short mode") + } + // introduce 2 errors: chmod top-level directories to 0 os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0) os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0) @@ -482,9 +502,9 @@ func TestWalk(t *testing.T) { markTree(tree.entries[1]) markTree(tree.entries[3]) // correct double-marking of directory itself - tree.entries[1].mark-- - tree.entries[3].mark-- - err := filepath.Walk(tree.name, markFn) + tree.entries[1].mark -= errVisit + tree.entries[3].mark -= errVisit + err := walk(tree.name, markFn) if err != nil { t.Fatalf("expected no error return from Walk, got %s", err) } @@ -500,10 +520,10 @@ func TestWalk(t *testing.T) { markTree(tree.entries[1]) markTree(tree.entries[3]) // correct double-marking of directory itself - tree.entries[1].mark-- - tree.entries[3].mark-- + tree.entries[1].mark -= errVisit + tree.entries[3].mark -= errVisit clear = false // error will stop processing - err = filepath.Walk(tree.name, markFn) + err = walk(tree.name, markFn) if err == nil { t.Fatalf("expected error return from Walk") } @@ -517,7 +537,7 @@ func TestWalk(t *testing.T) { // restore permissions os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0770) os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0770) - } + }) } func touch(t *testing.T, name string) { @@ -544,7 +564,7 @@ func TestWalkSkipDirOnFile(t *testing.T) { touch(t, filepath.Join(td, "dir/foo2")) sawFoo2 := false - walker := func(path string, info fs.FileInfo, err error) error { + walker := func(path string) error { if strings.HasSuffix(path, "foo2") { sawFoo2 = true } @@ -553,22 +573,31 @@ func TestWalkSkipDirOnFile(t *testing.T) { } return nil } + walkFn := func(path string, _ fs.FileInfo, _ error) error { return walker(path) } + walkDirFn := func(path string, _ fs.DirEntry, _ error) error { return walker(path) } - err = filepath.Walk(td, walker) - if err != nil { - t.Fatal(err) - } - if sawFoo2 { - t.Errorf("SkipDir on file foo1 did not block processing of foo2") + check := func(t *testing.T, walk func(root string) error, root string) { + t.Helper() + sawFoo2 = false + err = walk(root) + if err != nil { + t.Fatal(err) + } + if sawFoo2 { + t.Errorf("SkipDir on file foo1 did not block processing of foo2") + } } - err = filepath.Walk(filepath.Join(td, "dir"), walker) - if err != nil { - t.Fatal(err) - } - if sawFoo2 { - t.Errorf("SkipDir on file foo1 did not block processing of foo2") - } + t.Run("Walk", func(t *testing.T) { + Walk := func(root string) error { return filepath.Walk(td, walkFn) } + check(t, Walk, td) + check(t, Walk, filepath.Join(td, "dir")) + }) + t.Run("WalkDir", func(t *testing.T) { + WalkDir := func(root string) error { return filepath.WalkDir(td, walkDirFn) } + check(t, WalkDir, td) + check(t, WalkDir, filepath.Join(td, "dir")) + }) } func TestWalkFileError(t *testing.T) { -- cgit v1.3 From 74ec40fc8acffb81f17ccbaa498b15f694c25e4d Mon Sep 17 00:00:00 2001 From: Dmitri Shuralyov Date: Thu, 5 Nov 2020 01:05:04 +0000 Subject: path/filepath: revert "add WalkDir" This reverts CL 266240. Reason for revert: tests aren't passing on windows-amd64-longtest. Change-Id: If323c6254a42aff0418e2c0a9531f3d4c829a242 Reviewed-on: https://go-review.googlesource.com/c/go/+/267798 Trust: Dmitri Shuralyov Run-TryBot: Dmitri Shuralyov TryBot-Result: Go Bot Reviewed-by: Bryan C. Mills --- src/path/filepath/export_test.go | 2 - src/path/filepath/path.go | 213 +++++---------------------------------- src/path/filepath/path_test.go | 89 ++++++---------- 3 files changed, 54 insertions(+), 250 deletions(-) (limited to 'src/path/filepath') diff --git a/src/path/filepath/export_test.go b/src/path/filepath/export_test.go index e7ad7dd01a..0cf9e3bca1 100644 --- a/src/path/filepath/export_test.go +++ b/src/path/filepath/export_test.go @@ -5,5 +5,3 @@ package filepath var LstatP = &lstat - -type DirEntryFromInfo = dirEntryFromInfo diff --git a/src/path/filepath/path.go b/src/path/filepath/path.go index 3f7e5c713d..dffd27db14 100644 --- a/src/path/filepath/path.go +++ b/src/path/filepath/path.go @@ -336,130 +336,25 @@ func Rel(basepath, targpath string) (string, error) { // as an error by any function. var SkipDir = errors.New("skip this directory") -// WalkDirFunc is the type of the function called by WalkDir to visit -// each each file or directory. -// -// The path argument contains the argument to Walk as a prefix. -// That is, if Walk is called with root argument "dir" and finds a file -// named "a" in that directory, the walk function will be called with -// argument "dir/a". -// -// The directory and file are joined with Join, which may clean the -// directory name: if Walk is called with the root argument "x/../dir" -// and finds a file named "a" in that directory, the walk function will -// be called with argument "dir/a", not "x/../dir/a". -// -// The d argument is the fs.DirEntry for the named path. -// -// The error result returned by the function controls how WalkDir -// continues. If the function returns the special value SkipDir, WalkDir -// skips the current directory (path if d.IsDir() is true, otherwise -// path's parent directory). Otherwise, if the function returns a non-nil -// error, WalkDir stops entirely and returns that error. -// -// The err argument reports an error related to path, signaling that -// WalkDir will not walk into that directory. The function can decide how -// to handle that error; as described earlier, returning the error will -// cause WalkDir to stop walking the entire tree. -// -// WalkDir calls the function with a non-nil err argument in two cases. -// -// First, if the initial os.Lstat on the root directory fails, WalkDir -// calls the function with path set to root, d set to nil, and err set to -// the error from os.Lstat. -// -// Second, if a directory's ReadDir method fails, WalkDir calls the -// function with path set to the directory's path, d set to an -// fs.DirEntry describing the directory, and err set to the error from -// ReadDir. In this second case, the function is called twice with the -// path of the directory: the first call is before the directory read is -// attempted and has err set to nil, giving the function a chance to -// return SkipDir and avoid the ReadDir entirely. The second call is -// after a failed ReadDir and reports the error from ReadDir. -// (If ReadDir succeeds, there is no second call.) -// -// The differences between WalkDirFunc compared to WalkFunc are: -// -// - The second argument has type fs.DirEntry instead of fs.FileInfo. -// - The function is called before reading a directory, to allow SkipDir -// to bypass the directory read entirely. -// - If a directory read fails, the function is called a second time -// for that directory to report the error. -// -type WalkDirFunc func(path string, d fs.DirEntry, err error) error - -// WalkFunc is the type of the function called by Walk to visit each each -// file or directory. -// -// The path argument contains the argument to Walk as a prefix. -// That is, if Walk is called with root argument "dir" and finds a file -// named "a" in that directory, the walk function will be called with -// argument "dir/a". -// -// The directory and file are joined with Join, which may clean the -// directory name: if Walk is called with the root argument "x/../dir" -// and finds a file named "a" in that directory, the walk function will -// be called with argument "dir/a", not "x/../dir/a". -// -// The info argument is the fs.FileInfo for the named path. -// -// The error result returned by the function controls how Walk continues. -// If the function returns the special value SkipDir, Walk skips the -// current directory (path if info.IsDir() is true, otherwise path's -// parent directory). Otherwise, if the function returns a non-nil error, -// Walk stops entirely and returns that error. -// -// The err argument reports an error related to path, signaling that Walk -// will not walk into that directory. The function can decide how to -// handle that error; as described earlier, returning the error will -// cause Walk to stop walking the entire tree. -// -// Walk calls the function with a non-nil err argument in two cases. -// -// First, if an os.Lstat on the root directory or any directory or file -// in the tree fails, Walk calls the function with path set to that -// directory or file's path, info set to nil, and err set to the error -// from os.Lstat. -// -// Second, if a directory's Readdirnames method fails, Walk calls the -// function with path set to the directory's path, info, set to an -// fs.FileInfo describing the directory, and err set to the error from -// Readdirnames. +// WalkFunc is the type of the function called for each file or directory +// visited by Walk. The path argument contains the argument to Walk as a +// prefix; that is, if Walk is called with "dir", which is a directory +// containing the file "a", the walk function will be called with argument +// "dir/a". The info argument is the fs.FileInfo for the named path. +// +// If there was a problem walking to the file or directory named by path, the +// incoming error will describe the problem and the function can decide how +// to handle that error (and Walk will not descend into that directory). In the +// case of an error, the info argument will be nil. If an error is returned, +// processing stops. The sole exception is when the function returns the special +// value SkipDir. If the function returns SkipDir when invoked on a directory, +// Walk skips the directory's contents entirely. If the function returns SkipDir +// when invoked on a non-directory file, Walk skips the remaining files in the +// containing directory. type WalkFunc func(path string, info fs.FileInfo, err error) error var lstat = os.Lstat // for testing -// walkDir recursively descends path, calling walkDirFn. -func walkDir(path string, d fs.DirEntry, walkDirFn WalkDirFunc) error { - if err := walkDirFn(path, d, nil); err != nil || !d.IsDir() { - if err == SkipDir && d.IsDir() { - // Successfully skipped directory. - err = nil - } - return err - } - - dirs, err := readDir(path) - if err != nil { - // Second call, to report ReadDir error. - err = walkDirFn(path, d, err) - if err != nil { - return err - } - } - - for _, d1 := range dirs { - path1 := Join(path, d1.Name()) - if err := walkDir(path1, d1, walkDirFn); err != nil { - if err == SkipDir { - break - } - return err - } - } - return nil -} - // walk recursively descends path, calling walkFn. func walk(path string, info fs.FileInfo, walkFn WalkFunc) error { if !info.IsDir() { @@ -498,62 +393,18 @@ func walk(path string, info fs.FileInfo, walkFn WalkFunc) error { return nil } -// WalkDir walks the file tree rooted at root, calling fn for each file or -// directory in the tree, including root. -// -// All errors that arise visiting files and directories are filtered by fn: -// see the WalkDirFunc documentation for details. -// -// The files are walked in lexical order, which makes the output deterministic -// but requires WalkDir to read an entire directory into memory before proceeding -// to walk that directory. -// -// WalkDir does not follow symbolic links. -func WalkDir(root string, fn WalkDirFunc) error { - info, err := os.Lstat(root) - if err != nil { - err = fn(root, nil, err) - } else { - err = walkDir(root, &dirEntryFromInfo{info}, fn) - } - if err == SkipDir { - return nil - } - return err -} - -type dirEntryFromInfo struct { - fs.FileInfo -} - -func (e *dirEntryFromInfo) Type() fs.FileMode { - return e.Mode().Type() -} - -func (e *dirEntryFromInfo) Info() (fs.FileInfo, error) { - return e.FileInfo, nil -} - -// Walk walks the file tree rooted at root, calling fn for each file or -// directory in the tree, including root. -// -// All errors that arise visiting files and directories are filtered by fn: -// see the WalkFunc documentation for details. -// -// The files are walked in lexical order, which makes the output deterministic -// but requires Walk to read an entire directory into memory before proceeding -// to walk that directory. -// +// Walk walks the file tree rooted at root, calling walkFn for each file or +// directory in the tree, including root. All errors that arise visiting files +// and directories are filtered by walkFn. The files are walked in lexical +// order, which makes the output deterministic but means that for very +// large directories Walk can be inefficient. // Walk does not follow symbolic links. -// -// Walk is less efficient than WalkDir, introduced in Go 1.16, -// which avoids calling os.Lstat on every visited file or directory. -func Walk(root string, fn WalkFunc) error { +func Walk(root string, walkFn WalkFunc) error { info, err := os.Lstat(root) if err != nil { - err = fn(root, nil, err) + err = walkFn(root, nil, err) } else { - err = walk(root, info, fn) + err = walk(root, info, walkFn) } if err == SkipDir { return nil @@ -561,24 +412,8 @@ func Walk(root string, fn WalkFunc) error { return err } -// readDir reads the directory named by dirname and returns -// a sorted list of directory entries. -func readDir(dirname string) ([]fs.DirEntry, error) { - f, err := os.Open(dirname) - if err != nil { - return nil, err - } - dirs, err := f.ReadDir(-1) - f.Close() - if err != nil { - return nil, err - } - sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() }) - return dirs, nil -} - // readDirNames reads the directory named by dirname and returns -// a sorted list of directory entry names. +// a sorted list of directory entries. func readDirNames(dirname string) ([]string, error) { f, err := os.Open(dirname) if err != nil { diff --git a/src/path/filepath/path_test.go b/src/path/filepath/path_test.go index af6b69de09..7dc8b60c28 100644 --- a/src/path/filepath/path_test.go +++ b/src/path/filepath/path_test.go @@ -394,8 +394,8 @@ func checkMarks(t *testing.T, report bool) { // Assumes that each node name is unique. Good enough for a test. // If clear is true, any incoming error is cleared before return. The errors // are always accumulated, though. -func mark(d fs.DirEntry, err error, errors *[]error, clear bool) error { - name := d.Name() +func mark(info fs.FileInfo, err error, errors *[]error, clear bool) error { + name := info.Name() walkTree(tree, tree.name, func(path string, n *Node) { if n.name == name { n.mark++ @@ -432,19 +432,6 @@ func chtmpdir(t *testing.T) (restore func()) { } func TestWalk(t *testing.T) { - walk := func(root string, fn filepath.WalkDirFunc) error { - return filepath.Walk(root, func(path string, info fs.FileInfo, err error) error { - return fn(path, &filepath.DirEntryFromInfo{info}, err) - }) - } - testWalk(t, walk, 1) -} - -func TestWalkDir(t *testing.T) { - testWalk(t, filepath.WalkDir, 2) -} - -func testWalk(t *testing.T, walk func(string, filepath.WalkDirFunc) error, errVisit int) { if runtime.GOOS == "ios" { restore := chtmpdir(t) defer restore() @@ -468,11 +455,11 @@ func testWalk(t *testing.T, walk func(string, filepath.WalkDirFunc) error, errVi makeTree(t) errors := make([]error, 0, 10) clear := true - markFn := func(path string, d fs.DirEntry, err error) error { - return mark(d, err, &errors, clear) + markFn := func(path string, info fs.FileInfo, err error) error { + return mark(info, err, &errors, clear) } // Expect no errors. - err = walk(tree.name, markFn) + err = filepath.Walk(tree.name, markFn) if err != nil { t.Fatalf("no error expected, found: %s", err) } @@ -482,17 +469,10 @@ func testWalk(t *testing.T, walk func(string, filepath.WalkDirFunc) error, errVi checkMarks(t, true) errors = errors[0:0] - t.Run("PermErr", func(t *testing.T) { - // Test permission errors. Only possible if we're not root - // and only on some file systems (AFS, FAT). To avoid errors during - // all.bash on those file systems, skip during go test -short. - if os.Getuid() == 0 { - t.Skip("skipping as root") - } - if testing.Short() { - t.Skip("skipping in short mode") - } - + // Test permission errors. Only possible if we're not root + // and only on some file systems (AFS, FAT). To avoid errors during + // all.bash on those file systems, skip during go test -short. + if os.Getuid() > 0 && !testing.Short() { // introduce 2 errors: chmod top-level directories to 0 os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0) os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0) @@ -502,9 +482,9 @@ func testWalk(t *testing.T, walk func(string, filepath.WalkDirFunc) error, errVi markTree(tree.entries[1]) markTree(tree.entries[3]) // correct double-marking of directory itself - tree.entries[1].mark -= errVisit - tree.entries[3].mark -= errVisit - err := walk(tree.name, markFn) + tree.entries[1].mark-- + tree.entries[3].mark-- + err := filepath.Walk(tree.name, markFn) if err != nil { t.Fatalf("expected no error return from Walk, got %s", err) } @@ -520,10 +500,10 @@ func testWalk(t *testing.T, walk func(string, filepath.WalkDirFunc) error, errVi markTree(tree.entries[1]) markTree(tree.entries[3]) // correct double-marking of directory itself - tree.entries[1].mark -= errVisit - tree.entries[3].mark -= errVisit + tree.entries[1].mark-- + tree.entries[3].mark-- clear = false // error will stop processing - err = walk(tree.name, markFn) + err = filepath.Walk(tree.name, markFn) if err == nil { t.Fatalf("expected error return from Walk") } @@ -537,7 +517,7 @@ func testWalk(t *testing.T, walk func(string, filepath.WalkDirFunc) error, errVi // restore permissions os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0770) os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0770) - }) + } } func touch(t *testing.T, name string) { @@ -564,7 +544,7 @@ func TestWalkSkipDirOnFile(t *testing.T) { touch(t, filepath.Join(td, "dir/foo2")) sawFoo2 := false - walker := func(path string) error { + walker := func(path string, info fs.FileInfo, err error) error { if strings.HasSuffix(path, "foo2") { sawFoo2 = true } @@ -573,31 +553,22 @@ func TestWalkSkipDirOnFile(t *testing.T) { } return nil } - walkFn := func(path string, _ fs.FileInfo, _ error) error { return walker(path) } - walkDirFn := func(path string, _ fs.DirEntry, _ error) error { return walker(path) } - check := func(t *testing.T, walk func(root string) error, root string) { - t.Helper() - sawFoo2 = false - err = walk(root) - if err != nil { - t.Fatal(err) - } - if sawFoo2 { - t.Errorf("SkipDir on file foo1 did not block processing of foo2") - } + err = filepath.Walk(td, walker) + if err != nil { + t.Fatal(err) + } + if sawFoo2 { + t.Errorf("SkipDir on file foo1 did not block processing of foo2") } - t.Run("Walk", func(t *testing.T) { - Walk := func(root string) error { return filepath.Walk(td, walkFn) } - check(t, Walk, td) - check(t, Walk, filepath.Join(td, "dir")) - }) - t.Run("WalkDir", func(t *testing.T) { - WalkDir := func(root string) error { return filepath.WalkDir(td, walkDirFn) } - check(t, WalkDir, td) - check(t, WalkDir, filepath.Join(td, "dir")) - }) + err = filepath.Walk(filepath.Join(td, "dir"), walker) + if err != nil { + t.Fatal(err) + } + if sawFoo2 { + t.Errorf("SkipDir on file foo1 did not block processing of foo2") + } } func TestWalkFileError(t *testing.T) { -- cgit v1.3 From d21af00dd22d478d0026797c91961168ba83aff9 Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Thu, 29 Oct 2020 12:20:53 -0400 Subject: path/filepath: add WalkDir WalkDir is like Walk but can use ReadDir to read directories, instead of Readdirnames + Lstat on every entry, which is usually a significant performance improvement. (The Lstat can still happen if the walk function calls d.Info.) Fixes #42027. [Replay of CL 266240 after it was reverted due to accidentally enabling on Windows a test that does not work on Windows. The original code only ran the test on os.Getuid() > 0. The rolled-back CL skipped the test on os.Getuid() == 0. But on Windows, os.Getuid(), it turns out, always returns -1. So what looked like a test for root was also excluding Windows. This CL revises the test to skip Windows explicitly.] Change-Id: I9b3661013d6449b7486532445d934ae91e5393ef Reviewed-on: https://go-review.googlesource.com/c/go/+/267887 Trust: Russ Cox Run-TryBot: Dmitri Shuralyov Reviewed-by: Dmitri Shuralyov TryBot-Result: Go Bot --- src/path/filepath/export_test.go | 2 + src/path/filepath/path.go | 213 ++++++++++++++++++++++++++++++++++----- src/path/filepath/path_test.go | 92 +++++++++++------ 3 files changed, 253 insertions(+), 54 deletions(-) (limited to 'src/path/filepath') diff --git a/src/path/filepath/export_test.go b/src/path/filepath/export_test.go index 0cf9e3bca1..e7ad7dd01a 100644 --- a/src/path/filepath/export_test.go +++ b/src/path/filepath/export_test.go @@ -5,3 +5,5 @@ package filepath var LstatP = &lstat + +type DirEntryFromInfo = dirEntryFromInfo diff --git a/src/path/filepath/path.go b/src/path/filepath/path.go index dffd27db14..3f7e5c713d 100644 --- a/src/path/filepath/path.go +++ b/src/path/filepath/path.go @@ -336,25 +336,130 @@ func Rel(basepath, targpath string) (string, error) { // as an error by any function. var SkipDir = errors.New("skip this directory") -// WalkFunc is the type of the function called for each file or directory -// visited by Walk. The path argument contains the argument to Walk as a -// prefix; that is, if Walk is called with "dir", which is a directory -// containing the file "a", the walk function will be called with argument -// "dir/a". The info argument is the fs.FileInfo for the named path. -// -// If there was a problem walking to the file or directory named by path, the -// incoming error will describe the problem and the function can decide how -// to handle that error (and Walk will not descend into that directory). In the -// case of an error, the info argument will be nil. If an error is returned, -// processing stops. The sole exception is when the function returns the special -// value SkipDir. If the function returns SkipDir when invoked on a directory, -// Walk skips the directory's contents entirely. If the function returns SkipDir -// when invoked on a non-directory file, Walk skips the remaining files in the -// containing directory. +// WalkDirFunc is the type of the function called by WalkDir to visit +// each each file or directory. +// +// The path argument contains the argument to Walk as a prefix. +// That is, if Walk is called with root argument "dir" and finds a file +// named "a" in that directory, the walk function will be called with +// argument "dir/a". +// +// The directory and file are joined with Join, which may clean the +// directory name: if Walk is called with the root argument "x/../dir" +// and finds a file named "a" in that directory, the walk function will +// be called with argument "dir/a", not "x/../dir/a". +// +// The d argument is the fs.DirEntry for the named path. +// +// The error result returned by the function controls how WalkDir +// continues. If the function returns the special value SkipDir, WalkDir +// skips the current directory (path if d.IsDir() is true, otherwise +// path's parent directory). Otherwise, if the function returns a non-nil +// error, WalkDir stops entirely and returns that error. +// +// The err argument reports an error related to path, signaling that +// WalkDir will not walk into that directory. The function can decide how +// to handle that error; as described earlier, returning the error will +// cause WalkDir to stop walking the entire tree. +// +// WalkDir calls the function with a non-nil err argument in two cases. +// +// First, if the initial os.Lstat on the root directory fails, WalkDir +// calls the function with path set to root, d set to nil, and err set to +// the error from os.Lstat. +// +// Second, if a directory's ReadDir method fails, WalkDir calls the +// function with path set to the directory's path, d set to an +// fs.DirEntry describing the directory, and err set to the error from +// ReadDir. In this second case, the function is called twice with the +// path of the directory: the first call is before the directory read is +// attempted and has err set to nil, giving the function a chance to +// return SkipDir and avoid the ReadDir entirely. The second call is +// after a failed ReadDir and reports the error from ReadDir. +// (If ReadDir succeeds, there is no second call.) +// +// The differences between WalkDirFunc compared to WalkFunc are: +// +// - The second argument has type fs.DirEntry instead of fs.FileInfo. +// - The function is called before reading a directory, to allow SkipDir +// to bypass the directory read entirely. +// - If a directory read fails, the function is called a second time +// for that directory to report the error. +// +type WalkDirFunc func(path string, d fs.DirEntry, err error) error + +// WalkFunc is the type of the function called by Walk to visit each each +// file or directory. +// +// The path argument contains the argument to Walk as a prefix. +// That is, if Walk is called with root argument "dir" and finds a file +// named "a" in that directory, the walk function will be called with +// argument "dir/a". +// +// The directory and file are joined with Join, which may clean the +// directory name: if Walk is called with the root argument "x/../dir" +// and finds a file named "a" in that directory, the walk function will +// be called with argument "dir/a", not "x/../dir/a". +// +// The info argument is the fs.FileInfo for the named path. +// +// The error result returned by the function controls how Walk continues. +// If the function returns the special value SkipDir, Walk skips the +// current directory (path if info.IsDir() is true, otherwise path's +// parent directory). Otherwise, if the function returns a non-nil error, +// Walk stops entirely and returns that error. +// +// The err argument reports an error related to path, signaling that Walk +// will not walk into that directory. The function can decide how to +// handle that error; as described earlier, returning the error will +// cause Walk to stop walking the entire tree. +// +// Walk calls the function with a non-nil err argument in two cases. +// +// First, if an os.Lstat on the root directory or any directory or file +// in the tree fails, Walk calls the function with path set to that +// directory or file's path, info set to nil, and err set to the error +// from os.Lstat. +// +// Second, if a directory's Readdirnames method fails, Walk calls the +// function with path set to the directory's path, info, set to an +// fs.FileInfo describing the directory, and err set to the error from +// Readdirnames. type WalkFunc func(path string, info fs.FileInfo, err error) error var lstat = os.Lstat // for testing +// walkDir recursively descends path, calling walkDirFn. +func walkDir(path string, d fs.DirEntry, walkDirFn WalkDirFunc) error { + if err := walkDirFn(path, d, nil); err != nil || !d.IsDir() { + if err == SkipDir && d.IsDir() { + // Successfully skipped directory. + err = nil + } + return err + } + + dirs, err := readDir(path) + if err != nil { + // Second call, to report ReadDir error. + err = walkDirFn(path, d, err) + if err != nil { + return err + } + } + + for _, d1 := range dirs { + path1 := Join(path, d1.Name()) + if err := walkDir(path1, d1, walkDirFn); err != nil { + if err == SkipDir { + break + } + return err + } + } + return nil +} + // walk recursively descends path, calling walkFn. func walk(path string, info fs.FileInfo, walkFn WalkFunc) error { if !info.IsDir() { @@ -393,18 +498,62 @@ func walk(path string, info fs.FileInfo, walkFn WalkFunc) error { return nil } -// Walk walks the file tree rooted at root, calling walkFn for each file or -// directory in the tree, including root. All errors that arise visiting files -// and directories are filtered by walkFn. The files are walked in lexical -// order, which makes the output deterministic but means that for very -// large directories Walk can be inefficient. +// WalkDir walks the file tree rooted at root, calling fn for each file or +// directory in the tree, including root. +// +// All errors that arise visiting files and directories are filtered by fn: +// see the WalkDirFunc documentation for details. +// +// The files are walked in lexical order, which makes the output deterministic +// but requires WalkDir to read an entire directory into memory before proceeding +// to walk that directory. +// +// WalkDir does not follow symbolic links. +func WalkDir(root string, fn WalkDirFunc) error { + info, err := os.Lstat(root) + if err != nil { + err = fn(root, nil, err) + } else { + err = walkDir(root, &dirEntryFromInfo{info}, fn) + } + if err == SkipDir { + return nil + } + return err +} + +type dirEntryFromInfo struct { + fs.FileInfo +} + +func (e *dirEntryFromInfo) Type() fs.FileMode { + return e.Mode().Type() +} + +func (e *dirEntryFromInfo) Info() (fs.FileInfo, error) { + return e.FileInfo, nil +} + +// Walk walks the file tree rooted at root, calling fn for each file or +// directory in the tree, including root. +// +// All errors that arise visiting files and directories are filtered by fn: +// see the WalkFunc documentation for details. +// +// The files are walked in lexical order, which makes the output deterministic +// but requires Walk to read an entire directory into memory before proceeding +// to walk that directory. +// // Walk does not follow symbolic links. -func Walk(root string, walkFn WalkFunc) error { +// +// Walk is less efficient than WalkDir, introduced in Go 1.16, +// which avoids calling os.Lstat on every visited file or directory. +func Walk(root string, fn WalkFunc) error { info, err := os.Lstat(root) if err != nil { - err = walkFn(root, nil, err) + err = fn(root, nil, err) } else { - err = walk(root, info, walkFn) + err = walk(root, info, fn) } if err == SkipDir { return nil @@ -412,8 +561,24 @@ func Walk(root string, walkFn WalkFunc) error { return err } -// readDirNames reads the directory named by dirname and returns +// readDir reads the directory named by dirname and returns // a sorted list of directory entries. +func readDir(dirname string) ([]fs.DirEntry, error) { + f, err := os.Open(dirname) + if err != nil { + return nil, err + } + dirs, err := f.ReadDir(-1) + f.Close() + if err != nil { + return nil, err + } + sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() }) + return dirs, nil +} + +// readDirNames reads the directory named by dirname and returns +// a sorted list of directory entry names. func readDirNames(dirname string) ([]string, error) { f, err := os.Open(dirname) if err != nil { diff --git a/src/path/filepath/path_test.go b/src/path/filepath/path_test.go index 7dc8b60c28..ec6f8f2de9 100644 --- a/src/path/filepath/path_test.go +++ b/src/path/filepath/path_test.go @@ -394,8 +394,8 @@ func checkMarks(t *testing.T, report bool) { // Assumes that each node name is unique. Good enough for a test. // If clear is true, any incoming error is cleared before return. The errors // are always accumulated, though. -func mark(info fs.FileInfo, err error, errors *[]error, clear bool) error { - name := info.Name() +func mark(d fs.DirEntry, err error, errors *[]error, clear bool) error { + name := d.Name() walkTree(tree, tree.name, func(path string, n *Node) { if n.name == name { n.mark++ @@ -432,6 +432,19 @@ func chtmpdir(t *testing.T) (restore func()) { } func TestWalk(t *testing.T) { + walk := func(root string, fn filepath.WalkDirFunc) error { + return filepath.Walk(root, func(path string, info fs.FileInfo, err error) error { + return fn(path, &filepath.DirEntryFromInfo{info}, err) + }) + } + testWalk(t, walk, 1) +} + +func TestWalkDir(t *testing.T) { + testWalk(t, filepath.WalkDir, 2) +} + +func testWalk(t *testing.T, walk func(string, filepath.WalkDirFunc) error, errVisit int) { if runtime.GOOS == "ios" { restore := chtmpdir(t) defer restore() @@ -455,11 +468,11 @@ func TestWalk(t *testing.T) { makeTree(t) errors := make([]error, 0, 10) clear := true - markFn := func(path string, info fs.FileInfo, err error) error { - return mark(info, err, &errors, clear) + markFn := func(path string, d fs.DirEntry, err error) error { + return mark(d, err, &errors, clear) } // Expect no errors. - err = filepath.Walk(tree.name, markFn) + err = walk(tree.name, markFn) if err != nil { t.Fatalf("no error expected, found: %s", err) } @@ -469,10 +482,20 @@ func TestWalk(t *testing.T) { checkMarks(t, true) errors = errors[0:0] - // Test permission errors. Only possible if we're not root - // and only on some file systems (AFS, FAT). To avoid errors during - // all.bash on those file systems, skip during go test -short. - if os.Getuid() > 0 && !testing.Short() { + t.Run("PermErr", func(t *testing.T) { + // Test permission errors. Only possible if we're not root + // and only on some file systems (AFS, FAT). To avoid errors during + // all.bash on those file systems, skip during go test -short. + if runtime.GOOS == "windows" { + t.Skip("skipping on Windows") + } + if os.Getuid() == 0 { + t.Skip("skipping as root") + } + if testing.Short() { + t.Skip("skipping in short mode") + } + // introduce 2 errors: chmod top-level directories to 0 os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0) os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0) @@ -482,9 +505,9 @@ func TestWalk(t *testing.T) { markTree(tree.entries[1]) markTree(tree.entries[3]) // correct double-marking of directory itself - tree.entries[1].mark-- - tree.entries[3].mark-- - err := filepath.Walk(tree.name, markFn) + tree.entries[1].mark -= errVisit + tree.entries[3].mark -= errVisit + err := walk(tree.name, markFn) if err != nil { t.Fatalf("expected no error return from Walk, got %s", err) } @@ -500,10 +523,10 @@ func TestWalk(t *testing.T) { markTree(tree.entries[1]) markTree(tree.entries[3]) // correct double-marking of directory itself - tree.entries[1].mark-- - tree.entries[3].mark-- + tree.entries[1].mark -= errVisit + tree.entries[3].mark -= errVisit clear = false // error will stop processing - err = filepath.Walk(tree.name, markFn) + err = walk(tree.name, markFn) if err == nil { t.Fatalf("expected error return from Walk") } @@ -517,7 +540,7 @@ func TestWalk(t *testing.T) { // restore permissions os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0770) os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0770) - } + }) } func touch(t *testing.T, name string) { @@ -544,7 +567,7 @@ func TestWalkSkipDirOnFile(t *testing.T) { touch(t, filepath.Join(td, "dir/foo2")) sawFoo2 := false - walker := func(path string, info fs.FileInfo, err error) error { + walker := func(path string) error { if strings.HasSuffix(path, "foo2") { sawFoo2 = true } @@ -553,22 +576,31 @@ func TestWalkSkipDirOnFile(t *testing.T) { } return nil } + walkFn := func(path string, _ fs.FileInfo, _ error) error { return walker(path) } + walkDirFn := func(path string, _ fs.DirEntry, _ error) error { return walker(path) } - err = filepath.Walk(td, walker) - if err != nil { - t.Fatal(err) - } - if sawFoo2 { - t.Errorf("SkipDir on file foo1 did not block processing of foo2") + check := func(t *testing.T, walk func(root string) error, root string) { + t.Helper() + sawFoo2 = false + err = walk(root) + if err != nil { + t.Fatal(err) + } + if sawFoo2 { + t.Errorf("SkipDir on file foo1 did not block processing of foo2") + } } - err = filepath.Walk(filepath.Join(td, "dir"), walker) - if err != nil { - t.Fatal(err) - } - if sawFoo2 { - t.Errorf("SkipDir on file foo1 did not block processing of foo2") - } + t.Run("Walk", func(t *testing.T) { + Walk := func(root string) error { return filepath.Walk(td, walkFn) } + check(t, Walk, td) + check(t, Walk, filepath.Join(td, "dir")) + }) + t.Run("WalkDir", func(t *testing.T) { + WalkDir := func(root string) error { return filepath.WalkDir(td, walkDirFn) } + check(t, WalkDir, td) + check(t, WalkDir, filepath.Join(td, "dir")) + }) } func TestWalkFileError(t *testing.T) { -- cgit v1.3 From 362d25f2c82980860cb4eb5bfd0648116504788d Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Sun, 19 Jul 2020 01:31:05 -0400 Subject: io/fs: add WalkDir This commit is a copy of filepath.WalkDir adapted to use fs.FS instead of the native OS file system. It is the last implementation piece of the io/fs proposal. The original io/fs proposal was to adopt filepath.Walk, but we have since introduced the more efficient filepath.WalkDir (#42027), so this CL adopts that more efficient option instead. (The changes in path/filepath bring the two copies more in line with each other. The main change is unembedding the field in statDirEntry, so that the fs.DirEntry passed to the WalkDirFunc for the root of the tree does not have any extra methods.) For #41190. Change-Id: I9359dfcc110338c0ec64535f22cafb38d0b613a6 Reviewed-on: https://go-review.googlesource.com/c/go/+/243916 Trust: Russ Cox Run-TryBot: Russ Cox TryBot-Result: Go Bot Reviewed-by: Rob Pike --- src/io/fs/walk.go | 132 +++++++++++++++++++++++++++++++++ src/io/fs/walk_test.go | 155 +++++++++++++++++++++++++++++++++++++++ src/path/filepath/export_test.go | 2 - src/path/filepath/path.go | 77 +++---------------- src/path/filepath/path_test.go | 15 +++- 5 files changed, 310 insertions(+), 71 deletions(-) create mode 100644 src/io/fs/walk.go create mode 100644 src/io/fs/walk_test.go (limited to 'src/path/filepath') diff --git a/src/io/fs/walk.go b/src/io/fs/walk.go new file mode 100644 index 0000000000..e50c1bb15c --- /dev/null +++ b/src/io/fs/walk.go @@ -0,0 +1,132 @@ +// 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" +) + +// SkipDir is used as a return value from WalkFuncs to indicate that +// the directory named in the call is to be skipped. It is not returned +// as an error by any function. +var SkipDir = errors.New("skip this directory") + +// WalkDirFunc is the type of the function called by WalkDir to visit +// each each file or directory. +// +// The path argument contains the argument to Walk as a prefix. +// That is, if Walk is called with root argument "dir" and finds a file +// named "a" in that directory, the walk function will be called with +// argument "dir/a". +// +// The directory and file are joined with Join, which may clean the +// directory name: if Walk is called with the root argument "x/../dir" +// and finds a file named "a" in that directory, the walk function will +// be called with argument "dir/a", not "x/../dir/a". +// +// The d argument is the fs.DirEntry for the named path. +// +// The error result returned by the function controls how WalkDir +// continues. If the function returns the special value SkipDir, WalkDir +// skips the current directory (path if d.IsDir() is true, otherwise +// path's parent directory). Otherwise, if the function returns a non-nil +// error, WalkDir stops entirely and returns that error. +// +// The err argument reports an error related to path, signaling that +// WalkDir will not walk into that directory. The function can decide how +// to handle that error; as described earlier, returning the error will +// cause WalkDir to stop walking the entire tree. +// +// WalkDir calls the function with a non-nil err argument in two cases. +// +// First, if the initial os.Lstat on the root directory fails, WalkDir +// calls the function with path set to root, d set to nil, and err set to +// the error from os.Lstat. +// +// Second, if a directory's ReadDir method fails, WalkDir calls the +// function with path set to the directory's path, d set to an +// fs.DirEntry describing the directory, and err set to the error from +// ReadDir. In this second case, the function is called twice with the +// path of the directory: the first call is before the directory read is +// attempted and has err set to nil, giving the function a chance to +// return SkipDir and avoid the ReadDir entirely. The second call is +// after a failed ReadDir and reports the error from ReadDir. +// (If ReadDir succeeds, there is no second call.) +// +// The differences between WalkDirFunc compared to WalkFunc are: +// +// - The second argument has type fs.DirEntry instead of fs.FileInfo. +// - The function is called before reading a directory, to allow SkipDir +// to bypass the directory read entirely. +// - If a directory read fails, the function is called a second time +// for that directory to report the error. +// +type WalkDirFunc func(path string, entry DirEntry, err error) error + +// walkDir recursively descends path, calling walkDirFn. +func walkDir(fsys FS, name string, d DirEntry, walkDirFn WalkDirFunc) error { + if err := walkDirFn(name, d, nil); err != nil || !d.IsDir() { + if err == SkipDir && d.IsDir() { + // Successfully skipped directory. + err = nil + } + return err + } + + dirs, err := ReadDir(fsys, name) + if err != nil { + // Second call, to report ReadDir error. + err = walkDirFn(name, d, err) + if err != nil { + return err + } + } + + for _, d1 := range dirs { + name1 := path.Join(name, d1.Name()) + if err := walkDir(fsys, name1, d1, walkDirFn); err != nil { + if err == SkipDir { + break + } + return err + } + } + return nil +} + +// WalkDir walks the file tree rooted at root, calling fn for each file or +// directory in the tree, including root. +// +// All errors that arise visiting files and directories are filtered by fn: +// see the fs.WalkDirFunc documentation for details. +// +// The files are walked in lexical order, which makes the output deterministic +// but requires WalkDir to read an entire directory into memory before proceeding +// to walk that directory. +// +// WalkDir does not follow symbolic links found in directories, +// but if root itself is a symbolic link, its target will be walked. +func WalkDir(fsys FS, root string, fn WalkDirFunc) error { + info, err := Stat(fsys, root) + if err != nil { + err = fn(root, nil, err) + } else { + err = walkDir(fsys, root, &statDirEntry{info}, fn) + } + if err == SkipDir { + return nil + } + return err +} + +type statDirEntry struct { + info FileInfo +} + +func (d *statDirEntry) Name() string { return d.info.Name() } +func (d *statDirEntry) IsDir() bool { return d.info.IsDir() } +func (d *statDirEntry) Type() FileMode { return d.info.Mode().Type() } +func (d *statDirEntry) Info() (FileInfo, error) { return d.info, nil } diff --git a/src/io/fs/walk_test.go b/src/io/fs/walk_test.go new file mode 100644 index 0000000000..395471e2e8 --- /dev/null +++ b/src/io/fs/walk_test.go @@ -0,0 +1,155 @@ +// 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" + "io/ioutil" + "os" + pathpkg "path" + "runtime" + "testing" + "testing/fstest" +) + +type Node struct { + name string + entries []*Node // nil if the entry is a file + mark int +} + +var tree = &Node{ + "testdata", + []*Node{ + {"a", nil, 0}, + {"b", []*Node{}, 0}, + {"c", nil, 0}, + { + "d", + []*Node{ + {"x", nil, 0}, + {"y", []*Node{}, 0}, + { + "z", + []*Node{ + {"u", nil, 0}, + {"v", nil, 0}, + }, + 0, + }, + }, + 0, + }, + }, + 0, +} + +func walkTree(n *Node, path string, f func(path string, n *Node)) { + f(path, n) + for _, e := range n.entries { + walkTree(e, pathpkg.Join(path, e.name), f) + } +} + +func makeTree(t *testing.T) FS { + fsys := fstest.MapFS{} + walkTree(tree, tree.name, func(path string, n *Node) { + if n.entries == nil { + fsys[path] = &fstest.MapFile{} + } else { + fsys[path] = &fstest.MapFile{Mode: ModeDir} + } + }) + return fsys +} + +func markTree(n *Node) { walkTree(n, "", func(path string, n *Node) { n.mark++ }) } + +func checkMarks(t *testing.T, report bool) { + walkTree(tree, tree.name, func(path string, n *Node) { + if n.mark != 1 && report { + t.Errorf("node %s mark = %d; expected 1", path, n.mark) + } + n.mark = 0 + }) +} + +// Assumes that each node name is unique. Good enough for a test. +// If clear is true, any incoming error is cleared before return. The errors +// are always accumulated, though. +func mark(entry DirEntry, err error, errors *[]error, clear bool) error { + name := entry.Name() + walkTree(tree, tree.name, func(path string, n *Node) { + if n.name == name { + n.mark++ + } + }) + if err != nil { + *errors = append(*errors, err) + if clear { + return nil + } + return err + } + return nil +} + +func chtmpdir(t *testing.T) (restore func()) { + oldwd, err := os.Getwd() + if err != nil { + t.Fatalf("chtmpdir: %v", err) + } + d, err := ioutil.TempDir("", "test") + if err != nil { + t.Fatalf("chtmpdir: %v", err) + } + if err := os.Chdir(d); err != nil { + t.Fatalf("chtmpdir: %v", err) + } + return func() { + if err := os.Chdir(oldwd); err != nil { + t.Fatalf("chtmpdir: %v", err) + } + os.RemoveAll(d) + } +} + +func TestWalkDir(t *testing.T) { + if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" { + restore := chtmpdir(t) + defer restore() + } + + tmpDir, err := ioutil.TempDir("", "TestWalk") + if err != nil { + t.Fatal("creating temp dir:", err) + } + defer os.RemoveAll(tmpDir) + + origDir, err := os.Getwd() + if err != nil { + t.Fatal("finding working dir:", err) + } + if err = os.Chdir(tmpDir); err != nil { + t.Fatal("entering temp dir:", err) + } + defer os.Chdir(origDir) + + fsys := makeTree(t) + errors := make([]error, 0, 10) + clear := true + markFn := func(path string, entry DirEntry, err error) error { + return mark(entry, err, &errors, clear) + } + // Expect no errors. + err = WalkDir(fsys, ".", markFn) + if err != nil { + t.Fatalf("no error expected, found: %s", err) + } + if len(errors) != 0 { + t.Fatalf("unexpected errors: %s", errors) + } + checkMarks(t, true) +} diff --git a/src/path/filepath/export_test.go b/src/path/filepath/export_test.go index e7ad7dd01a..0cf9e3bca1 100644 --- a/src/path/filepath/export_test.go +++ b/src/path/filepath/export_test.go @@ -5,5 +5,3 @@ package filepath var LstatP = &lstat - -type DirEntryFromInfo = dirEntryFromInfo diff --git a/src/path/filepath/path.go b/src/path/filepath/path.go index 3f7e5c713d..2e7b439355 100644 --- a/src/path/filepath/path.go +++ b/src/path/filepath/path.go @@ -334,59 +334,7 @@ func Rel(basepath, targpath string) (string, error) { // SkipDir is used as a return value from WalkFuncs to indicate that // the directory named in the call is to be skipped. It is not returned // as an error by any function. -var SkipDir = errors.New("skip this directory") - -// WalkDirFunc is the type of the function called by WalkDir to visit -// each each file or directory. -// -// The path argument contains the argument to Walk as a prefix. -// That is, if Walk is called with root argument "dir" and finds a file -// named "a" in that directory, the walk function will be called with -// argument "dir/a". -// -// The directory and file are joined with Join, which may clean the -// directory name: if Walk is called with the root argument "x/../dir" -// and finds a file named "a" in that directory, the walk function will -// be called with argument "dir/a", not "x/../dir/a". -// -// The d argument is the fs.DirEntry for the named path. -// -// The error result returned by the function controls how WalkDir -// continues. If the function returns the special value SkipDir, WalkDir -// skips the current directory (path if d.IsDir() is true, otherwise -// path's parent directory). Otherwise, if the function returns a non-nil -// error, WalkDir stops entirely and returns that error. -// -// The err argument reports an error related to path, signaling that -// WalkDir will not walk into that directory. The function can decide how -// to handle that error; as described earlier, returning the error will -// cause WalkDir to stop walking the entire tree. -// -// WalkDir calls the function with a non-nil err argument in two cases. -// -// First, if the initial os.Lstat on the root directory fails, WalkDir -// calls the function with path set to root, d set to nil, and err set to -// the error from os.Lstat. -// -// Second, if a directory's ReadDir method fails, WalkDir calls the -// function with path set to the directory's path, d set to an -// fs.DirEntry describing the directory, and err set to the error from -// ReadDir. In this second case, the function is called twice with the -// path of the directory: the first call is before the directory read is -// attempted and has err set to nil, giving the function a chance to -// return SkipDir and avoid the ReadDir entirely. The second call is -// after a failed ReadDir and reports the error from ReadDir. -// (If ReadDir succeeds, there is no second call.) -// -// The differences between WalkDirFunc compared to WalkFunc are: -// -// - The second argument has type fs.DirEntry instead of fs.FileInfo. -// - The function is called before reading a directory, to allow SkipDir -// to bypass the directory read entirely. -// - If a directory read fails, the function is called a second time -// for that directory to report the error. -// -type WalkDirFunc func(path string, d fs.DirEntry, err error) error +var SkipDir error = fs.SkipDir // WalkFunc is the type of the function called by Walk to visit each each // file or directory. @@ -430,7 +378,7 @@ type WalkFunc func(path string, info fs.FileInfo, err error) error var lstat = os.Lstat // for testing // walkDir recursively descends path, calling walkDirFn. -func walkDir(path string, d fs.DirEntry, walkDirFn WalkDirFunc) error { +func walkDir(path string, d fs.DirEntry, walkDirFn fs.WalkDirFunc) error { if err := walkDirFn(path, d, nil); err != nil || !d.IsDir() { if err == SkipDir && d.IsDir() { // Successfully skipped directory. @@ -502,19 +450,19 @@ func walk(path string, info fs.FileInfo, walkFn WalkFunc) error { // directory in the tree, including root. // // All errors that arise visiting files and directories are filtered by fn: -// see the WalkDirFunc documentation for details. +// see the fs.WalkDirFunc documentation for details. // // The files are walked in lexical order, which makes the output deterministic // but requires WalkDir to read an entire directory into memory before proceeding // to walk that directory. // // WalkDir does not follow symbolic links. -func WalkDir(root string, fn WalkDirFunc) error { +func WalkDir(root string, fn fs.WalkDirFunc) error { info, err := os.Lstat(root) if err != nil { err = fn(root, nil, err) } else { - err = walkDir(root, &dirEntryFromInfo{info}, fn) + err = walkDir(root, &statDirEntry{info}, fn) } if err == SkipDir { return nil @@ -522,17 +470,14 @@ func WalkDir(root string, fn WalkDirFunc) error { return err } -type dirEntryFromInfo struct { - fs.FileInfo +type statDirEntry struct { + info fs.FileInfo } -func (e *dirEntryFromInfo) Type() fs.FileMode { - return e.Mode().Type() -} - -func (e *dirEntryFromInfo) Info() (fs.FileInfo, error) { - return e.FileInfo, nil -} +func (d *statDirEntry) Name() string { return d.info.Name() } +func (d *statDirEntry) IsDir() bool { return d.info.IsDir() } +func (d *statDirEntry) Type() fs.FileMode { return d.info.Mode().Type() } +func (d *statDirEntry) Info() (fs.FileInfo, error) { return d.info, nil } // Walk walks the file tree rooted at root, calling fn for each file or // directory in the tree, including root. diff --git a/src/path/filepath/path_test.go b/src/path/filepath/path_test.go index ec6f8f2de9..d760530e26 100644 --- a/src/path/filepath/path_test.go +++ b/src/path/filepath/path_test.go @@ -432,19 +432,28 @@ func chtmpdir(t *testing.T) (restore func()) { } func TestWalk(t *testing.T) { - walk := func(root string, fn filepath.WalkDirFunc) error { + walk := func(root string, fn fs.WalkDirFunc) error { return filepath.Walk(root, func(path string, info fs.FileInfo, err error) error { - return fn(path, &filepath.DirEntryFromInfo{info}, err) + return fn(path, &statDirEntry{info}, err) }) } testWalk(t, walk, 1) } +type statDirEntry struct { + info fs.FileInfo +} + +func (d *statDirEntry) Name() string { return d.info.Name() } +func (d *statDirEntry) IsDir() bool { return d.info.IsDir() } +func (d *statDirEntry) Type() fs.FileMode { return d.info.Mode().Type() } +func (d *statDirEntry) Info() (fs.FileInfo, error) { return d.info, nil } + func TestWalkDir(t *testing.T) { testWalk(t, filepath.WalkDir, 2) } -func testWalk(t *testing.T, walk func(string, filepath.WalkDirFunc) error, errVisit int) { +func testWalk(t *testing.T, walk func(string, fs.WalkDirFunc) error, errVisit int) { if runtime.GOOS == "ios" { restore := chtmpdir(t) defer restore() -- 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/path/filepath') 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