53 lines
1.2 KiB
Python
53 lines
1.2 KiB
Python
import json
|
|
from pathlib import Path
|
|
import logging
|
|
|
|
log = logging.getLogger("rc.refstor")
|
|
|
|
|
|
class DiskStoredRefs:
|
|
__file: Path = None
|
|
__refs: dict = {}
|
|
|
|
def __init__(self, file: Path):
|
|
log.debug(f"Initializing disk stored refs: {file.as_posix()}")
|
|
self.__file = file
|
|
self.__refs = {}
|
|
|
|
if self.__file.is_file():
|
|
log.debug(f"Loading from file")
|
|
self.__refs = dict(json.loads(self.__file.read_text()))
|
|
|
|
def __persist(self):
|
|
|
|
self.__file.write_text(json.dumps(sorted(self.__refs.items())))
|
|
|
|
def keys(self):
|
|
return list(self.__refs.keys())
|
|
|
|
def count(self):
|
|
log.debug(f"DiskStoredRefs: {len(self.__refs)} items")
|
|
return len(self.__refs)
|
|
|
|
def __len__(self):
|
|
log.debug(f"DiskStoredRefs: {len(self.__refs)} items")
|
|
return len(self.__refs)
|
|
|
|
def get(self, key):
|
|
log.debug(f"DiskStoredRefs: getting key {key}")
|
|
return self.__refs.get(key)
|
|
|
|
def remove(self, key) -> bool:
|
|
if key not in self.__refs:
|
|
log.debug(f"DiskStoredRefs: {key} not found for deletion")
|
|
return False
|
|
log.debug(f"DiskStoredRefs: Deleting key {key}")
|
|
del self.__refs[key]
|
|
self.__persist()
|
|
return True
|
|
|
|
def update(self, key: str, value: str):
|
|
log.debug(f"DiskStoredRefs: update {key} => {value}")
|
|
self.__refs[key] = value
|
|
self.__persist()
|