Skip to content

Commit

Permalink
Avoid corrupting project files if saving fails/is interrupted
Browse files Browse the repository at this point in the history
  • Loading branch information
dgelessus committed Apr 23, 2021
1 parent 44783c8 commit 1972a23
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ prob_test_log.txt
*.log
*.log.*
*.prob
*.prob2project.tmp

# TestFX screenshots
screenshot*.png
14 changes: 13 additions & 1 deletion src/main/java/de/prob2/ui/project/ProjectManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Expand Down Expand Up @@ -184,11 +185,22 @@ public void saveCurrentProject() {
);
currentProject.set(updatedProject);

// To avoid corrupting the previously saved project if saving fails/is interrupted for some reason,
// save the project under a temporary file name first,
// and only once the project has been fully saved rename it to the real file name
// (overwriting any existing project file with that name).
final Path tempLocation = location.resolveSibling(location.getFileName() + ".tmp");
try {
this.jacksonManager.writeToFile(location, updatedProject);
this.jacksonManager.writeToFile(tempLocation, updatedProject);
Files.move(tempLocation, location, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException | RuntimeException exc) {
LOGGER.warn("Failed to save project", exc);
stageManager.makeExceptionAlert(exc, "project.projectManager.alerts.failedToSaveProject.header", "project.projectManager.alerts.failedToSaveProject.content").show();
try {
Files.deleteIfExists(tempLocation);
} catch (IOException e) {
LOGGER.warn("Failed to delete temporary project file after project save error", e);
}
return;
}

Expand Down

0 comments on commit 1972a23

Please sign in to comment.