github.com/haraldrudell/parl@v0.4.176/pfs/read-dir.go (about)

     1  /*
     2  © 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pfs
     7  
     8  import (
     9  	"io/fs"
    10  	"os"
    11  	"slices"
    12  
    13  	"github.com/haraldrudell/parl"
    14  	"github.com/haraldrudell/parl/perrors"
    15  )
    16  
    17  const (
    18  	// [DirectoryOrder]
    19  	NoSorting = false
    20  )
    21  
    22  // directoryOrder returns unsorted entries, most with deferred [fs.FileInfo]
    23  func ReadDir(abs string, sort ...bool) (entries []fs.DirEntry, err error) {
    24  	// open the directory
    25  	var osFile *os.File
    26  	if osFile, err = os.Open(abs); perrors.Is(&err, "os.Open %w", err) {
    27  		return
    28  	}
    29  	defer parl.Close(osFile, &err)
    30  
    31  	// reads in directory order
    32  	//	- returns an array of interface-value pointers, meaning
    33  	//		each DirEntry is a separate allocation
    34  	//	- for most modeTypes, Type is availble without lstat invocation
    35  	//	- lstat is then deferred until Info method is invoked.
    36  	//		Every time such deferring Info is invoked, lstat is executed
    37  	if entries, err = osFile.ReadDir(allNamesAtOnce); perrors.Is(&err, "os.File.ReadDir %w", err) {
    38  		return
    39  	}
    40  
    41  	// if NoSorting present, do not sort
    42  	if len(sort) > 0 && !sort[0] {
    43  		return
    44  	}
    45  
    46  	// sort by 8-bit characters
    47  	slices.SortFunc(entries, compareDirEntry)
    48  
    49  	return
    50  }