StarfallBot/starfall/config.py

49 lines
1.3 KiB
Python

import os
from shutil import copy
from typing import Any
import tomllib
class Config:
data: dict[str, Any] = dict()
"""Configuration imported from config.toml."""
@classmethod
def create(cls) -> str:
"""Copy config-sample.toml file to config.toml.
Does not alert the user to the modification.
"""
return copy(src="config-sample.toml", dst="config.toml")
@classmethod
def load(cls) -> None:
"""Loads the contents of the config.toml file into the class.
Raises:
FileNotFoundError: If the file does not exist.
"""
if not cls.file_exists():
raise FileNotFoundError("config.toml does not exist")
with open("config.toml", "rb") as f:
cls.data = tomllib.load(f)
@classmethod
def file_exists(cls) -> bool:
"""Whether the config.toml file exists or needs to be created.
Returns:
bool: True if path exists and is a file, False otherwise.
"""
return os.path.exists("config.toml") and os.path.isfile("config.toml")
@classmethod
def get(cls, key: str, default: Any):
"""Get config key, if it exists, or return a default.
Returns:
Any: Result, or default if key does not exist.
"""
return cls.data.get(key, default)