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.
This commit is contained in:
Dmytro Maluka
2025-08-03 18:41:34 +02:00
parent a862c9709e
commit 0a9fa4f2ea

View File

@@ -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)