datastore: support custom knodes instead of nemubotstate

This commit is contained in:
nemunaire 2017-08-20 21:17:08 +02:00
commit 350e0f5f59
2 changed files with 24 additions and 6 deletions

View file

@ -32,16 +32,20 @@ class Abstract:
def close(self): def close(self):
return return
def load(self, module): def load(self, module, knodes):
"""Load data for the given module """Load data for the given module
Argument: Argument:
module -- the module name of data to load module -- the module name of data to load
knodes -- the schema to use to load the datas
Return: Return:
The loaded data The loaded data
""" """
if knodes is not None:
return None
return self.new() return self.new()
def save(self, module, data): def save(self, module, data):

View file

@ -83,27 +83,38 @@ class XML(Abstract):
return os.path.join(self.basedir, module + ".xml") return os.path.join(self.basedir, module + ".xml")
def load(self, module): def load(self, module, knodes):
"""Load data for the given module """Load data for the given module
Argument: Argument:
module -- the module name of data to load module -- the module name of data to load
knodes -- the schema to use to load the datas
""" """
data_file = self._get_data_file_path(module) data_file = self._get_data_file_path(module)
if knodes is None:
from nemubot.tools.xmlparser import parse_file
def _true_load(path):
return parse_file(path)
else:
from nemubot.tools.xmlparser import XMLParser
p = XMLParser(knodes)
def _true_load(path):
return p.parse_file(path)
# Try to load original file # Try to load original file
if os.path.isfile(data_file): if os.path.isfile(data_file):
from nemubot.tools.xmlparser import parse_file
try: try:
return parse_file(data_file) return _true_load(data_file)
except xml.parsers.expat.ExpatError: except xml.parsers.expat.ExpatError:
# Try to load from backup # Try to load from backup
for i in range(10): for i in range(10):
path = data_file + "." + str(i) path = data_file + "." + str(i)
if os.path.isfile(path): if os.path.isfile(path):
try: try:
cnt = parse_file(path) cnt = _true_load(path)
logger.warn("Restoring from backup: %s", path) logger.warn("Restoring from backup: %s", path)
@ -112,7 +123,7 @@ class XML(Abstract):
continue continue
# Default case: initialize a new empty datastore # Default case: initialize a new empty datastore
return Abstract.load(self, module) return super().load(module, knodes)
def _rotate(self, path): def _rotate(self, path):
"""Backup given path """Backup given path
@ -143,6 +154,9 @@ class XML(Abstract):
if self.rotate: if self.rotate:
self._rotate(path) self._rotate(path)
if data is None:
return
import tempfile import tempfile
_, tmpath = tempfile.mkstemp() _, tmpath = tempfile.mkstemp()
with open(tmpath, "w") as f: with open(tmpath, "w") as f: