Refactor codebase to by DRY
This commit is contained in:
parent
c925079e8b
commit
83a526c533
13 changed files with 320 additions and 131 deletions
47
ops_bot/config.py
Normal file
47
ops_bot/config.py
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import List, Literal
|
||||
|
||||
from pydantic import BaseSettings
|
||||
|
||||
from ops_bot.matrix import MatrixClientSettings
|
||||
|
||||
|
||||
class RoutingKey(BaseSettings):
|
||||
name: str
|
||||
path_key: str
|
||||
secret_token: str
|
||||
room_id: str
|
||||
hook_type: Literal["gitlab", "pagerduty", "aws-sns"]
|
||||
|
||||
|
||||
class BotSettings(BaseSettings):
|
||||
routing_keys: List[RoutingKey]
|
||||
log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
|
||||
matrix: MatrixClientSettings
|
||||
|
||||
class Config:
|
||||
env_prefix = "BOT_"
|
||||
case_sensitive = False
|
||||
|
||||
def get_rooms(self) -> List[str]:
|
||||
return list(set([key.room_id for key in self.routing_keys]))
|
||||
|
||||
|
||||
def config_file_exists(filename: str) -> bool:
|
||||
return Path(filename).exists()
|
||||
|
||||
|
||||
def load_config(filename: str = "config.json") -> BotSettings:
|
||||
if config_file_exists(filename):
|
||||
bot_settings = BotSettings.parse_file(filename)
|
||||
else:
|
||||
bot_settings = BotSettings(_env_file=".env", _env_file_encoding="utf-8")
|
||||
logging.getLogger().setLevel(bot_settings.log_level)
|
||||
return bot_settings
|
||||
|
||||
|
||||
def save_config(settings: BotSettings, filename: str = "config.json") -> None:
|
||||
with open(filename, "w") as f:
|
||||
f.write(json.dumps(settings.dict(), indent=2))
|
||||
Loading…
Add table
Add a link
Reference in a new issue