From 0a9fa4f2eaeb4f8d9689a6509dc5ab4a1c0959b9 Mon Sep 17 00:00:00 2001 From: Dmytro Maluka Date: Sun, 3 Aug 2025 18:41:34 +0200 Subject: [PATCH] Always use temporary file when writing backup When writing a backup file, we should write it atomically (i.e. use a temporary file + rename) in all cases, not only when replacing an existing backup. Just like we do in util.SafeWrite(). Otherwise, if micro crashes while writing this backup, even if that doesn't result in corrupting an existing good backup, it still results in creating an undesired backup with invalid contents. --- internal/buffer/backup.go | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/internal/buffer/backup.go b/internal/buffer/backup.go index e93cb069..9920897d 100644 --- a/internal/buffer/backup.go +++ b/internal/buffer/backup.go @@ -104,18 +104,8 @@ func (b *SharedBuffer) writeBackup(path string) (string, error) { } name := util.DetermineEscapePath(backupdir, path) - - // If no existing backup, just write the backup. - if _, err := os.Stat(name); errors.Is(err, fs.ErrNotExist) { - _, err = b.overwriteFile(name) - if err != nil { - os.Remove(name) - } - return name, err - } - - // If a backup already exists, replace it atomically. tmp := util.AppendBackupSuffix(name) + _, err := b.overwriteFile(tmp) if err != nil { os.Remove(tmp)