Support a TOML configuration file

The new config file currently only configures the same options that were
already available through environment variables. However I have ideas
for additional features that would be much nicer to support using a
structured configuration format like TOML rather than environment
variables, so config files exist now!

The previous environment variables are still supported and will be used
if you don't have a config file. I plan to keep supporting the MPD_HOST
and MPD_PORT environment variables forever since they're shared with
other MPD clients such as mpc, but I may eventually drop the environment
variables specific to mpd-now-playable in a future release.
This commit is contained in:
Danielle McLean 2024-06-22 18:19:39 +10:00
parent 796e3df87d
commit dc037a0a4b
Signed by: 00dani
GPG key ID: 6854781A0488421C
12 changed files with 305 additions and 33 deletions

View file

@ -0,0 +1,34 @@
from os import environ
from apischema import deserialize
from pytomlpp import load
from xdg_base_dirs import xdg_config_home
from .model import Config
__all__ = "loadConfig"
def loadConfigFromFile() -> Config:
path = xdg_config_home() / "mpd-now-playable" / "config.toml"
data = load(path)
print(f"Loaded your configuration from {path}")
return deserialize(Config, data)
def loadConfigFromEnv() -> Config:
port = int(environ["MPD_PORT"]) if "MPD_PORT" in environ else None
host = environ.get("MPD_HOST")
password = environ.get("MPD_PASSWORD")
cache = environ.get("MPD_NOW_PLAYABLE_CACHE")
if password is None and host is not None and "@" in host:
password, host = host.split("@", maxsplit=1)
data = {"cache": cache, "mpd": {"port": port, "host": host, "password": password}}
return deserialize(Config, data)
def loadConfig() -> Config:
try:
return loadConfigFromFile()
except FileNotFoundError:
return loadConfigFromEnv()