2023-09-10 14:54:06 +00:00
|
|
|
from typing import Any, Tuple, Union
|
2023-09-10 14:27:09 +00:00
|
|
|
from pathlib import Path
|
2023-04-14 15:01:32 +00:00
|
|
|
import logging
|
2023-04-13 21:45:50 +00:00
|
|
|
|
2023-09-10 14:27:09 +00:00
|
|
|
import toml
|
2023-04-15 15:17:33 +00:00
|
|
|
|
2023-09-10 14:27:09 +00:00
|
|
|
from .attributes.attribute import Attribute, Description, EmptyLine
|
2023-04-14 09:22:47 +00:00
|
|
|
|
2023-04-13 21:45:50 +00:00
|
|
|
|
2023-09-10 14:54:06 +00:00
|
|
|
class ConfigDict(dict):
|
|
|
|
def __init__(self, config_reference: "Config", *args, **kwargs):
|
|
|
|
self.config_reference: Config = config_reference
|
|
|
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def __getattribute__(self, __name: str) -> Any:
|
|
|
|
return super().__getattribute__(__name)
|
|
|
|
|
|
|
|
def __setitem__(self, __key: Any, __value: Any) -> None:
|
|
|
|
attribute: Attribute = self.config_reference.attribute_map[__key]
|
|
|
|
attribute.load_toml({attribute.name: __value})
|
|
|
|
self.config_reference.write()
|
|
|
|
|
|
|
|
return super().__setitem__(__key, attribute.value)
|
|
|
|
|
|
|
|
|
2023-04-14 15:01:32 +00:00
|
|
|
class Config:
|
2023-09-10 14:27:09 +00:00
|
|
|
def __init__(self, componet_list: Tuple[Union[Attribute, Description, EmptyLine]], config_file: Path) -> None:
|
|
|
|
self.config_file: Path = config_file
|
2023-04-14 16:28:33 +00:00
|
|
|
|
2023-09-10 14:27:09 +00:00
|
|
|
self.component_list: Tuple[Union[Attribute, Description, EmptyLine]] = componet_list
|
|
|
|
self.loaded_settings: dict = {}
|
2023-04-15 09:54:17 +00:00
|
|
|
|
2023-09-10 14:54:06 +00:00
|
|
|
self.attribute_map = {}
|
|
|
|
for component in self.component_list:
|
|
|
|
if not isinstance(component, Attribute):
|
|
|
|
continue
|
|
|
|
|
|
|
|
self.attribute_map[component.name] = component
|
|
|
|
self.loaded_settings[component.name] = component.value
|
|
|
|
|
2023-04-14 10:40:52 +00:00
|
|
|
@property
|
2023-09-10 14:27:09 +00:00
|
|
|
def toml_string(self):
|
|
|
|
"\n\n".join(component.toml_string for component in self.component_list)
|
2023-04-14 10:40:52 +00:00
|
|
|
|
2023-09-10 14:27:09 +00:00
|
|
|
def write(self):
|
|
|
|
with self.config_file.open("w") as conf_file:
|
|
|
|
conf_file.write(self.toml_string)
|
2023-04-14 16:28:33 +00:00
|
|
|
|
2023-09-10 14:27:09 +00:00
|
|
|
def read(self):
|
|
|
|
if not self.config_file.is_file():
|
|
|
|
logging.info(f"Config file at '{self.config_file}' doesn't exist => generating")
|
|
|
|
self.write()
|
2023-04-14 16:28:33 +00:00
|
|
|
return
|
2023-09-10 14:27:09 +00:00
|
|
|
|
|
|
|
toml_data = {}
|
|
|
|
with self.config_file.open("r") as conf_file:
|
|
|
|
toml_data = toml.load(conf_file)
|
|
|
|
|
|
|
|
for component in self.component_list:
|
|
|
|
if isinstance(component, Attribute):
|
|
|
|
component.load_toml(toml_data, self.loaded_settings)
|