From e847ec7474736661b8153dfadd6b84d3f84ec946 Mon Sep 17 00:00:00 2001 From: Natasha Sarkar Date: Tue, 8 Jun 2021 11:18:11 -0700 Subject: [PATCH] ReadDir method for filesys --- api/filesys/filesystem.go | 2 ++ api/filesys/fsnode.go | 23 +++++++++++++++++++++++ api/filesys/fsondisk.go | 13 +++++++++++++ 3 files changed, 38 insertions(+) diff --git a/api/filesys/filesystem.go b/api/filesys/filesystem.go index 2d8caf2b8..e5034092b 100644 --- a/api/filesys/filesystem.go +++ b/api/filesys/filesystem.go @@ -28,6 +28,8 @@ type FileSystem interface { Open(path string) (File, error) // IsDir returns true if the path is a directory. IsDir(path string) bool + // ReadDir returns a list of files and directories within a directory. + ReadDir(path string) ([]string, error) // CleanedAbs converts the given path into a // directory and a file name, where the directory // is represented as a ConfirmedDir and all that implies. diff --git a/api/filesys/fsnode.go b/api/filesys/fsnode.go index 97e0408e0..f3c1d3878 100644 --- a/api/filesys/fsnode.go +++ b/api/filesys/fsnode.go @@ -349,6 +349,29 @@ func (n *fsNode) IsDir(path string) bool { return result.isNodeADir() } +// ReadDir implements FileSystem. +func (n *fsNode) ReadDir(path string) ([]string, error) { + if !n.IsDir(path) { + return nil, fmt.Errorf("%s is not a directory", path) + } + + dir, err := n.Find(path) + if err != nil { + return nil, err + } + if dir == nil { + return nil, fmt.Errorf("could not find directory %s", path) + } + + keys := make([]string, len(dir.dir)) + i := 0 + for k := range dir.dir { + keys[i] = k + i++ + } + return keys, nil +} + // Size returns the size of the node. func (n *fsNode) Size() int64 { if n.isNodeADir() { diff --git a/api/filesys/fsondisk.go b/api/filesys/fsondisk.go index 6becbb6f1..86cd26d75 100644 --- a/api/filesys/fsondisk.go +++ b/api/filesys/fsondisk.go @@ -100,6 +100,19 @@ func (fsOnDisk) IsDir(name string) bool { return info.IsDir() } +// ReadDir delegates to os.ReadDir +func (fsOnDisk) ReadDir(name string) ([]string, error) { + dirEntries, err := os.ReadDir(name) + if err != nil { + return nil, err + } + result := make([]string, len(dirEntries)) + for i := range dirEntries { + result[i] = dirEntries[i].Name() + } + return result, nil +} + // ReadFile delegates to ioutil.ReadFile. func (fsOnDisk) ReadFile(name string) ([]byte, error) { return ioutil.ReadFile(name) }