diff --git a/ioutils.go b/ioutils.go index 392c407f..c0c8f011 100644 --- a/ioutils.go +++ b/ioutils.go @@ -32,31 +32,39 @@ func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error { // atomicWriteFile writes data to a file by first writing to a temp // file and calling rename. -func atomicWriteFile(filename string, r io.Reader, dataSize int64, perm os.FileMode) error { - f, err := os.CreateTemp(filepath.Dir(filename), ".tmp-"+filepath.Base(filename)) +func atomicWriteFile(filename string, r io.Reader, dataSize int64, perm os.FileMode) (err error) { + var ( + f *os.File + n int64 + ) + + f, err = os.CreateTemp(filepath.Dir(filename), ".tmp-"+filepath.Base(filename)) if err != nil { - return err + return } + defer func() { + f.Close() + if err == nil { + err = os.Rename(f.Name(), filename) + } + }() + err = os.Chmod(f.Name(), perm) if err != nil { - f.Close() - return err + return } - n, err := io.Copy(f, r) + n, err = io.Copy(f, r) if err == nil && n < dataSize { - f.Close() - return io.ErrShortWrite + err = io.ErrShortWrite + return } if err != nil { - f.Close() - return err - } - if err := f.Sync(); err != nil { - f.Close() - return err + return } - if err := f.Close(); err != nil { - return err + + if err = f.Sync(); err != nil { + return } - return os.Rename(f.Name(), filename) + + return nil }