ReadDir method for filesys

This commit is contained in:
Natasha Sarkar
2021-06-08 11:18:11 -07:00
parent da1bd901b4
commit e847ec7474
3 changed files with 38 additions and 0 deletions

View File

@@ -28,6 +28,8 @@ type FileSystem interface {
Open(path string) (File, error) Open(path string) (File, error)
// IsDir returns true if the path is a directory. // IsDir returns true if the path is a directory.
IsDir(path string) bool 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 // CleanedAbs converts the given path into a
// directory and a file name, where the directory // directory and a file name, where the directory
// is represented as a ConfirmedDir and all that implies. // is represented as a ConfirmedDir and all that implies.

View File

@@ -349,6 +349,29 @@ func (n *fsNode) IsDir(path string) bool {
return result.isNodeADir() 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. // Size returns the size of the node.
func (n *fsNode) Size() int64 { func (n *fsNode) Size() int64 {
if n.isNodeADir() { if n.isNodeADir() {

View File

@@ -100,6 +100,19 @@ func (fsOnDisk) IsDir(name string) bool {
return info.IsDir() 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. // ReadFile delegates to ioutil.ReadFile.
func (fsOnDisk) ReadFile(name string) ([]byte, error) { return ioutil.ReadFile(name) } func (fsOnDisk) ReadFile(name string) ([]byte, error) { return ioutil.ReadFile(name) }