50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
from os import environ, makedirs, path
|
|
import yaml
|
|
|
|
import logging
|
|
log = logging.getLogger(__name__)
|
|
class ConfigFile:
|
|
"""
|
|
Class managing a yaml config file.
|
|
The file is loaded on creation and can be saved with .save().
|
|
|
|
You may initialize an instance with empty string as filepath,
|
|
in this case no file will not be loaded or saved.
|
|
"""
|
|
def __init__(self, filepath: str, init_values = None):
|
|
self.values = {}
|
|
if init_values:
|
|
self.values = init_values
|
|
self.filepath = filepath
|
|
if path.isfile(self.filepath):
|
|
log.debug(f"[{self.filepath}] loading from file")
|
|
with open(self.filepath, "r") as file:
|
|
self.values |= yaml.safe_load(file)
|
|
|
|
def save(self):
|
|
if not self.filepath: return
|
|
directory = path.dirname(self.filepath)
|
|
if not path.isdir(directory):
|
|
makedirs(directory)
|
|
log.debug(f"[{self.filepath}] saving to file")
|
|
with open(self.filepath, "w") as file:
|
|
yaml.dump(self.values, file)
|
|
|
|
def get_or(self, name: str, default):
|
|
if name in self.values: return self.values[name]
|
|
return default
|
|
|
|
def get(self, name: str):
|
|
if name in self.values: return self.values[name]
|
|
raise KeyError(f"Key '{name}' not found in config file '{self.filepath}'")
|
|
|
|
def set(self, name: str, value):
|
|
log.debug(f"[{self.filepath}] set {name} = {value}")
|
|
self.values[name] = value
|
|
|
|
def get_values(self):
|
|
return self.values.copy()
|
|
|
|
def set_values(self, values):
|
|
log.debug(f"[{self.filepath}] set values = {values}")
|
|
self.values = values |