atomicWriteFile writes data to path via a same-directory temp file and an atomic rename, so readers (and crashes) only ever observe the old or the new content — never a torn write.
(path string, data []byte, perm os.FileMode)
| 28 | // atomic rename, so readers (and crashes) only ever observe the old or the new |
| 29 | // content — never a torn write. |
| 30 | func atomicWriteFile(path string, data []byte, perm os.FileMode) error { |
| 31 | dir := filepath.Dir(path) |
| 32 | tmp, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp") |
| 33 | if err != nil { |
| 34 | return err |
| 35 | } |
| 36 | tmpName := tmp.Name() |
| 37 | cleanup := func() { _ = os.Remove(tmpName) } |
| 38 | |
| 39 | if _, err := tmp.Write(data); err != nil { |
| 40 | _ = tmp.Close() |
| 41 | cleanup() |
| 42 | return err |
| 43 | } |
| 44 | if err := tmp.Chmod(perm); err != nil { |
| 45 | _ = tmp.Close() |
| 46 | cleanup() |
| 47 | return err |
| 48 | } |
| 49 | if err := tmp.Close(); err != nil { |
| 50 | cleanup() |
| 51 | return err |
| 52 | } |
| 53 | if err := os.Rename(tmpName, path); err != nil { |
| 54 | cleanup() |
| 55 | return err |
| 56 | } |
| 57 | return nil |
| 58 | } |
| 59 | |
| 60 | // quarantineCorrupt moves an unparseable store file aside as |
| 61 | // "<path>.corrupt" (or a timestamped variant when a previous quarantine |