Skip to content

Commit

Permalink
atomicWriteFile: file defer close
Browse files Browse the repository at this point in the history
Signed-off-by: helen <[email protected]>
  • Loading branch information
helen committed Feb 22, 2023
1 parent 2a963a2 commit 972ff0d
Showing 1 changed file with 25 additions and 17 deletions.
42 changes: 25 additions & 17 deletions ioutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 972ff0d

Please sign in to comment.