mirror of
https://github.com/tiennm99/awesome-ai-dev-tools.git
synced 2026-10-05 12:14:01 +00:00
README.md and site/data.json were written with os.Create/os.WriteFile, so a write that failed midway left the repo front page truncated, while history.jsonl already used a temp-file-plus-rename. Extract that pattern into atomicWriteFile and route all three writers through it. Also sort snapshots by date when reading history.jsonl: delta windows pick the newest snapshot inside the window by scan order, which silently produces wrong deltas if a hand edit or a merge of two concurrent runs interleaves lines. Cover the README renderer, which had no test beyond sanitizeCell, and name the generated paths as constants instead of repeating literals. Coverage 65.1% -> 75.7%.
39 lines
1.0 KiB
Go
39 lines
1.0 KiB
Go
package main
|
|
|
|
import (
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
// atomicWriteFile writes through a temp file in the same directory and renames
|
|
// it over path, so a crash or a failed write never leaves a generated file
|
|
// truncated or half-written. The callback receives the temp file as an
|
|
// io.Writer, which suits streaming producers (templates, JSON encoders)
|
|
// without buffering the whole payload in memory.
|
|
//
|
|
// Errors from Sync and Close are reported too: on a write path they are the
|
|
// difference between "data reached the disk" and silent loss.
|
|
func atomicWriteFile(path string, write func(io.Writer) error) error {
|
|
tmp := path + ".tmp"
|
|
f, err := os.Create(tmp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
writeErr := write(f)
|
|
|
|
if syncErr := f.Sync(); syncErr != nil && writeErr == nil {
|
|
writeErr = syncErr
|
|
}
|
|
if closeErr := f.Close(); closeErr != nil && writeErr == nil {
|
|
writeErr = closeErr
|
|
}
|
|
|
|
if writeErr != nil {
|
|
_ = os.Remove(tmp) // best-effort cleanup; the write error is what matters
|
|
return writeErr
|
|
}
|
|
|
|
return os.Rename(tmp, path)
|
|
}
|