2020-06-04 03:12:31 +04:00
|
|
|
"""An implementation of a simple key=value configuration."""
|
|
|
|
|
|
|
|
from os import getenv
|
|
|
|
from os.path import exists, join
|
|
|
|
from platform import system
|
|
|
|
from typing import Union
|
|
|
|
|
|
|
|
__all__ = ["Configuration", "get_configuration_path"]
|
|
|
|
|
|
|
|
|
|
|
|
def get_configuration_path():
|
|
|
|
if system() == "Linux":
|
|
|
|
return getenv("XDG_CONFIG_HOME") or f"{getenv('HOME')}/.config"
|
|
|
|
elif system() == "Windows":
|
|
|
|
return getenv("APPDATA")
|
|
|
|
|
|
|
|
|
2020-06-05 03:51:29 +04:00
|
|
|
DEFAULT_CONFIGURATION = {
|
|
|
|
"default-currency": "SRUB"
|
|
|
|
}
|
|
|
|
DEFAULT_CONFIGURATION_FILE = join(get_configuration_path(), "piggybank.conf")
|
|
|
|
|
|
|
|
|
2020-06-04 03:12:31 +04:00
|
|
|
class Configuration:
|
|
|
|
def __init__(self, configuration_file: str = DEFAULT_CONFIGURATION_FILE,
|
|
|
|
default_configuration: dict = DEFAULT_CONFIGURATION) -> None:
|
|
|
|
self._configuration_file = configuration_file
|
|
|
|
self._configuration = dict()
|
|
|
|
if exists(self._configuration_file):
|
|
|
|
self.load()
|
|
|
|
elif not default_configuration is None:
|
|
|
|
self._configuration = default_configuration
|
|
|
|
self.save()
|
|
|
|
|
|
|
|
def load(self) -> None:
|
|
|
|
for line in open(self._configuration_file, 'r'):
|
2020-06-05 03:51:29 +04:00
|
|
|
key, value = line[:-1].split(" = ")
|
2020-06-04 03:12:31 +04:00
|
|
|
self._configuration[key] = value
|
|
|
|
|
|
|
|
def save(self) -> None:
|
|
|
|
with open(self._configuration_file, 'w') as cf:
|
|
|
|
for key, value in self._configuration.items():
|
|
|
|
cf.write(f"{key} = {value}\n")
|
|
|
|
|
|
|
|
def __getitem__(self, key: str) -> Union[int, str, bool]:
|
|
|
|
return self._configuration[key]
|
|
|
|
|
|
|
|
def __setitem__(self, key: str, value: Union[int, str, bool]) -> None:
|
|
|
|
self._configuration[key] = value
|