aboutsummaryrefslogtreecommitdiff
path: root/internal/journal/journal.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/journal/journal.go')
-rw-r--r--internal/journal/journal.go26
1 files changed, 25 insertions, 1 deletions
diff --git a/internal/journal/journal.go b/internal/journal/journal.go
index 465cd51..085c88a 100644
--- a/internal/journal/journal.go
+++ b/internal/journal/journal.go
@@ -54,13 +54,37 @@ func Open(path string) (*Writer, error) {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return nil, fmt.Errorf("journal: %w", err)
}
- f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
+ f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return nil, fmt.Errorf("journal: %w", err)
}
+ if err := endWithNewline(f); err != nil {
+ f.Close()
+ return nil, fmt.Errorf("journal: %w", err)
+ }
return &Writer{f: f}, nil
}
+// endWithNewline restores a missing final newline. A crash can cut the log's
+// last line short (spec ยง15.1: krino survives a truncated line); appending
+// straight after the fragment would glue the next run's first line onto it,
+// and that run could then never be undone.
+func endWithNewline(f *os.File) error {
+ fi, err := f.Stat()
+ if err != nil || fi.Size() == 0 {
+ return err
+ }
+ last := make([]byte, 1)
+ if _, err := f.ReadAt(last, fi.Size()-1); err != nil {
+ return err
+ }
+ if last[0] == '\n' {
+ return nil
+ }
+ _, err = f.Write([]byte{'\n'})
+ return err
+}
+
// Append writes e as one line and flushes it before returning. The whole
// line is written with a single Write call so that two concurrent runs
// appending to the same file cannot interleave a partial line.