Source file src/io/fs/readdir.go

     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  }
    48  
    49  // dirInfo is a DirEntry based on a FileInfo.
    50  type dirInfo struct {
    51  	fileInfo FileInfo
    52  }
    53  
    54  func (di dirInfo) IsDir() bool {
    55  	return di.fileInfo.IsDir()
    56  }
    57  
    58  func (di dirInfo) Type() FileMode {
    59  	return di.fileInfo.Mode().Type()
    60  }
    61  
    62  func (di dirInfo) Info() (FileInfo, error) {
    63  	return di.fileInfo, nil
    64  }
    65  
    66  func (di dirInfo) Name() string {
    67  	return di.fileInfo.Name()
    68  }
    69  
    70  // FileInfoToDirEntry returns a DirEntry that returns information from info.
    71  // If info is nil, FileInfoToDirEntry returns nil.
    72  func FileInfoToDirEntry(info FileInfo) DirEntry {
    73  	if info == nil {
    74  		return nil
    75  	}
    76  	return dirInfo{fileInfo: info}
    77  }
    78  

View as plain text