75 lines
2 KiB
Python
75 lines
2 KiB
Python
"""Load the config for J.A.R.V.I.S."""
|
|
from yaml import load
|
|
|
|
from jarvis.db.models import Config as DBConfig
|
|
|
|
try:
|
|
from yaml import CLoader as Loader
|
|
except ImportError:
|
|
from yaml import Loader
|
|
|
|
|
|
class Config(object):
|
|
"""Config singleton object for J.A.R.V.I.S."""
|
|
|
|
def __new__(cls, *args: list, **kwargs: dict):
|
|
"""Get the singleton config, or creates a new one."""
|
|
it = cls.__dict__.get("it")
|
|
if it is not None:
|
|
return it
|
|
cls.__it__ = it = object.__new__(cls)
|
|
it.init(*args, **kwargs)
|
|
return it
|
|
|
|
def init(
|
|
self,
|
|
token: str,
|
|
client_id: str,
|
|
logo: str,
|
|
mongo: dict,
|
|
urls: dict,
|
|
log_level: str = "WARNING",
|
|
cogs: list = None,
|
|
events: bool = True,
|
|
gitlab_token: str = None,
|
|
max_messages: int = 1000,
|
|
) -> None:
|
|
"""Initialize the config object."""
|
|
self.token = token
|
|
self.client_id = client_id
|
|
self.logo = logo
|
|
self.mongo = mongo
|
|
self.urls = urls
|
|
self.log_level = log_level
|
|
self.cogs = cogs
|
|
self.events = events
|
|
self.max_messages = max_messages
|
|
self.gitlab_token = gitlab_token
|
|
|
|
def get_db_config(self) -> None:
|
|
"""Load the database config objects."""
|
|
config = DBConfig.objects()
|
|
for item in config:
|
|
setattr(self, item.key, item.value)
|
|
|
|
@classmethod
|
|
def from_yaml(cls, y: dict) -> "Config":
|
|
"""Load the yaml config file."""
|
|
instance = cls(**y)
|
|
return instance
|
|
|
|
|
|
def get_config(path: str = "config.yaml") -> Config:
|
|
"""Get the config from the specified yaml file."""
|
|
if Config.__dict__.get("it"):
|
|
return Config()
|
|
with open(path) as f:
|
|
raw = f.read()
|
|
y = load(raw, Loader=Loader)
|
|
return Config.from_yaml(y)
|
|
|
|
|
|
def reload_config() -> None:
|
|
"""Force reload of the config singleton on next call."""
|
|
if "it" in Config.__dict__:
|
|
Config.__dict__.pop("it")
|