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 | package file
import (
"io"
"io/fs"
"os"
"path/filepath"
"gitlab.com/tozd/go/errors"
)
func Stat(path string) (fs.FileInfo, errors.E) {
stat, err := os.Stat(path)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, errors.WithStack(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) errors.E {
stat, err := os.Stat(src)
if err != nil {
return errors.WithMessage(err, "could not stat source file")
}
sf, err := os.Open(src)
if err != nil {
return errors.WithMessage(err, "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 errors.WithMessage(err, "could not open destination file for writing")
}
defer df.Close()
if _, err := io.Copy(df, sf); err != nil {
return errors.WithMessage(err, "could not copy")
}
err = df.Sync()
if err != nil {
return errors.WithMessage(err, "could not call fsync")
}
return nil
}
func CleanDir(dir string) errors.E {
files, err := os.ReadDir(dir)
if err != nil {
return errors.WithMessage(errors.WithStack(err), "could not read directory")
}
for _, file := range files {
err = errors.Join(err, os.RemoveAll(filepath.Join(dir, file.Name())))
}
return errors.WithStack(err)
}
|