publish-meetups/publish_meetups/utils/config.py

86 lines
1.7 KiB
Python

import logging
import toml
import platformdirs
from . import PROGRAM_DATA_DIR, PROGRAM_NAME
logger = logging.getLogger("config")
_config: dict = {
"ics_url": "",
"locale": "en",
"date_format": "%Y-%m-%d %H:%M:%S",
"time_format": "%H:%M",
"time_format_full_hour": "%H",
"weekday_translations": {},
"months_translations": {},
"active_feeds": [
"mastodon",
"twitter",
],
"feed": {
"mastodon": {},
"twitter": {},
"lemmy": {},
},
}
CONFIG_FILE = PROGRAM_DATA_DIR / f"{PROGRAM_NAME}.toml"
logger.info(f"Config file: {CONFIG_FILE}")
def read():
global _config, CONFIG_FILE
if CONFIG_FILE.exists():
with CONFIG_FILE.open("r", encoding="utf-8") as f:
_config.update(toml.load(f))
def write():
global _config, CONFIG_FILE
with CONFIG_FILE.open("w", encoding="utf-8") as f:
toml.dump(_config, f)
def get_field(__name: str, default=None):
global _config
_parts = __name.split(".")
_field_container = _config
for _part in _parts[:-1]:
_field_container = _field_container.get(_part, {})
return _field_container.get(_parts[-1], default)
def set_field(__name: str, __value, update_dict=False):
global _config
_parts = __name.split(".")
_field_container = _config
for _part in _parts[:-1]:
if _part not in _field_container:
_field_container[_part] = {}
_field_container = _field_container[_part]
if update_dict and isinstance(__value, dict) and isinstance(_config.get(__name), dict):
_field_container[_parts[-1]].update(__value)
else:
_field_container[_parts[-1]] = __value
write()
read()