Significantly overhaul configuration management

Everything now uses bog-standard Python dataclasses, with Pydantic
providing validation and type conversion through separate classes using
its type adapter feature. It's also possible to define your classes
using Pydantic's own model type directly, making the type adapter
unnecessary, but I didn't want to do things that way because no actual
validation is needed when constructing a Song instance for example.
Having Pydantic do its thing only on-demand was preferable.

I tried a number of validation libraries before settling on Pydantic for
this. It's not the fastest option out there (msgspec is I think), but it
makes adding support for third-party types like yarl.URL really easy, it
generates a nice clean JSON Schema which is easy enough to adjust to my
requirements through its GenerateJsonSchema hooks, and raw speed isn't
all that important anyway since this is a single-user desktop program
that reads its configuration file once on startup.

Also, MessagePack is now mandatory if you're caching to an external
service. It just didn't make a whole lot sense to explicitly install
mpd-now-playable's Redis or Memcached support and then use pickling with
them.

With all this fussing around done, I'm probably finally ready to
actually use that configuration file to configure new features! Yay!
This commit is contained in:
Danielle McLean 2024-07-01 00:10:17 +10:00
parent 3b7ddfa718
commit 27d8c37139
Signed by: 00dani
GPG key ID: 6854781A0488421C
18 changed files with 355 additions and 169 deletions

View file

@ -1,46 +1,5 @@
from json import dump
from pathlib import Path
from pprint import pp
from shutil import get_terminal_size
from typing import Any, Mapping
from apischema import schema, settings
from apischema.json_schema import JsonSchemaVersion, deserialization_schema
from apischema.schemas import Schema
from class_doc import extract_docs_from_cls_obj
from ..tools.schema.generate import write
from .model import Config
def field_base_schema(tp: type, name: str, alias: str) -> Schema | None:
desc_lines = extract_docs_from_cls_obj(tp).get(name, [])
if desc_lines:
print((tp, name, alias))
return schema(description=" ".join(desc_lines))
return None
settings.base_schema.field = field_base_schema
def generate() -> Mapping[str, Any]:
return deserialization_schema(
Config,
version=JsonSchemaVersion.DRAFT_7,
)
def write() -> None:
schema = dict(generate())
schema["$id"] = Config.schema.human_repr()
schema_file = Path(__file__).parent / Config.schema.name
print(f"Writing this schema to {schema_file}")
pp(schema, sort_dicts=True, width=get_terminal_size().columns)
with open(schema_file, "w") as fp:
dump(schema, fp, indent="\t", sort_keys=True)
fp.write("\n")
if __name__ == "__main__":
write()
write(Config)