//
// 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)
}
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 {
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 {