54 lines
996 B
Go
54 lines
996 B
Go
|
package fsutil
|
||
|
|
||
|
import (
|
||
|
"os"
|
||
|
)
|
||
|
|
||
|
// Return true if os.Stat doesn't return an error.
|
||
|
func PathExists(path string) bool {
|
||
|
_, err := os.Stat(path)
|
||
|
return err == nil
|
||
|
}
|
||
|
|
||
|
// Returns true if os.Stat doesn't return an error and the path is a regular file.
|
||
|
func FileExists(path string) bool {
|
||
|
fi, err := os.Stat(path)
|
||
|
if err != nil {
|
||
|
return false
|
||
|
}
|
||
|
return fi.Mode().IsRegular()
|
||
|
}
|
||
|
|
||
|
// Returns true if os.Stat doesn't return an error and the path is a directory.
|
||
|
func DirExists(path string) bool {
|
||
|
fi, err := os.Stat(path)
|
||
|
if err != nil {
|
||
|
return false
|
||
|
}
|
||
|
return fi.Mode().IsDir()
|
||
|
}
|
||
|
|
||
|
// Write a file atomically on a POSIX file system.
|
||
|
func WriteFileAtomic(data []byte, tmpPath, finalPath string) error {
|
||
|
f, err := os.Create(tmpPath)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if _, err := f.Write(data); err != nil {
|
||
|
f.Close()
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if err := f.Sync(); err != nil {
|
||
|
f.Close()
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if err := f.Close(); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return os.Rename(tmpPath, finalPath)
|
||
|
}
|