music-kraken-core/src/music_kraken/utils/config/config.py

38 lines
1.2 KiB
Python
Raw Normal View History

2023-09-10 14:27:09 +00:00
from typing import Tuple, Union
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-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-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-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-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()
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)