]> Cypherpunks repositories - gostls13.git/commitdiff
os: add dirFs.ReadDir to implement fs.ReadDirFS for DirFS
authorTobias Klauser <tklauser@distanz.ch>
Wed, 24 May 2023 17:49:24 +0000 (19:49 +0200)
committerGopher Robot <gobot@golang.org>
Wed, 24 May 2023 22:39:06 +0000 (22:39 +0000)
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 <iant@google.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Run-TryBot: Tobias Klauser <tobias.klauser@gmail.com>

src/os/file.go
src/os/os_test.go

index fc5ba3e4847ec9df76d42c44f85e7fc93c3df024..7fd2f5d20271423b1da96bf68d6435827cf00c52 100644 (file)
@@ -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 {
index 2ffbc5b29e0d12f74b943dcdb6031f21d6943e1b..7f9ed1f8c8539b896eb7959ea0da7bc49ee4d60e 100644 (file)
@@ -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 {