package file import ( "io" "io/fs" "os" "path/filepath" "gitlab.com/tozd/go/errors" ) func Exists(path string) bool { stat, err := os.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 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) (err error) { files, err := os.ReadDir(dir) if err != nil { return errors.WithMessage(err, "could not read directory") } for _, file := range files { err = errors.Join(err, os.RemoveAll(filepath.Join(dir, file.Name()))) } return err }