duty-board-dog/config_reader.py

46 lines
1.2 KiB
Python
Raw Normal View History

2023-12-13 20:39:25 +01:00
# SPDX-FileCopyrightText: 2023 Egor Guslyancev <electromagneticcyclone@disroot.org>
#
# SPDX-License-Identifier: AGPL-3.0-or-later
"The module reads and checks config."
import configparser
2023-12-18 12:01:00 +01:00
FIELDS = {
"tokens.prod": (str, "" if __debug__ else None, None),
"tokens.devel": (str, None if __debug__ else "", None),
"settings.notify_period": (int, 120, None),
}
2023-12-13 20:39:25 +01:00
CONFIG_FILENAME = "config.ini"
config = configparser.ConfigParser()
config.read(CONFIG_FILENAME)
2023-12-13 20:52:30 +01:00
2023-12-18 12:01:00 +01:00
def check_field(field: str) -> None:
2023-12-13 20:52:30 +01:00
"Checks if the config field does exist and has the correct type."
2023-12-18 12:01:00 +01:00
read(field)
def read(field: str) -> any:
"Reads field and converts the value to the correct type."
2023-12-13 20:52:30 +01:00
a = config
2023-12-18 12:01:00 +01:00
if field not in FIELDS:
raise ValueError(f"Field {field} does not exist.")
t, d, allowed = FIELDS[field]
for i in field.split("."):
2023-12-13 20:52:30 +01:00
a = a[i]
2023-12-18 12:01:00 +01:00
if a is None:
if d is None:
raise ValueError(f"Field {field} does not have value.")
return d
2023-12-13 20:52:30 +01:00
a = t(a)
2023-12-18 12:01:00 +01:00
if allowed is not None:
if a not in allowed:
raise ValueError(f"Field {field} does not have allowed value.")
return a
2023-12-13 20:52:30 +01:00
2023-12-18 12:01:00 +01:00
for f in FIELDS:
check_field(f)