XML datastore: add file rotation for backup purpose
This commit is contained in:
parent
8a7ca25d6f
commit
ab2eb405ca
1 changed files with 35 additions and 3 deletions
|
@ -14,7 +14,9 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import fcntl, os
|
||||
import fcntl
|
||||
import os
|
||||
import xml.parsers.expat
|
||||
|
||||
from nemubot.datastore.abstract import Abstract
|
||||
|
||||
|
@ -23,8 +25,17 @@ class XML(Abstract):
|
|||
|
||||
"""A concrete implementation of a data store that relies on XML files"""
|
||||
|
||||
def __init__(self, basedir):
|
||||
def __init__(self, basedir, rotate=True):
|
||||
"""Initialize the datastore
|
||||
|
||||
Arguments:
|
||||
basedir -- path to directory containing XML files
|
||||
rotate -- auto-backup files?
|
||||
"""
|
||||
|
||||
self.basedir = basedir
|
||||
self.rotate = rotate
|
||||
self.nb_save = 0
|
||||
|
||||
def open(self):
|
||||
"""Lock the directory"""
|
||||
|
@ -83,6 +94,22 @@ class XML(Abstract):
|
|||
else:
|
||||
return Abstract.load(self, module)
|
||||
|
||||
def _rotate(self, path):
|
||||
"""Backup given path
|
||||
|
||||
Argument:
|
||||
path -- location of the file to backup
|
||||
"""
|
||||
|
||||
self.nb_save += 1
|
||||
|
||||
for i in range(10):
|
||||
if self.nb_save % (1 << i) == 0:
|
||||
src = path + "." + str(i-1) if i != 0 else path
|
||||
dst = path + "." + str(i)
|
||||
if os.path.isfile(src):
|
||||
os.rename(src, dst)
|
||||
|
||||
def save(self, module, data):
|
||||
"""Load data for the given module
|
||||
|
||||
|
@ -91,4 +118,9 @@ class XML(Abstract):
|
|||
data -- the new data to save
|
||||
"""
|
||||
|
||||
return data.save(self._get_data_file_path(module))
|
||||
path = self._get_data_file_path(module)
|
||||
|
||||
if self.rotate:
|
||||
self._rotate(path)
|
||||
|
||||
return data.save(path)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue