github.com/haraldrudell/parl@v0.4.176/pfs/exists.go (about)

     1  /*
     2  © 2021–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  
    12  	"github.com/haraldrudell/parl/perrors"
    13  )
    14  
    15  // Exists determines if a path exists
    16  // If the path exists, fileInfo is non-nil
    17  // if the path does not exist, fileInfo is nil
    18  // panic on troubles
    19  func Exists(path string) (fileInfo fs.FileInfo /* interface */) {
    20  	var err error
    21  	fileInfo, err = os.Stat(path)
    22  	if err == nil {
    23  		return // does exist: fileInfo
    24  	}
    25  	if os.IsNotExist(err) {
    26  		return // does not exist: nil
    27  	}
    28  	panic(perrors.Errorf("os.Stat: '%w'", err))
    29  }
    30  
    31  // Exists2 determines if a path exists
    32  //   - fileInfo non-nil: does exist
    33  //   - isNotExists true, fileInfo nil, err non-nil: does not exist
    34  //   - isNotExist false, fileInfo nil, err non-nil: some error
    35  func Exists2(path string) (fileInfo fs.FileInfo, isNotExist bool, err error) {
    36  	if fileInfo, err = os.Stat(path); err == nil {
    37  		return // does exist return : fileInfo non-nil, error nil
    38  	}
    39  	isNotExist = os.IsNotExist(err)
    40  	err = perrors.ErrorfPF("os.Stat %w", err)
    41  
    42  	return
    43  }