publish-meetups/publish_meetups/utils/config.py

86 lines
1.7 KiB
Python
Raw Normal View History

2024-02-13 20:25:47 +00:00
import logging
import toml
import platformdirs
2024-02-13 20:43:29 +00:00
from . import PROGRAM_DATA_DIR, PROGRAM_NAME
2024-02-13 20:25:47 +00:00
logger = logging.getLogger("config")
_config: dict = {
2024-02-14 23:27:52 +00:00
"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": {},
2024-02-13 20:25:47 +00:00
"active_feeds": [
"mastodon",
"twitter",
],
2024-02-14 23:27:52 +00:00
2024-02-15 00:08:45 +00:00
"feed": {
"mastodon": {},
"twitter": {},
"lemmy": {},
},
2024-02-13 20:25:47 +00:00
}
2024-02-13 20:43:29 +00:00
CONFIG_FILE = PROGRAM_DATA_DIR / f"{PROGRAM_NAME}.toml"
2024-02-13 20:25:47 +00:00
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
2024-02-15 00:08:45 +00:00
_parts = __name.split(".")
_field_container = _config
for _part in _parts[:-1]:
_field_container = _field_container.get(_part, {})
return _field_container.get(_parts[-1], default)
2024-02-13 20:25:47 +00:00
def set_field(__name: str, __value, update_dict=False):
global _config
2024-02-15 00:08:45 +00:00
_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]
2024-02-13 20:25:47 +00:00
if update_dict and isinstance(__value, dict) and isinstance(_config.get(__name), dict):
2024-02-15 00:08:45 +00:00
_field_container[_parts[-1]].update(__value)
2024-02-13 20:25:47 +00:00
else:
2024-02-15 00:08:45 +00:00
_field_container[_parts[-1]] = __value
2024-02-13 20:25:47 +00:00
write()
read()