Converted version_1.py to new logging style

It had its own mini-logging facility to suppress the most useless debug
messages. Since the new facility does not show debug messages to the
user, but still allows them to end up in the log file, I replaced it
entirely with DEBUG-level logging.

Some spots have received an extra ERROR-level logging on top for the
sake of alerting the user to issues we would like to hear about, and to
avoid breaking up the hierarchical indenting done by the DEBUG-level
messages.
This commit is contained in:
Jan Wester 2019-10-14 14:56:55 +02:00
parent ff2cbca028
commit 37becdf80a

View file

@ -54,8 +54,6 @@ characterMap = OrderedDict([
(Character.notes, "Notes") (Character.notes, "Notes")
]) ])
# If true, logs infos while saving and loading.
LOG = False
def formatMetaData(name, value, tabLength=10): def formatMetaData(name, value, tabLength=10):
@ -95,11 +93,6 @@ def slugify(name):
return newName return newName
def log(*args):
if LOG:
print(" ".join(str(a) for a in args))
def saveProject(zip=None): def saveProject(zip=None):
""" """
Saves the project. If zip is False, the project is saved as a multitude of plain-text files for the most parts Saves the project. If zip is False, the project is saved as a multitude of plain-text files for the most parts
@ -113,7 +106,7 @@ def saveProject(zip=None):
if zip == None: if zip == None:
zip = settings.saveToZip zip = settings.saveToZip
log("\n\nSaving to:", "zip" if zip else "folder") LOGGER.info("Saving to: %s", "zip" if zip else "folder")
# List of files to be written # List of files to be written
files = [] files = []
@ -344,7 +337,7 @@ def saveProject(zip=None):
folder = os.path.splitext(os.path.basename(project))[0] folder = os.path.splitext(os.path.basename(project))[0]
# Debug # Debug
log("\nSaving to folder", folder) LOGGER.debug("Saving to folder %s", folder)
# If cache is empty (meaning we haven't loaded from disk), we wipe folder, just to be sure. # If cache is empty (meaning we haven't loaded from disk), we wipe folder, just to be sure.
if not cache: if not cache:
@ -361,7 +354,7 @@ def saveProject(zip=None):
# Move the old file to the new place # Move the old file to the new place
try: try:
os.replace(oldPath, newPath) os.replace(oldPath, newPath)
log("* Renaming/moving {} to {}".format(old, new)) LOGGER.debug("* Renaming/moving {} to {}".format(old, new))
except FileNotFoundError: except FileNotFoundError:
# Maybe parent folder has been renamed # Maybe parent folder has been renamed
pass pass
@ -371,7 +364,7 @@ def saveProject(zip=None):
for f in cache: for f in cache:
f2 = f.replace(old, new) f2 = f.replace(old, new)
if f2 != f: if f2 != f:
log(" * Updating cache:", f, f2) LOGGER.debug(" * Updating cache: %s, %s", f, f2)
cache2[f2] = cache[f] cache2[f2] = cache[f]
cache = cache2 cache = cache2
@ -382,7 +375,7 @@ def saveProject(zip=None):
# Check if content is in cache, and write if necessary # Check if content is in cache, and write if necessary
if path not in cache or cache[path] != content: if path not in cache or cache[path] != content:
log("* Writing file {} ({})".format(path, "not in cache" if path not in cache else "different")) LOGGER.debug("* Writing file {} ({})".format(path, "not in cache" if path not in cache else "different"))
# mode = "w" + ("b" if type(content) == bytes else "") # mode = "w" + ("b" if type(content) == bytes else "")
if type(content) == bytes: if type(content) == bytes:
with open(filename, "wb") as f: with open(filename, "wb") as f:
@ -396,7 +389,7 @@ def saveProject(zip=None):
# Removing phantoms # Removing phantoms
for path in [p for p in cache if p not in [p for p, c in files]]: for path in [p for p in cache if p not in [p for p, c in files]]:
filename = os.path.join(dir, folder, path) filename = os.path.join(dir, folder, path)
log("* Removing", path) LOGGER.debug("* Removing %s", path)
if os.path.isdir(filename): if os.path.isdir(filename):
shutil.rmtree(filename) shutil.rmtree(filename)
@ -413,7 +406,7 @@ def saveProject(zip=None):
newDir = os.path.join(root, dir) newDir = os.path.join(root, dir)
try: try:
os.removedirs(newDir) os.removedirs(newDir)
log("* Removing empty directory:", newDir) LOGGER.debug("* Removing empty directory: %s", newDir)
except: except:
# Directory not empty, we don't remove. # Directory not empty, we don't remove.
pass pass
@ -539,8 +532,8 @@ def exportOutlineItem(root):
lp = child._lastPath lp = child._lastPath
if lp and spath != lp: if lp and spath != lp:
moves.append((lp, spath)) moves.append((lp, spath))
log(child.title(), "has been renamed (", lp, "", spath, ")") LOGGER.debug("%s has been renamed (%s%s)", child.title(), lp, spath)
log(" → We mark for moving:", lp) LOGGER.debug(" → We mark for moving: %s", lp)
# Updates item last's path # Updates item last's path
child._lastPath = spath child._lastPath = spath
@ -556,7 +549,7 @@ def exportOutlineItem(root):
files.append((spath, content)) files.append((spath, content))
else: else:
log("Unknown type") LOGGER.debug("Unknown type: %s", child.type())
f, m, r = exportOutlineItem(child) f, m, r = exportOutlineItem(child)
files += f files += f
@ -634,7 +627,7 @@ def loadProject(project, zip=None):
#################################################################################################################### ####################################################################################################################
# Read and store everything in a dict # Read and store everything in a dict
log("\nLoading {} ({})".format(project, "ZIP" if zip else "not zip")) LOGGER.debug("Loading {} ({})".format(project, "zip" if zip else "folder"))
if zip: if zip:
files = loadFilesFromZip(project) files = loadFilesFromZip(project)
@ -698,7 +691,7 @@ def loadProject(project, zip=None):
mdl = mw.mdlLabels mdl = mw.mdlLabels
mdl.appendRow(QStandardItem("")) # Empty = No labels mdl.appendRow(QStandardItem("")) # Empty = No labels
if "labels.txt" in files: if "labels.txt" in files:
log("\nReading labels:") LOGGER.debug("Reading labels:")
for s in files["labels.txt"].split("\n"): for s in files["labels.txt"].split("\n"):
if not s: if not s:
continue continue
@ -706,7 +699,7 @@ def loadProject(project, zip=None):
m = re.search(r"^(.*?):\s*(.*)$", s) m = re.search(r"^(.*?):\s*(.*)$", s)
txt = m.group(1) txt = m.group(1)
col = m.group(2) col = m.group(2)
log("* Add status: {} ({})".format(txt, col)) LOGGER.debug("* Add status: {} ({})".format(txt, col))
icon = iconFromColorString(col) icon = iconFromColorString(col)
mdl.appendRow(QStandardItem(icon, txt)) mdl.appendRow(QStandardItem(icon, txt))
@ -719,11 +712,11 @@ def loadProject(project, zip=None):
mdl = mw.mdlStatus mdl = mw.mdlStatus
mdl.appendRow(QStandardItem("")) # Empty = No status mdl.appendRow(QStandardItem("")) # Empty = No status
if "status.txt" in files: if "status.txt" in files:
log("\nReading Status:") LOGGER.debug("Reading status:")
for s in files["status.txt"].split("\n"): for s in files["status.txt"].split("\n"):
if not s: if not s:
continue continue
log("* Add status:", s) LOGGER.debug("* Add status: %s", s)
mdl.appendRow(QStandardItem(s)) mdl.appendRow(QStandardItem(s))
else: else:
errors.append("status.txt") errors.append("status.txt")
@ -765,7 +758,7 @@ def loadProject(project, zip=None):
mdl = mw.mdlPlots mdl = mw.mdlPlots
if "plots.xml" in files: if "plots.xml" in files:
log("\nReading plots:") LOGGER.debug("Reading plots:")
# xml = bytearray(files["plots.xml"], "utf-8") # xml = bytearray(files["plots.xml"], "utf-8")
root = ET.fromstring(files["plots.xml"]) root = ET.fromstring(files["plots.xml"])
@ -774,7 +767,7 @@ def loadProject(project, zip=None):
row = getStandardItemRowFromXMLEnum(plot, Plot) row = getStandardItemRowFromXMLEnum(plot, Plot)
# Log # Log
log("* Add plot: ", row[0].text()) LOGGER.debug("* Add plot: %s", row[0].text())
# Characters # Characters
if row[Plot.characters].text(): if row[Plot.characters].text():
@ -801,7 +794,7 @@ def loadProject(project, zip=None):
mdl = mw.mdlWorld mdl = mw.mdlWorld
if "world.opml" in files: if "world.opml" in files:
log("\nReading World:") LOGGER.debug("Reading World:")
# xml = bytearray(files["plots.xml"], "utf-8") # xml = bytearray(files["plots.xml"], "utf-8")
root = ET.fromstring(files["world.opml"]) root = ET.fromstring(files["world.opml"])
body = root.find("body") body = root.find("body")
@ -817,7 +810,7 @@ def loadProject(project, zip=None):
# Characters # Characters
mdl = mw.mdlCharacter mdl = mw.mdlCharacter
log("\nReading Characters:") LOGGER.debug("Reading Characters:")
for f in [f for f in files if "characters" in f]: for f in [f for f in files if "characters" in f]:
md, body = parseMMDFile(files[f]) md, body = parseMMDFile(files[f])
c = mdl.addCharacter() c = mdl.addCharacter()
@ -843,7 +836,7 @@ def loadProject(project, zip=None):
else: else:
c.infos.append(CharacterInfo(c, desc, val)) c.infos.append(CharacterInfo(c, desc, val))
log("* Adds {} ({})".format(c.name(), c.ID())) LOGGER.debug("* Adds {} ({})".format(c.name(), c.ID()))
#################################################################################################################### ####################################################################################################################
# Texts # Texts
@ -851,14 +844,14 @@ def loadProject(project, zip=None):
# everything, but the outline folder takes precedence (in cases it's been edited outside of manuskript. # everything, but the outline folder takes precedence (in cases it's been edited outside of manuskript.
mdl = mw.mdlOutline mdl = mw.mdlOutline
log("\nReading outline:") LOGGER.debug("Reading outline:")
paths = [f for f in files if "outline" in f] paths = [f for f in files if "outline" in f]
outline = OrderedDict() outline = OrderedDict()
# We create a structure of imbricated OrderedDict to store the whole tree. # We create a structure of imbricated OrderedDict to store the whole tree.
for f in paths: for f in paths:
split = f.split(os.path.sep)[1:] split = f.split(os.path.sep)[1:]
# log("* ", split) # LOGGER.debug("* %s", split)
last = "" last = ""
parent = outline parent = outline
@ -913,7 +906,7 @@ def addTextItems(mdl, odict, parent=None):
if type(odict[k]) == OrderedDict and "folder.txt" in odict[k]: if type(odict[k]) == OrderedDict and "folder.txt" in odict[k]:
# Adds folder # Adds folder
log("{}* Adds {} to {} (folder)".format(" " * parent.level(), k, parent.title())) LOGGER.debug("{}* Adds {} to {} (folder)".format(" " * parent.level(), k, parent.title()))
item = outlineFromMMD(odict[k]["folder.txt"], parent=parent) item = outlineFromMMD(odict[k]["folder.txt"], parent=parent)
item._lastPath = odict[k + ":lastPath"] item._lastPath = odict[k + ":lastPath"]
@ -922,7 +915,7 @@ def addTextItems(mdl, odict, parent=None):
# k is not a folder # k is not a folder
elif type(odict[k]) == str and k != "folder.txt" and not ":lastPath" in k: elif type(odict[k]) == str and k != "folder.txt" and not ":lastPath" in k:
log("{}* Adds {} to {} (file)".format(" " * parent.level(), k, parent.title())) LOGGER.debug("{}* Adds {} to {} (file)".format(" " * parent.level(), k, parent.title()))
item = outlineFromMMD(odict[k], parent=parent) item = outlineFromMMD(odict[k], parent=parent)
item._lastPath = odict[k + ":lastPath"] item._lastPath = odict[k + ":lastPath"]
@ -977,17 +970,19 @@ def appendRevisions(mdl, root):
# Get root's ID # Get root's ID
ID = root.attrib["ID"] ID = root.attrib["ID"]
if not ID: if not ID:
log("* Serious problem: no ID!") LOGGER.debug("* Serious problem: no ID!")
LOGGER.error("Revision has no ID associated!")
continue continue
# Find outline item in model # Find outline item in model
item = mdl.getItemByID(ID) item = mdl.getItemByID(ID)
if not item: if not item:
log("* Error: no item whose ID is", ID) LOGGER.debug("* Error: no item whose ID is %s", ID)
LOGGER.error("Could not identify the item matching the revision ID.")
continue continue
# Store revision # Store revision
log("* Appends revision ({}) to {}".format(child.attrib["timestamp"], item.title())) LOGGER.debug("* Appends revision ({}) to {}".format(child.attrib["timestamp"], item.title()))
item.appendRevision(child.attrib["timestamp"], child.attrib["text"]) item.appendRevision(child.attrib["timestamp"], child.attrib["text"])
@ -999,7 +994,7 @@ def getOutlineItem(item, enum):
@return: [QStandardItem] @return: [QStandardItem]
""" """
row = getStandardItemRowFromXMLEnum(item, enum) row = getStandardItemRowFromXMLEnum(item, enum)
log("* Add worldItem:", row[0].text()) LOGGER.debug("* Add worldItem: %s", row[0].text())
for child in item: for child in item:
sub = getOutlineItem(child, enum) sub = getOutlineItem(child, enum)
row[0].appendRow(sub) row[0].appendRow(sub)