internal/file/file.go (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | package file
import (
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/Southclaws/fault"
"github.com/Southclaws/fault/fmsg"
)
func Stat(path string) (fs.FileInfo, error) {
stat, err := os.Stat(path)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, fault.Wrap(err)
}
return stat, nil
}
func Exists(path string) bool {
stat, err := Stat(path)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
panic("could not stat path " + path + ": " + err.Error())
}
return stat != nil
}
func Copy(src, dest string) error {
stat, err := os.Stat(src)
if err != nil {
return fault.Wrap(err, fmsg.With("could not stat source file"))
}
sf, err := os.Open(src)
if err != nil {
return fault.Wrap(err, fmsg.With("could not open source file for reading"))
}
defer sf.Close()
df, err := os.OpenFile(dest, os.O_RDWR|os.O_CREATE, stat.Mode())
if err != nil {
return fault.Wrap(err, fmsg.With("could not open destination file for writing"))
}
defer df.Close()
if _, err := io.Copy(df, sf); err != nil {
return fault.Wrap(err, fmsg.With("could not copy"))
}
err = df.Sync()
if err != nil {
return fault.Wrap(err, fmsg.With("could not call fsync"))
}
return nil
}
func CleanDir(dir string) error {
files, err := os.ReadDir(dir)
if err != nil {
return fault.Wrap(fault.Wrap(err), fmsg.With("could not read directory"))
}
for _, file := range files {
err = errors.Join(err, os.RemoveAll(filepath.Join(dir, file.Name())))
}
return fault.Wrap(err)
}
|