Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't overwrite save file on failed JSON serialization, fixes file corruption problem #132

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions PyFlow/App.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import shutil
from string import ascii_letters
import random
from datetime import datetime


from qtpy import QtGui
from qtpy import QtCore
Expand Down Expand Up @@ -413,10 +415,29 @@ def save(self, save_as=False):
self.currentFileName += ".pygraph"

if not self.currentFileName == "":
with open(self.currentFileName, "w") as f:
saveData = self.graphManager.get().serialize()
json.dump(saveData, f, indent=4)
print(str("// saved: '{0}'".format(self.currentFileName)))
# Get the current time and format it as a string
current_time = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")

tempFileName = self.currentFileName.replace(".pygraph", "") + f"-tempfile-{current_time}.pygraph"

# Open the temp file in 'w+' mode and the target file in 'w' mode
with open(tempFileName, "w+") as tempPtr, open(self.currentFileName, "r+") as filePtr:
try:
saveData = self.graphManager.get().serialize()
json.dump(saveData, tempPtr, indent=4)

# Move the file pointer to the beginning of the temp file before reading
tempPtr.seek(0)
filePtr.write(tempPtr.read())
tempPtr.close()

# If everything goes well, delete the temp file
os.remove(tempFileName)

print(f"// saved: '{self.currentFileName}'")
except Exception as e:
raise RuntimeError(f'JSON serialization failed.\nCould not save file \"{self.currentFileName}\"') from e

self.modified = False
self.updateLabel()
return True
Expand Down