Skip to content

Commit

Permalink
Merge pull request #213 from helen-frank/feature/deferFileClose
Browse files Browse the repository at this point in the history
atomicWriteFile: file defer close
  • Loading branch information
dmcgowan authored Mar 6, 2023
2 parents d6500b3 + 9eb2a49 commit 6f1e02f
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions ioutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,26 +37,32 @@ func atomicWriteFile(filename string, r io.Reader, dataSize int64, perm os.FileM
if err != nil {
return err
}
needClose := true
defer func() {
if needClose {
f.Close()
}
}()

err = os.Chmod(f.Name(), perm)
if err != nil {
f.Close()
return err
}
n, err := io.Copy(f, r)
if err == nil && n < dataSize {
f.Close()
return io.ErrShortWrite
}
if err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
if err = f.Sync(); err != nil {
return err
}

needClose = false
if err := f.Close(); err != nil {
return err
}

return os.Rename(f.Name(), filename)
}

0 comments on commit 6f1e02f

Please sign in to comment.