github.com/safing/portbase@v0.19.5/utils/fs.go (about) 1 package utils 2 3 import ( 4 "errors" 5 "fmt" 6 "io/fs" 7 "os" 8 "runtime" 9 ) 10 11 const isWindows = runtime.GOOS == "windows" 12 13 // EnsureDirectory ensures that the given directory exists and that is has the given permissions set. 14 // If path is a file, it is deleted and a directory created. 15 func EnsureDirectory(path string, perm os.FileMode) error { 16 // open path 17 f, err := os.Stat(path) 18 if err == nil { 19 // file exists 20 if f.IsDir() { 21 // directory exists, check permissions 22 if isWindows { 23 // TODO: set correct permission on windows 24 // acl.Chmod(path, perm) 25 } else if f.Mode().Perm() != perm { 26 return os.Chmod(path, perm) 27 } 28 return nil 29 } 30 err = os.Remove(path) 31 if err != nil { 32 return fmt.Errorf("could not remove file %s to place dir: %w", path, err) 33 } 34 } 35 // file does not exist (or has been deleted) 36 if err == nil || errors.Is(err, fs.ErrNotExist) { 37 err = os.Mkdir(path, perm) 38 if err != nil { 39 return fmt.Errorf("could not create dir %s: %w", path, err) 40 } 41 return os.Chmod(path, perm) 42 } 43 // other error opening path 44 return fmt.Errorf("failed to access %s: %w", path, err) 45 } 46 47 // PathExists returns whether the given path (file or dir) exists. 48 func PathExists(path string) bool { 49 _, err := os.Stat(path) 50 return err == nil || errors.Is(err, fs.ErrExist) 51 }