disko2: Make messages type-safe and modular

Using untyped dicts was not a safe way to pass arguments to error
message rendering. Also, having one giant match statement wouldn't scale
well. Using function pointers and kwargs, mypy can now properly check
whether all required arguments are passed to DiskoMessage().

As a bonus, it's now easy to use the "Go to definition" LSP command for
error codes, which wasn't possible before.
This commit is contained in:
Felix Uhl committed 2024-11-03 22:35:06 +01:00
1 parent 4db452e40a
commit a6944c6bea
11 files changed
+242 -201

No files matched your search

+10 -7
View File
@@ -1,9 +1,12 @@
from dataclasses import dataclass
from typing import Any, Generic, Literal, TypeVar
from typing import Any, Generic, Literal, ParamSpec, TypeVar
from .logging import DiskoMessage, debug, print_msg, MessageCode
from disko_lib.messages.bugs import bug_success_without_context
from .logging import DiskoMessage, debug, MessageFactory
T = TypeVar("T", covariant=True)
P = ParamSpec("P")
@dataclass
@@ -15,15 +18,15 @@ class DiskoSuccess(Generic[T]):
@dataclass
class DiskoError:
messages: list[DiskoMessage]
messages: list[DiskoMessage[Any]]
context: str
success: Literal[False] = False
@classmethod
def single_message(
cls, code: MessageCode, details: dict[str, Any], context: str
cls, factory: MessageFactory[P], context: str, *_: P.args, **details: P.kwargs
) -> "DiskoError":
return cls([DiskoMessage(code, details)], context)
return cls([DiskoMessage(factory, **details)], context)
DiskoResult = DiskoSuccess[T] | DiskoError
@@ -32,13 +35,13 @@ DiskoResult = DiskoSuccess[T] | DiskoError
def exit_on_error(result: DiskoResult[T]) -> T:
if isinstance(result, DiskoSuccess):
if result.context is None:
print_msg("BUG_SUCCESS_WITHOUT_CONTEXT", {"value": result.value})
DiskoMessage(bug_success_without_context, value=result.value).print()
else:
debug(f"Success in '{result.context}'")
debug(f"Returned value: {result.value}")
return result.value
for message in result.messages:
print_msg(message.code, message.details)
message.print()
exit(1)