latecomers/latecomers/config.py

58 lines
1.3 KiB
Python

# -*- encoding: utf-8 -*-
import logging
import typing as T
from latecomers.helpers import logit
import yaml
logger = logging.getLogger(__name__)
def get_section(obj: T.Dict[T.Text, T.Any], key: T.Text) -> T.Any:
value = obj.get(key)
if value is None:
raise ValueError(f"Missing '{key}' value")
return value
class Config(object):
smtp: T.Dict[T.Text, T.Any] = {}
to: T.List[T.Text] = []
cc: T.List[T.Text] = []
store: T.Optional[T.Text] = None
def __init__(self, path: T.Text) -> None:
self.from_file(path)
@logit(logger)
def from_file(self, path: T.Text) -> None:
"""
Parses the file and validates it.
"""
with open(path) as f:
content = yaml.safe_load(f)
self.to = get_section(content, "to")
if cc := content.get("cc"):
self.cc = cc
smtp = get_section(content, "smtp")
for key in [
"smtp_addr",
"smtp_port",
"smtp_starttls",
"smtp_user",
"smtp_pass",
]:
self.smtp[key] = get_section(smtp, key)
self.smtp["smtp_from"] = smtp.get("smtp_from")
self.store = content.get("store")
def __str__(self) -> T.Text:
return f"Config<smtp={self.smtp},to={self.to}>"