78 lines
2.3 KiB
Python
78 lines
2.3 KiB
Python
from pathlib import Path
|
|
import tomllib
|
|
|
|
|
|
class TomlConfig:
|
|
def __init__(self, config_dir: str, config_file: str):
|
|
self.config_path = Path(config_dir).expanduser() / config_file
|
|
if not self.config_path.exists():
|
|
raise FileNotFoundError(f"Config file not found: {self.config_path}")
|
|
self.config = self._load_config()
|
|
|
|
def _load_config(self):
|
|
try:
|
|
with open(self.config_path, "rb") as f:
|
|
return tomllib.load(f)
|
|
except tomllib.TOMLDecodeError as e:
|
|
raise ValueError(
|
|
f"Failed to decode TOML file at {self.config_path}: {e}"
|
|
)
|
|
|
|
def get_value(self, key, section=None):
|
|
if section is None:
|
|
return self.config[key]
|
|
return self.config[section][key]
|
|
|
|
def set_value(self, key, value, section=None):
|
|
if section is None:
|
|
self.config[key] = value
|
|
else:
|
|
self.config[section][key] = value
|
|
self._save_config()
|
|
|
|
def get_section(self, section):
|
|
return self.config[section]
|
|
|
|
def get_sections(self):
|
|
return list(self.config.keys())
|
|
|
|
def get_keys_in_section(self, section):
|
|
if section not in self.config:
|
|
return []
|
|
else:
|
|
keys = list(self.config[section].keys())
|
|
return keys
|
|
|
|
def get_section_for_key(self, key):
|
|
for section, keys in self.config.items():
|
|
if key in keys:
|
|
return section
|
|
return None
|
|
|
|
def global_search(self, key_to_find):
|
|
"""
|
|
Recursively searches for a specific key in the TOML configuration,
|
|
regardless of its section.
|
|
:param key_to_find: The key to search for.
|
|
:return: the value of the key if found, or None if the key does not exist.
|
|
"""
|
|
|
|
def recursive_search(d):
|
|
if isinstance(d, dict):
|
|
for key, value in d.items():
|
|
if key == key_to_find:
|
|
return value
|
|
if isinstance(value, dict):
|
|
result = recursive_search(value)
|
|
if result is not None:
|
|
return result
|
|
return None
|
|
|
|
return recursive_search(self.config)
|
|
|
|
def get_all(self):
|
|
return self.config
|
|
|
|
def dump(self):
|
|
print(self.config)
|