2022-07-31 15:33:35 +02:00
|
|
|
from typing import Optional
|
|
|
|
import os
|
2022-08-04 14:44:58 +02:00
|
|
|
import logging
|
|
|
|
log = logging.getLogger("rc.lststor")
|
2022-07-31 15:33:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
class DiskStoredList:
|
|
|
|
__file: Optional[str] = None
|
|
|
|
__items: Optional[list] = None
|
|
|
|
|
|
|
|
def __init__(self, file: str):
|
|
|
|
# file does not have to exist, but parent directory does
|
|
|
|
if not os.path.exists(file):
|
|
|
|
if not os.path.isdir(os.path.dirname(file)):
|
|
|
|
raise NotADirectoryError(f"Parent directory for file {file} does not exist!")
|
|
|
|
|
|
|
|
self.__file = file
|
|
|
|
self.__items = []
|
|
|
|
|
|
|
|
if os.path.exists(file):
|
|
|
|
self._load_from_file()
|
|
|
|
|
|
|
|
def _load_from_file(self):
|
2022-08-04 14:44:58 +02:00
|
|
|
log.debug(f"DiskStoredList: loading")
|
2022-07-31 15:33:35 +02:00
|
|
|
with open(self.__file, 'r') as f:
|
|
|
|
for line in f.readlines():
|
|
|
|
line = line.strip()
|
|
|
|
if len(line):
|
|
|
|
self.__items.append(line)
|
2022-08-04 14:44:58 +02:00
|
|
|
log.debug(f"DiskStoredList: loaded {len(self.__items)}")
|
|
|
|
|
2022-07-31 15:33:35 +02:00
|
|
|
|
|
|
|
def append(self, line: str):
|
|
|
|
with open(self.__file, 'a') as f:
|
2022-08-04 14:44:58 +02:00
|
|
|
log.debug(f"DiskStoredList: append {line}")
|
2022-07-31 15:33:35 +02:00
|
|
|
self.__items.append(line)
|
|
|
|
f.write(f"{line}\n")
|
|
|
|
|
|
|
|
def count(self):
|
|
|
|
return len(self.__items)
|
|
|
|
|
|
|
|
def __contains__(self, line: str) -> bool:
|
2022-08-04 14:44:58 +02:00
|
|
|
log.debug(f"DiskStoredList: contains? {line}")
|
2022-07-31 15:33:35 +02:00
|
|
|
return line in self.__items
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return self.__items.__iter__()
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self.__items)
|