diff options
Diffstat (limited to 'muck/pers.py')
-rw-r--r-- | muck/pers.py | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/muck/pers.py b/muck/pers.py new file mode 100644 index 0000000..aa4f4c1 --- /dev/null +++ b/muck/pers.py @@ -0,0 +1,55 @@ +# Copyright (C) 2018 Lars Wirzenius +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# 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 json +import os + +import muck + + +class PersistentStore: + + def __init__(self, dirname): + self._dirname = dirname + self._log = ChangeLogWriter(self._changelog_filename()) + + def _changelog_filename(self): + return os.path.join(self._dirname, 'changelog') + + def append_change(self, chg): + self._log.append(chg) + + def load_memory_store(self): + ms = muck.MemoryStore() + for chg in self._changelog_reader(): + ms.change(chg) + return ms + + def _changelog_reader(self): + with open(self._changelog_filename()) as f: + for line in f: + entry = json.loads(line.strip()) + yield muck.create_change_from_log_entry(entry) + + +class ChangeLogWriter: + + def __init__(self, filename): + mode = os.O_WRONLY | os.O_APPEND | os.O_CREAT + self._fd = os.open(filename, mode, 0o666) + + def append(self, chg): + line = json.dumps(chg.as_dict()) + os.write(self._fd, line.encode('UTF-8')) |