github.com/haraldrudell/parl@v0.4.176/pfs/is-directory.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 const ( 16 // if path does not exist, return the error [IsDirectory] 17 IsDirectoryNonExistentIsError IsDirectoryArg = 1 << iota 18 // if existing path is not directory, return an error [IsDirectory] 19 // - symlinks are followed, so a symlink pointing ot directory is ok 20 IsDirectoryNotDirIsError 21 ) 22 23 // bitfield argument to [IsDirectory] 24 // - IsDirectoryNonExistentIsError IsDirectoryNotDirIsError 25 type IsDirectoryArg uint8 26 27 // IsDirectory determines if path exists, is directory or another type of file-system entry 28 // - path may be relative, contain symlinks or be unclean 29 // - isDirectory is true if path exists and is directory. 30 // Non-existing path is not an error. 31 // - if IsDirectoryNonExistentIsError is present, 32 // non-existing path returns error 33 // - if IsDirectoryNotDirIsError is present, 34 // a file-system entry that is not directory returns error 35 // - flags is bitfield: IsDirectoryNonExistentIsError | IsDirectoryNotDirIsError 36 // - symlinks are followed [os.Stat] 37 func IsDirectory(path string, flags IsDirectoryArg) (isDirectory bool, err error) { 38 var fileInfo fs.FileInfo 39 if fileInfo, err = Stat(path); err != nil { 40 if os.IsNotExist(err) { 41 if flags&IsDirectoryNonExistentIsError == 0 { 42 err = nil 43 } 44 } 45 return // stat error return, possibly ignored 46 } 47 if isDirectory = fileInfo.IsDir(); !isDirectory && IsDirectoryNotDirIsError != 0 { 48 err = perrors.Errorf("Not directory: %s", path) 49 } 50 51 return 52 }