2024-02-21 20:31:14 +00:00
|
|
|
from __future__ import annotations
|
2024-02-17 00:04:46 +00:00
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
import toml
|
|
|
|
import platformdirs
|
|
|
|
|
|
|
|
from . shared import ENCODING
|
|
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
I need a config directory, where I can store all config files.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2024-02-21 20:31:14 +00:00
|
|
|
class ConfigItem(dict):
|
|
|
|
"""
|
|
|
|
recursive config
|
|
|
|
"""
|
|
|
|
def __init__(self, data: dict):
|
|
|
|
self._data: dict = {}
|
2024-02-17 00:04:46 +00:00
|
|
|
|
2024-02-21 20:31:14 +00:00
|
|
|
self._default = data.get("DEFAULT", {})
|
|
|
|
|
|
|
|
for key, value in data.items():
|
|
|
|
self[key] = value
|
2024-02-17 00:04:46 +00:00
|
|
|
|
2024-02-21 20:31:14 +00:00
|
|
|
def __missing__(self, key):
|
|
|
|
return self._default.get(key, None)
|
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
|
|
|
if isinstance(value, dict):
|
|
|
|
self._data[key] = ConfigItem(value)
|
|
|
|
else:
|
|
|
|
self._data[key] = value
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Config(ConfigItem):
|
2024-02-17 00:04:46 +00:00
|
|
|
def __init__(self, appname: str, profile: str = None, config_dir: str = None):
|
2024-02-21 20:31:14 +00:00
|
|
|
self.is_root: bool = is_root
|
|
|
|
self._config: ConfigItem = ConfigItem({})
|
2024-02-17 00:04:46 +00:00
|
|
|
|
|
|
|
self.appname: str = appname
|
|
|
|
self.config_dir: Path = Path(config_dir or platformdirs.user_config_path(appname=appname))
|
|
|
|
|
2024-02-21 20:31:14 +00:00
|
|
|
|
2024-02-17 00:04:46 +00:00
|
|
|
self.config_file: Path = self.load_profile(profile)
|
|
|
|
|
|
|
|
|
|
|
|
def load_profile(self, profile: str = None) -> Path:
|
|
|
|
profile = profile if profile is not None else self.appname
|
|
|
|
|
|
|
|
self.config_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
self.config_file = self.config_dir / f"{profile}.toml"
|
2024-02-21 20:31:14 +00:00
|
|
|
|
|
|
|
self.read()
|
|
|
|
|
2024-02-17 00:04:46 +00:00
|
|
|
return self.config_file
|
|
|
|
|
|
|
|
|
|
|
|
def read(self):
|
2024-02-21 20:31:14 +00:00
|
|
|
_raw = {}
|
|
|
|
with self.config_file.open("r", encoding=ENCODING) as f:
|
|
|
|
self._config = ConfigItem(toml.load(f))
|
2024-02-17 00:04:46 +00:00
|
|
|
|
|
|
|
|
|
|
|
def write(self):
|
|
|
|
with self.config_file.open("w", encoding=ENCODING) as f:
|
|
|
|
toml.dump(self._config, f)
|
2024-02-21 20:31:14 +00:00
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
|
|
|
self._config.__setitem__(key, value)
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
return self._config.__getitem__(key)
|