From 79a8997ac5592f11388d9f26ab3fff65ec876dbd Mon Sep 17 00:00:00 2001 From: Tobias Klauser Date: Wed, 24 May 2023 19:49:24 +0200 Subject: [PATCH] os: add dirFs.ReadDir to implement fs.ReadDirFS for DirFS Follow CL 416775 which added dirFs.ReadFile. Fixes #53761 Change-Id: Iec19a815ab7c37a3206be141518cc587a588de20 Reviewed-on: https://go-review.googlesource.com/c/go/+/498015 Run-TryBot: Ian Lance Taylor Reviewed-by: Matthew Dempsky Auto-Submit: Ian Lance Taylor TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Run-TryBot: Tobias Klauser --- src/os/file.go | 13 ++++++++++++- src/os/os_test.go | 14 +++++++++++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/os/file.go b/src/os/file.go index fc5ba3e484..7fd2f5d202 100644 --- a/src/os/file.go +++ b/src/os/file.go @@ -616,7 +616,8 @@ func (f *File) SyscallConn() (syscall.RawConn, error) { // // The directory dir must not be "". // -// The result implements fs.StatFS. +// The result implements [io/fs.StatFS], [io/fs.ReadFileFS] and +// [io/fs.ReadDirFS]. func DirFS(dir string) fs.FS { return dirFS(dir) } @@ -664,6 +665,16 @@ func (dir dirFS) ReadFile(name string) ([]byte, error) { return ReadFile(fullname) } +// ReadDir reads the named directory, returning all its directory entries sorted +// by filename. Through this method, dirFS implements [io/fs.ReadDirFS]. +func (dir dirFS) ReadDir(name string) ([]DirEntry, error) { + fullname, err := dir.join(name) + if err != nil { + return nil, &PathError{Op: "readdir", Path: name, Err: err} + } + return ReadDir(fullname) +} + func (dir dirFS) Stat(name string) (fs.FileInfo, error) { fullname, err := dir.join(name) if err != nil { diff --git a/src/os/os_test.go b/src/os/os_test.go index 2ffbc5b29e..7f9ed1f8c8 100644 --- a/src/os/os_test.go +++ b/src/os/os_test.go @@ -2995,15 +2995,23 @@ func TestDirFS(t *testing.T) { t.Fatal(err) } } - fs := DirFS("./testdata/dirfs") - if err := fstest.TestFS(fs, "a", "b", "dir/x"); err != nil { + fsys := DirFS("./testdata/dirfs") + if err := fstest.TestFS(fsys, "a", "b", "dir/x"); err != nil { t.Fatal(err) } + rdfs, ok := fsys.(fs.ReadDirFS) + if !ok { + t.Error("expected DirFS result to implement fs.ReadDirFS") + } + if _, err := rdfs.ReadDir("nonexistent"); err == nil { + t.Error("fs.ReadDir of nonexistent directory suceeded") + } + // Test that the error message does not contain a backslash, // and does not contain the DirFS argument. const nonesuch = "dir/nonesuch" - _, err := fs.Open(nonesuch) + _, err := fsys.Open(nonesuch) if err == nil { t.Error("fs.Open of nonexistent file succeeded") } else { -- 2.48.1