Skip to content

[Bug]: MigrateCommand backup operation is not atomic — risk of data loss #196

@Splatcrafter

Description

@Splatcrafter

AI REVIEWED

Module: cli
File: cli/command/MigrateCommand.java (~line 656-661)
Severity: High

Summary

The backup-then-write operation is not atomic. If the write fails after the backup has replaced a previous .bak file, both the original and backup may be corrupted.

Files.copy(inputFile.toPath(), backupPath, StandardCopyOption.REPLACE_EXISTING);
Files.writeString(inputFile.toPath(), content); // if this fails, original is gone

Suggested Fix

Write to a temp file first, then atomically move:

Path tempPath = Files.createTempFile(inputFile.toPath().getParent(), "migrate_", ".tmp");
try {
    Files.writeString(tempPath, content, StandardCharsets.UTF_8);
    if (this.backup) {
        Files.move(inputFile.toPath(), backupPath, StandardCopyOption.REPLACE_EXISTING);
    }
    Files.move(tempPath, inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    Files.deleteIfExists(tempPath);
    throw e;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions