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

128 lines
4.8 KiB
Python
Raw Normal View History

2023-04-15 09:54:17 +00:00
from typing import Union, Tuple, Dict, Iterable, List
from datetime import datetime
2023-04-14 15:01:32 +00:00
import logging
import os
2023-04-13 21:45:50 +00:00
2023-04-15 10:35:11 +00:00
from ..exception.config import SettingNotFound, SettingValueError
2023-04-14 15:01:32 +00:00
from ..path_manager import LOCATIONS
from .base_classes import Description, Attribute, Section, EmptyLine, COMMENT_PREFIX
2023-04-14 15:01:32 +00:00
from .audio import AUDIO_SECTION
from .logging import LOGGING_SECTION
2023-04-15 11:01:20 +00:00
from .connection import CONNECTION_SECTION
2023-04-15 15:17:33 +00:00
from .misc import MISC_SECTION
2023-04-15 17:15:27 +00:00
from .paths import PATHS_SECTION
2023-04-15 15:17:33 +00:00
LOGGER = logging.getLogger("config")
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:
def __init__(self):
self.config_elements: Tuple[Union[Description, Attribute, Section], ...] = (
Description("IMPORTANT: If you modify this file, the changes for the actual setting, will be kept as is.\n"
"The changes you make to the comments, will be discarded, next time you run music-kraken. "
"Have fun!"),
Description(f"Latest reset: {datetime.now()}"),
2023-04-14 15:01:32 +00:00
Description("Those are all Settings for the audio codec.\n"
"If you, for some reason wanna fill your drive real quickly, I mean enjoy HIFI music,\n"
"feel free to tinker with the Bitrate or smth. :)"),
AUDIO_SECTION,
2023-04-15 11:01:20 +00:00
Description("Modify how Music-Kraken connects to the internet:"),
CONNECTION_SECTION,
2023-04-15 17:15:27 +00:00
Description("Modify all your paths, except your config file..."),
PATHS_SECTION,
2023-04-14 15:01:32 +00:00
Description("For all your Logging needs.\n"
"If you found a bug, and wan't to report it, please set the Logging level to 0,\n"
"reproduce the bug, and attach the logfile in the bugreport. ^w^"),
LOGGING_SECTION,
2023-04-15 15:17:33 +00:00
Description("If there are stupid settings, they are here."),
MISC_SECTION,
2023-04-14 17:14:58 +00:00
Description("🏳️‍⚧️🏳️‍⚧️ Protect trans youth. 🏳️‍⚧️🏳️‍⚧️\n"),
2023-04-14 15:01:32 +00:00
)
2023-04-14 11:03:48 +00:00
2023-04-15 09:54:17 +00:00
self._length = 0
2023-04-14 17:14:58 +00:00
self._section_list: List[Section] = []
self._name_section_map: Dict[str, Section] = dict()
for element in self.config_elements:
if not isinstance(element, Section):
continue
2023-04-14 17:14:58 +00:00
self._section_list.append(element)
for name in element.name_attribute_map:
if name in self._name_section_map:
raise ValueError(f"Two sections have the same name: "
f"{name}: "
f"{element.__class__.__name__} {self._name_section_map[name].__class__.__name__}")
self._name_section_map[name] = element
2023-04-15 09:54:17 +00:00
self._length += 1
2023-06-15 10:46:01 +00:00
def set_name_to_value(self, name: str, value: str, silent: bool = True):
2023-04-15 10:35:11 +00:00
"""
:raises SettingValueError, SettingNotFound:
:param name:
:param value:
:return:
"""
if name not in self._name_section_map:
2023-06-15 10:46:01 +00:00
if silent:
LOGGER.warning(f"The setting \"{name}\" is either deprecated, or doesn't exist.")
return
2023-04-15 10:35:11 +00:00
raise SettingNotFound(setting_name=name)
2023-04-15 15:17:56 +00:00
LOGGER.debug(f"setting: {name} value: {value}")
2023-04-15 15:17:33 +00:00
2023-04-15 10:35:11 +00:00
self._name_section_map[name].modify_setting(setting_name=name, new_value=value)
2023-04-15 09:54:17 +00:00
def __len__(self):
return self._length
2023-04-14 10:40:52 +00:00
@property
2023-04-14 15:01:32 +00:00
def config_string(self) -> str:
return "\n\n".join(str(element) for element in self.config_elements)
2023-04-14 10:40:52 +00:00
def _parse_conf_line(self, line: str, index: int):
2023-04-15 10:35:11 +00:00
"""
:raises SettingValueError, SettingNotFound:
:param line:
:param index:
:return:
"""
line = line.strip()
if line.startswith(COMMENT_PREFIX):
return
if line == "":
return
if "=" not in line:
2023-04-15 15:17:33 +00:00
"""
TODO
No value error but custom conf error
"""
raise ValueError(f"Couldn't find the '=' in line {index}.")
line_segments = line.split("=")
name = line_segments[0]
value = "=".join(line_segments[1:])
self.set_name_to_value(name, value)
def read_from_config_file(self, path: os.PathLike):
with open(path, "r", encoding=LOCATIONS.FILE_ENCODING) as conf_file:
2023-04-15 15:17:33 +00:00
for section in self._section_list:
section.reset_list_attribute()
for i, line in enumerate(conf_file):
self._parse_conf_line(line, i+1)
2023-04-14 15:01:32 +00:00
def write_to_config_file(self, path: os.PathLike):
with open(path, "w", encoding=LOCATIONS.FILE_ENCODING) as conf_file:
2023-04-14 15:01:32 +00:00
conf_file.write(self.config_string)
2023-04-14 10:40:52 +00:00
2023-04-14 17:14:58 +00:00
def __iter__(self) -> Iterable[Attribute]:
for section in self._section_list:
for name, attribute in section.name_attribute_map.items():
yield attribute