dump safely by writing to tempfile

First write all the dump to a temporary file.
Rename temp file to actual file name when done.
This prevents savefile corruption when botany crashes during write.
pull/9/head
troido 2018-05-23 21:21:50 +02:00
parent 09b18e862d
commit d0bc57226a
1 changed files with 6 additions and 2 deletions

View File

@ -543,8 +543,10 @@ class DataManager(object):
def save_plant(self, this_plant): def save_plant(self, this_plant):
# create savefile # create savefile
this_plant.last_time = int(time.time()) this_plant.last_time = int(time.time())
with open(self.savefile_path, 'wb') as f: temp_path = self.savefile_path + ".temp"
with open(temp_path, 'wb') as f:
pickle.dump(this_plant, f, protocol=2) pickle.dump(this_plant, f, protocol=2)
os.rename(temp_path, self.savefile_path)
def data_write_json(self, this_plant): def data_write_json(self, this_plant):
# create personal json file for user to use outside of the game (website?) # create personal json file for user to use outside of the game (website?)
@ -598,8 +600,10 @@ class DataManager(object):
this_harvest[this_plant_id] = plant_info this_harvest[this_plant_id] = plant_info
# dump harvest file # dump harvest file
with open(self.harvest_file_path, 'wb') as f: temp_path = self.harvest_file_path + ".temp"
with open(temp_path, 'wb') as f:
pickle.dump(this_harvest, f, protocol=2) pickle.dump(this_harvest, f, protocol=2)
os.rename(temp_path, self.harvest_file_path)
# dump json file # dump json file
with open(self.harvest_json_path, 'w') as outfile: with open(self.harvest_json_path, 'w') as outfile:
json.dump(this_harvest, outfile) json.dump(this_harvest, outfile)