writeFileAtomic writes data to path via a sibling temp file followed by an os.Rename. If the process is killed mid-write, the original file is preserved intact instead of being truncated/partial — which os.WriteFile + O_TRUNC|O_WRONLY would leave behind. The temp file lives in the same directory so
(path string, data []byte, mode os.FileMode)
| 16 | // runs on every error path so stray temps don't accumulate when the |
| 17 | // destination directory is read-only or out of inodes. |
| 18 | func writeFileAtomic(path string, data []byte, mode os.FileMode) error { |
| 19 | dir := filepath.Dir(path) |
| 20 | f, err := os.CreateTemp(dir, "."+filepath.Base(path)+".tmp-*") |
| 21 | if err != nil { |
| 22 | return fmt.Errorf("create temp file: %w", err) |
| 23 | } |
| 24 | tmp := f.Name() |
| 25 | cleanup := func() { _ = os.Remove(tmp) } |
| 26 | |
| 27 | if _, err := f.Write(data); err != nil { |
| 28 | _ = f.Close() |
| 29 | cleanup() |
| 30 | return fmt.Errorf("write temp file: %w", err) |
| 31 | } |
| 32 | if err := f.Chmod(mode); err != nil { |
| 33 | _ = f.Close() |
| 34 | cleanup() |
| 35 | return fmt.Errorf("chmod temp file: %w", err) |
| 36 | } |
| 37 | if err := f.Close(); err != nil { |
| 38 | cleanup() |
| 39 | return fmt.Errorf("close temp file: %w", err) |
| 40 | } |
| 41 | if err := os.Rename(tmp, path); err != nil { |
| 42 | cleanup() |
| 43 | return fmt.Errorf("rename temp file: %w", err) |
| 44 | } |
| 45 | return nil |
| 46 | } |
no test coverage detected