implemented basic functionality

This commit is contained in:
Hellow
2024-02-21 21:31:14 +01:00
parent d147958c7b
commit 5d6060cba0
4 changed files with 60 additions and 4 deletions

View File

@@ -1,3 +1,4 @@
from __future__ import annotations
from pathlib import Path
import toml
@@ -12,16 +13,38 @@ I need a config directory, where I can store all config files.
"""
CONFIG_DIR = Path.home() / ".config" / "configparser_toml"
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:
class Config(ConfigItem):
def __init__(self, appname: str, profile: str = None, config_dir: str = None):
self._config: dict = {}
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)
@@ -31,13 +54,24 @@ class Config:
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):
pass
_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)

View File

@@ -0,0 +1,11 @@
class ConfigParserError(Exception):
"""Base class for exceptions in this module."""
def __init__(self, msg=''):
self.message = msg
Exception.__init__(self, msg)
def __repr__(self):
return self.message
__str__ = __repr__

View File

@@ -0,0 +1 @@
ENCODING = "utf-8"