github.com/gofunct/common@v0.0.0-20190131174352-fd058c7fbf22/pkg/path/file.go (about) 1 package path 2 3 import ( 4 "errors" 5 "os" 6 ) 7 8 // LinkTreatment is the base type for constants used by Exists that indicate 9 // how symlinks are treated for existence checks. 10 type LinkTreatment int 11 12 const ( 13 // CheckFollowSymlink follows the symlink and verifies that the target of 14 // the symlink exists. 15 CheckFollowSymlink LinkTreatment = iota 16 17 // CheckSymlinkOnly does not follow the symlink and verfies only that they 18 // symlink itself exists. 19 CheckSymlinkOnly 20 ) 21 22 // ErrInvalidLinkTreatment indicates that the link treatment behavior requested 23 // is not a valid behavior. 24 var ErrInvalidLinkTreatment = errors.New("unknown link behavior") 25 26 // Exists checks if specified file, directory, or symlink exists. The behavior 27 // of the test depends on the linkBehaviour argument. See LinkTreatment for 28 // more details. 29 func Exists(linkBehavior LinkTreatment, filename string) (bool, error) { 30 var err error 31 _, err = os.Stat(filename) 32 33 if os.IsNotExist(err) { 34 return false, nil 35 } else if err != nil { 36 return false, err 37 } 38 return true, nil 39 } 40 41 // ReadDirNoStat returns a string of files/directories contained 42 // in dirname without calling lstat on them. 43 func ReadDirNoStat(dirname string) ([]string, error) { 44 if dirname == "" { 45 dirname = "." 46 } 47 48 f, err := os.Open(dirname) 49 if err != nil { 50 return nil, err 51 } 52 defer f.Close() 53 54 return f.Readdirnames(-1) 55 }