Initial commit
This commit is contained in:
53
config.py
Normal file
53
config.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Module for generating and reading config"""
|
||||
|
||||
import json
|
||||
import aiofiles
|
||||
import os
|
||||
import traceback
|
||||
|
||||
from datatypes import AppConfig
|
||||
import util
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"matrix_homeserver": "https://matrix.domain.net",
|
||||
"matrix_user": "short_username",
|
||||
"store_dir": "session_storage"
|
||||
}
|
||||
|
||||
|
||||
|
||||
#
|
||||
# PRIVATE
|
||||
#
|
||||
async def write_default_config(path: str) -> None:
|
||||
try:
|
||||
async with aiofiles.open(path, "w") as f:
|
||||
await f.write(json.dumps(DEFAULT_CONFIG, indent=4))
|
||||
util.log_info(f"Default config is saved to `{path}`")
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
|
||||
#
|
||||
# PUBLIC
|
||||
#
|
||||
async def load_config(path: str = "config.json") -> AppConfig | None:
|
||||
"""Load config from specified path. Creates default config if it does not exist (but still returns None)."""
|
||||
# no file
|
||||
if not os.path.isfile(path):
|
||||
await write_default_config(path)
|
||||
return None
|
||||
# open and read
|
||||
try:
|
||||
async with aiofiles.open(path, "r") as f:
|
||||
j = json.loads((await f.read()).strip())
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return None
|
||||
# parse
|
||||
try:
|
||||
cfg = AppConfig(**j)
|
||||
return cfg
|
||||
except:
|
||||
return None
|
||||
Reference in New Issue
Block a user