configparser-toml/configparser_toml/__init__.py

78 lines
1.8 KiB
Python

from __future__ import annotations
from pathlib import Path
import toml
import platformdirs
from . shared import ENCODING
"""
I need a config directory, where I can store all config files.
"""
class ConfigItem(dict):
"""
recursive config
"""
def __init__(self, data: dict):
self._data: dict = {}
self._default = data.get("DEFAULT", {})
for key, value in data.items():
self[key] = value
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):
def __init__(self, appname: str, profile: str = None, config_dir: str = None):
self.is_root: bool = is_root
self._config: ConfigItem = ConfigItem({})
self.appname: str = appname
self.config_dir: Path = Path(config_dir or platformdirs.user_config_path(appname=appname))
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"
self.read()
return self.config_file
def read(self):
_raw = {}
with self.config_file.open("r", encoding=ENCODING) as f:
self._config = ConfigItem(toml.load(f))
def write(self):
with self.config_file.open("w", encoding=ENCODING) as f:
toml.dump(self._config, f)
def __setitem__(self, key, value):
self._config.__setitem__(key, value)
def __getitem__(self, key):
return self._config.__getitem__(key)