A Python port of the Invisible Internet Project (I2P)
at main 48 lines 1.6 kB view raw
1"""FileStorage — persist addressbook in hosts.txt format.""" 2 3from __future__ import annotations 4 5import os 6 7from i2p_apps.addressbook.book import AddressbookEntry 8 9 10class FileStorage: 11 """Persist addressbook in hosts.txt format (hostname=destination per line).""" 12 13 def __init__(self, path: str) -> None: 14 self._path = path 15 16 def save(self, entries: dict[str, AddressbookEntry]) -> None: 17 """Write entries to file in hosts.txt format.""" 18 with open(self._path, "w") as f: 19 for _key, entry in sorted(entries.items()): 20 f.write(f"{entry.hostname}={entry.destination}\n") 21 22 def load(self) -> dict[str, AddressbookEntry]: 23 """Load entries from hosts.txt file. Missing file returns empty dict.""" 24 if not os.path.exists(self._path): 25 return {} 26 27 entries: dict[str, AddressbookEntry] = {} 28 with open(self._path, "r") as f: 29 for line in f: 30 line = line.strip() 31 if not line or line.startswith("#"): 32 continue 33 if "=" not in line: 34 continue 35 hostname, destination = line.split("=", 1) 36 hostname = hostname.strip().lower() 37 destination = destination.strip() 38 entries[hostname] = AddressbookEntry( 39 hostname=hostname, 40 destination=destination, 41 source="local", 42 ) 43 return entries 44 45 @property 46 def path(self) -> str: 47 """Return the file path.""" 48 return self._path