From 4252df9682cd1e8425095a88426a7f8f533f3016 Mon Sep 17 00:00:00 2001 From: "Veronica K. B. Olsen" <1619840+vkbo@users.noreply.github.com> Date: Sat, 2 Nov 2019 12:25:37 +0100 Subject: [PATCH] Add backups of the project xml file as a rolling version in the cashe folder --- nw/project/project.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/nw/project/project.py b/nw/project/project.py index 06c3d593..23e46e9e 100644 --- a/nw/project/project.py +++ b/nw/project/project.py @@ -14,6 +14,7 @@ import logging import nw from os import path, mkdir, listdir +from shutil import copyfile from lxml import etree from hashlib import sha256 from datetime import datetime @@ -288,6 +289,9 @@ class NWProject(): logger.debug("Saving project: %s" % self.projPath) + # Save a copy of the current file, just in case + self._maintainPrevious() + # Root element and project details logger.debug("Writing project meta") nwXML = etree.Element("novelWriterXML",attrib={ @@ -699,4 +703,41 @@ class NWProject(): itemHandle = self._makeHandle(addSeed+"!") return itemHandle + def _maintainPrevious(self): + """This function will take the current project file and copy it into the project cache + folder with an incremental file extension added. These serve as a backup in case the xml + file gets corrupted. + """ + + countFile = path.join(self.projCache, "projCount.txt") + projCount = 0 + + if path.isfile(countFile): + try: + with open(countFile, mode="r") as inFile: + projCount = int(inFile.read())+1 + except: + projCount = 0 + + if projCount > 9: + projCount = 0 + + projBackup = "%s.%d" % (nwFiles.PROJ_FILE, projCount) + + try: + copyfile( + path.join(self.projPath,self.projFile), + path.join(self.projCache,projBackup) + ) + except: + logger.error("Failed to write to file %s" % projBackup) + + try: + with open(countFile, mode="w") as outFile: + outFile.write(str(projCount)) + except: + logger.error("Failed to write to file %s" % countFile) + + return + # END Class NWProject