github.com/haraldrudell/parl@v0.4.176/pfs/info-defer-entry.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  	"path/filepath"
    12  
    13  	"github.com/haraldrudell/parl/perrors"
    14  )
    15  
    16  type DeferringDirEntry struct {
    17  	abs string
    18  }
    19  
    20  var _ fs.DirEntry = &DeferringDirEntry{}
    21  
    22  // NewDeferringDirEntry returns [fs.DirEntry] with [fs.FileInfo] deferred
    23  //   - abs is absolute path that maybe does not exist
    24  func NewDeferringDirEntry(abs string) (entry *DeferringDirEntry) { return &DeferringDirEntry{abs: abs} }
    25  
    26  // Info returns the FileInfo for the file or subdirectory described by the entry
    27  //   - thread-safe, does [os.Lstat] every time
    28  func (e *DeferringDirEntry) Info() (fileInfo fs.FileInfo, err error) {
    29  	if fileInfo, err = os.Lstat(e.abs); err != nil {
    30  		err = perrors.ErrorfPF("os.Lstat %w", err)
    31  	}
    32  
    33  	return
    34  }
    35  
    36  // IsDir reports whether the entry is a directory, ie. ModeDir bit being set
    37  //   - may panic unless Info has successfully completed
    38  func (e *DeferringDirEntry) IsDir() (isDir bool) {
    39  	var fileInfo, err = e.Info()
    40  	if err != nil {
    41  		panic(err)
    42  	}
    43  	isDir = fileInfo.IsDir()
    44  
    45  	return
    46  }
    47  
    48  // base name of the file
    49  func (e *DeferringDirEntry) Name() (base string) { return filepath.Base(e.abs) }
    50  
    51  // Type returns ModeType bits, 0 for regular file
    52  //   - ModeDir ModeSymlink ModeNamedPipe ModeSocket ModeDevice ModeCharDevice ModeIrregular
    53  func (e *DeferringDirEntry) Type() (modeType fs.FileMode) {
    54  	var fileInfo, err = e.Info()
    55  	if err != nil {
    56  		panic(err)
    57  	}
    58  	modeType = fileInfo.Mode().Type()
    59  
    60  	return
    61  }