github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/io/fs/readdir.go (about) 1 // Copyright 2020 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package fs 6 7 import ( 8 "errors" 9 "sort" 10 ) 11 12 // ReadDirFS is the interface implemented by a file system 13 // that provides an optimized implementation of ReadDir. 14 type ReadDirFS interface { 15 FS 16 17 // ReadDir reads the named directory 18 // and returns a list of directory entries sorted by filename. 19 ReadDir(name string) ([]DirEntry, error) 20 } 21 22 // ReadDir reads the named directory 23 // and returns a list of directory entries sorted by filename. 24 // 25 // If fs implements ReadDirFS, ReadDir calls fs.ReadDir. 26 // Otherwise ReadDir calls fs.Open and uses ReadDir and Close 27 // on the returned file. 28 func ReadDir(fsys FS, name string) ([]DirEntry, error) { 29 if fsys, ok := fsys.(ReadDirFS); ok { 30 return fsys.ReadDir(name) 31 } 32 33 file, err := fsys.Open(name) 34 if err != nil { 35 return nil, err 36 } 37 defer file.Close() 38 39 dir, ok := file.(ReadDirFile) 40 if !ok { 41 return nil, &PathError{Op: "readdir", Path: name, Err: errors.New("not implemented")} 42 } 43 44 list, err := dir.ReadDir(-1) 45 sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() }) 46 return list, err 47 }