From 88a85411ba073acce0ab3299e120a8afe79ebda7 Mon Sep 17 00:00:00 2001 From: Felix Uhl Date: Tue, 29 Oct 2024 20:26:21 +0100 Subject: [PATCH] disko2: Make Result generic over the value it contains This will be essential for type safety later on. --- disko2 | 12 ++++++++---- lib/result.py | 12 +++++++----- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/disko2 b/disko2 index 2096c6a..9aecbe0 100755 --- a/disko2 +++ b/disko2 @@ -2,7 +2,7 @@ import argparse from pathlib import Path -from typing import Literal +from typing import Any, Literal, Union from lib.logging import LOGGER, DiskoMessage, debug, info from lib.result import DiskoError, DiskoSuccess, DiskoResult, exit_on_error @@ -32,7 +32,9 @@ MODE_DESCRIPTION: dict[Mode, str] = { } -def run_apply(*, mode: str, disko_file: Path | None, flake: str | None) -> DiskoResult: +def run_apply( + *, mode: str, disko_file: Path | None, flake: str | None +) -> DiskoResult[dict[str, Any]]: if flake is None and disko_file is None: return DiskoError([DiskoMessage("ERR_MISSING_ARGUMENTS")], "validate args") if flake is not None and disko_file is not None: @@ -48,11 +50,13 @@ def run_apply(*, mode: str, disko_file: Path | None, flake: str | None) -> Disko ) -def run_generate() -> DiskoResult: +def run_generate() -> DiskoResult[Literal["generate"]]: return DiskoSuccess("generate", "generate config") -def run(args: argparse.Namespace) -> DiskoResult: +def run( + args: argparse.Namespace, +) -> DiskoResult[Literal["generate"] | dict[str, Any]]: if args.verbose == True: LOGGER.setLevel("DEBUG") debug("Enabled debug logging.") diff --git a/lib/result.py b/lib/result.py index c1ffa23..30e3369 100644 --- a/lib/result.py +++ b/lib/result.py @@ -1,12 +1,14 @@ from dataclasses import dataclass -from typing import Literal, Union +from typing import Generic, Literal, TypeVar from lib.logging import DiskoMessage, debug, print_msg +T = TypeVar("T", covariant=True) + @dataclass -class DiskoSuccess: - value: object +class DiskoSuccess(Generic[T]): + value: T context: None | str = None success: Literal[True] = True @@ -18,10 +20,10 @@ class DiskoError: success: Literal[False] = False -DiskoResult = Union[DiskoSuccess, DiskoError] +DiskoResult = DiskoSuccess[T] | DiskoError -def exit_on_error(result: DiskoResult) -> object: +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})