"""FileStorage — persist addressbook in hosts.txt format.""" from __future__ import annotations import os from i2p_apps.addressbook.book import AddressbookEntry class FileStorage: """Persist addressbook in hosts.txt format (hostname=destination per line).""" def __init__(self, path: str) -> None: self._path = path def save(self, entries: dict[str, AddressbookEntry]) -> None: """Write entries to file in hosts.txt format.""" with open(self._path, "w") as f: for _key, entry in sorted(entries.items()): f.write(f"{entry.hostname}={entry.destination}\n") def load(self) -> dict[str, AddressbookEntry]: """Load entries from hosts.txt file. Missing file returns empty dict.""" if not os.path.exists(self._path): return {} entries: dict[str, AddressbookEntry] = {} with open(self._path, "r") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue if "=" not in line: continue hostname, destination = line.split("=", 1) hostname = hostname.strip().lower() destination = destination.strip() entries[hostname] = AddressbookEntry( hostname=hostname, destination=destination, source="local", ) return entries @property def path(self) -> str: """Return the file path.""" return self._path