Coverage for src / lilbee / settings.py: 100%

25 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-03-16 08:27 +0000

1"""Persistent settings stored in config.toml alongside the data directory.""" 

2 

3import tomllib 

4from pathlib import Path 

5 

6 

7def _config_path(data_root: Path) -> Path: 

8 return data_root / "config.toml" 

9 

10 

11def load(data_root: Path) -> dict[str, str]: 

12 """Read all settings from config.toml. Returns {} if file is missing.""" 

13 path = _config_path(data_root) 

14 if not path.exists(): 

15 return {} 

16 with path.open("rb") as f: 

17 return {k: str(v) for k, v in tomllib.load(f).items()} 

18 

19 

20def save(data_root: Path, settings: dict[str, str]) -> None: 

21 """Write settings dict as simple TOML key-value pairs.""" 

22 path = _config_path(data_root) 

23 path.parent.mkdir(parents=True, exist_ok=True) 

24 lines = [f'{k} = "{v}"\n' for k, v in sorted(settings.items())] 

25 path.write_text("".join(lines)) 

26 

27 

28def get(data_root: Path, key: str) -> str | None: 

29 """Look up a single key from config.toml.""" 

30 return load(data_root).get(key) 

31 

32 

33def set_value(data_root: Path, key: str, value: str) -> None: 

34 """Read-modify-write a single key in config.toml.""" 

35 current = load(data_root) 

36 current[key] = value 

37 save(data_root, current) 

38 

39 

40def delete_value(data_root: Path, key: str) -> None: 

41 """Remove a key from config.toml. No-op if key doesn't exist.""" 

42 current = load(data_root) 

43 current.pop(key, None) 

44 save(data_root, current)