From a6944c6bea4e1830cf1f0901d3ba5c35b4305bd2 Mon Sep 17 00:00:00 2001 From: Felix Uhl Date: Sun, 3 Nov 2024 22:13:02 +0100 Subject: [PATCH] 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. --- src/disko/cli.py | 8 +- src/disko_lib/eval_config.py | 17 ++- src/disko_lib/logging.py | 200 +++++------------------------ src/disko_lib/messages/__init__.py | 3 + src/disko_lib/messages/bugs.py | 30 +++++ src/disko_lib/messages/colors.py | 14 ++ src/disko_lib/messages/msgs.py | 117 +++++++++++++++++ src/disko_lib/result.py | 17 ++- src/disko_lib/run_cmd.py | 12 +- src/disko_lib/types/disk.py | 20 +-- tests/disko_lib/test_types_disk.py | 5 +- 11 files changed, 242 insertions(+), 201 deletions(-) create mode 100644 src/disko_lib/messages/__init__.py create mode 100644 src/disko_lib/messages/bugs.py create mode 100644 src/disko_lib/messages/colors.py create mode 100644 src/disko_lib/messages/msgs.py diff --git a/src/disko/cli.py b/src/disko/cli.py index 3adc8d5..3639894 100644 --- a/src/disko/cli.py +++ b/src/disko/cli.py @@ -8,6 +8,8 @@ from typing import Any, Literal, assert_never from disko_lib.ansi import disko_dev_ansi from disko_lib.eval_config import eval_disko_file, eval_flake from disko_lib.logging import LOGGER, debug, info +from disko_lib.messages import err_missing_arguments +from disko_lib.messages.msgs import err_missing_mode, err_too_many_arguments from disko_lib.result import DiskoError, DiskoSuccess, DiskoResult, exit_on_error from disko_lib.types.disk import generate_config from disko_lib.types.device import disko_dev_lsblk @@ -49,13 +51,13 @@ def run_apply( ) -> DiskoResult[dict[str, Any]]: # match would be nicer, but mypy doesn't understand type narrowing in tuples if not disko_file and not flake: - return DiskoError.single_message("ERR_MISSING_ARGUMENTS", {}, "validate args") + return DiskoError.single_message(err_missing_arguments, "validate args") if not disko_file and flake: return eval_flake(flake) if disko_file and not flake: return eval_disko_file(Path(disko_file)) - return DiskoError.single_message("ERR_TOO_MANY_ARGUMENTS", {}, "validate args") + return DiskoError.single_message(err_too_many_arguments, "validate args") def run_generate() -> DiskoResult[dict[str, Any]]: @@ -82,7 +84,7 @@ def run( match args.mode: case None: return DiskoError.single_message( - "ERR_MISSING_MODE", {"valid_modes": ALL_MODES}, "select mode" + err_missing_mode, "select mode", valid_modes=[str(m) for m in ALL_MODES] ) case "generate": return run_generate() diff --git a/src/disko_lib/eval_config.py b/src/disko_lib/eval_config.py index b3a81fe..dbfaae7 100644 --- a/src/disko_lib/eval_config.py +++ b/src/disko_lib/eval_config.py @@ -3,6 +3,12 @@ from pathlib import Path import re from typing import Any +from disko_lib.messages.msgs import ( + err_eval_config_failed, + err_file_not_found, + err_flake_uri_no_attr, +) + from .run_cmd import run from .result import DiskoError, DiskoResult, DiskoSuccess @@ -32,9 +38,10 @@ def eval_config(args: dict[str, str]) -> DiskoResult[dict[str, Any]]: if isinstance(result, DiskoError): return DiskoError.single_message( - "ERR_EVAL_CONFIG_FAILED", - {"args": args, "stderr": result.messages[0].details["stderr"]}, + err_eval_config_failed, "evaluate disko configuration", + args=args, + stderr=result.messages[0].details["stderr"], ) return result @@ -47,9 +54,9 @@ def eval_disko_file(config_file: Path) -> DiskoResult[dict[str, Any]]: if not abs_path.exists(): return DiskoError.single_message( - "ERR_FILE_NOT_FOUND", - {"path": abs_path}, + err_file_not_found, "evaluate disko_file", + path=abs_path, ) return eval_config({"diskoFile": str(abs_path)}) @@ -69,7 +76,7 @@ def eval_flake(flake_uri: str) -> DiskoResult[dict[str, Any]]: if not flake_attr: return DiskoError.single_message( - "ERR_FLAKE_URI_NO_ATTR", {"flake_uri": flake_uri}, "evaluate flake" + err_flake_uri_no_attr, "evaluate flake", flake_uri=flake_uri ) flake_path = Path(flake) diff --git a/src/disko_lib/logging.py b/src/disko_lib/logging.py index 3609f59..caeb46e 100644 --- a/src/disko_lib/logging.py +++ b/src/disko_lib/logging.py @@ -1,190 +1,55 @@ # Logging functionality and global logging configuration -from dataclasses import dataclass, field -import json +from dataclasses import dataclass import logging import re -from typing import Any, Literal, assert_never +from typing import ( + Any, + Callable, + Generic, + Literal, + ParamSpec, + TypeAlias, +) from .ansi import Colors +from .messages.colors import RESET logging.basicConfig(format="%(message)s", level=logging.INFO) LOGGER = logging.getLogger("disko_logger") -# Color definitions. Note: Sort them alphabetically when adding new ones! -COMMAND = Colors.CYAN_ITALIC # Commands that were run or can be run -EM = Colors.WHITE_ITALIC # Emphasized text -EM_WARN = Colors.YELLOW_ITALIC # Emphasized text that is a warning -FILE = Colors.BLUE # File paths -FLAG = Colors.GREEN # Command line flags (like --version or -f) -INVALID = Colors.RED # Invalid values -PLACEHOLDER = Colors.MAGENTA_ITALIC # Values that need to be replaced -VALUE = Colors.GREEN # Values that are allowed - -RESET = Colors.RESET # Shortcut to reset the color - - @dataclass class ReadableMessage: type: Literal["bug", "error", "warning", "info", "help", "debug"] msg: str -# Codes for every single message that disko can print -# Note: Sort them alphabetically when adding new ones! -MessageCode = Literal[ - "BUG_SUCCESS_WITHOUT_CONTEXT", - "ERR_COMMAND_FAILED", - "ERR_EVAL_CONFIG_FAILED", - "ERR_FILE_NOT_FOUND", - "ERR_FLAKE_URI_NO_ATTR", - "ERR_MISSING_ARGUMENTS", - "ERR_MISSING_MODE", - "ERR_TOO_MANY_ARGUMENTS", - "ERR_UNSUPPORTED_PTTYPE", - "WARN_GENERATE_PARTIAL_FAILURE", -] +P = ParamSpec("P") + +MessageFactory: TypeAlias = Callable[P, ReadableMessage | list[ReadableMessage]] @dataclass -class DiskoMessage: - code: MessageCode - details: dict[str, Any] = field(default_factory=dict) +class DiskoMessage(Generic[P]): + factory: MessageFactory[P] + # Can't infer a TypedDict from a ParamSpec yet (mypy 1.10.1, python 3.12.5) + # This is only safe to use because the type of __init__ ensures that the + # keys in details are the same as the keys in the factory kwargs + details: dict[str, Any] + def __init__(self, factory: MessageFactory[P], **details: P.kwargs) -> None: + self.factory = factory + self.details = details -ERR_ARGUMENTS_HELP_TXT = f"Provide either {PLACEHOLDER}disko_file{RESET} as the second argument or \ -{FLAG}--flake{RESET}/{FLAG}-f{RESET} {PLACEHOLDER}flake-uri{RESET}." + def to_readable(self) -> list[ReadableMessage]: + result = self.factory(**self.details) + if isinstance(result, list): + return result + return [result] - -def bug_help_message(error_code: MessageCode) -> ReadableMessage: - return ReadableMessage( - "help", - f""" - Please report this bug! - First, check if has already been reported at - https://github.com/nix-community/disko/issues?q=is%3Aissue+{error_code} - If not, open a new issue at - https://github.com/nix-community/disko/issues/new?title={error_code} - and include the full logs printed above! - """, - ) - - -def to_readable(message: DiskoMessage) -> list[ReadableMessage]: - match message.code: - case "BUG_SUCCESS_WITHOUT_CONTEXT": - return [ - ReadableMessage( - "bug", - f""" - Success message without context! - Returned value: - {message.details['value']} - """, - ), - bug_help_message(message.code), - ] - case "ERR_COMMAND_FAILED": - return [ - ReadableMessage( - "error", - f""" - Command failed: {COMMAND}{message.details['command']}{COMMAND} - Exit code: {INVALID}{message.details['exit_code']}{RESET} - stderr: {message.details['stderr']} - """, - ) - ] - case "ERR_EVAL_CONFIG_FAILED": - return [ - ReadableMessage( - "error", - f""" - Failed to evaluate disko config with args {INVALID}{message.details['args']}{RESET}! - Stderr from {COMMAND}nix eval{RESET}:\n{message.details['stderr']} - """, - ) - ] - case "ERR_FILE_NOT_FOUND": - return [ - ReadableMessage( - "error", f"File not found: {FILE}{message.details['path']}{RESET}" - ) - ] - case "ERR_FLAKE_URI_NO_ATTR": - return [ - ReadableMessage( - "error", - f"Flake URI {INVALID}{message.details['flake_uri']}{RESET} has no attribute.", - ), - ReadableMessage( - "help", - f"Append an attribute like {VALUE}#{PLACEHOLDER}foo{RESET} to the flake URI.", - ), - ] - case "ERR_MISSING_ARGUMENTS": - return [ - ReadableMessage( - "error", - f"Missing arguments!", - ), - ReadableMessage("help", ERR_ARGUMENTS_HELP_TXT), - ] - case "ERR_TOO_MANY_ARGUMENTS": - return [ - ReadableMessage( - "error", - f"Too many arguments!", - ), - ReadableMessage("help", ERR_ARGUMENTS_HELP_TXT), - ] - case "ERR_MISSING_MODE": - modes_list = "\n".join( - [f" - {VALUE}{m}{RESET}" for m in message.details["valid_modes"]] - ) - return [ - ReadableMessage("error", "Missing mode!"), - ReadableMessage("help", "Allowed modes are:\n" + modes_list), - ] - case "ERR_UNSUPPORTED_PTTYPE": - return [ - ReadableMessage( - "error", - f"Device {FILE}{message.details['device']}{RESET} has unsupported partition type {INVALID}{message.details['pttype']}{RESET}!", - ), - ] - case "WARN_GENERATE_PARTIAL_FAILURE": - return [ - ReadableMessage( - "info", - f""" - Successfully generated config for {EM}some{RESET} devices. - Errors are printed above. The generated partial config is: - {json.dumps(message.details["partial_config"], indent=2)} - """, - ), - ReadableMessage( - "warning", - f""" - Successfully generated config for {EM}some{RESET} devices, {EM_WARN}but not all{RESET}! - Failed devices: {", ".join(f"{INVALID}{d}{RESET}" for d in message.details["failed_devices"])} - Successful devices: {", ".join(f"{VALUE}{d}{RESET}" for d in message.details["successful_devices"])} - """, - ), - ReadableMessage( - "help", - f""" - The {INVALID}ERROR{RESET} messages are printed {EM}above the generated config{RESET}. - Take a look at them and see if you can fix or safely ignore them. - If you can't, but you need a solution now, you can try to use the generated config, - but there is {EM_WARN}no guarantee{RESET} that it will work! - """, - ), - ] - - # We could also remove these two lines, but assert_never emits a better error message - case _ as c: - assert_never(c) + def print(self) -> None: + for msg in self.to_readable(): + render_message(msg) # Dedent lines based on the indent of the first line until a non-indented line is hit. @@ -273,11 +138,6 @@ def render_message(message: ReadableMessage) -> None: log_msg(f"{decor_color}╰───────────{RESET}") # Exactly as long as the heading -def print_msg(code: MessageCode, details: dict[str, Any]) -> None: - for msg in to_readable(DiskoMessage(code, details)): - render_message(msg) - - def debug(msg: str) -> None: # Check debug level immediately to avoid unnecessary formatting if LOGGER.isEnabledFor(logging.DEBUG): diff --git a/src/disko_lib/messages/__init__.py b/src/disko_lib/messages/__init__.py new file mode 100644 index 0000000..f62e401 --- /dev/null +++ b/src/disko_lib/messages/__init__.py @@ -0,0 +1,3 @@ +# Re-export all messages +from .msgs import * # noqa +from .bugs import * # noqa diff --git a/src/disko_lib/messages/bugs.py b/src/disko_lib/messages/bugs.py new file mode 100644 index 0000000..982810e --- /dev/null +++ b/src/disko_lib/messages/bugs.py @@ -0,0 +1,30 @@ +from typing import Any +from disko_lib.logging import ReadableMessage + + +def __bug_help_message(error_code: str) -> ReadableMessage: + return ReadableMessage( + "help", + f""" + Please report this bug! + First, check if has already been reported at + https://github.com/nix-community/disko/issues?q=is%3Aissue+{error_code} + If not, open a new issue at + https://github.com/nix-community/disko/issues/new?title={error_code} + and include the full logs printed above! + """, + ) + + +def bug_success_without_context(*, value: Any) -> list[ReadableMessage]: + return [ + ReadableMessage( + "bug", + f""" + Success message without context! + Returned value: + {value} + """, + ), + __bug_help_message("bug_success_without_context"), + ] diff --git a/src/disko_lib/messages/colors.py b/src/disko_lib/messages/colors.py new file mode 100644 index 0000000..e8ea8b7 --- /dev/null +++ b/src/disko_lib/messages/colors.py @@ -0,0 +1,14 @@ +from disko_lib.ansi import Colors + + +# Color definitions. Note: Sort them alphabetically when adding new ones! +COMMAND = Colors.CYAN_ITALIC # Commands that were run or can be run +EM = Colors.WHITE_ITALIC # Emphasized text +EM_WARN = Colors.YELLOW_ITALIC # Emphasized text that is a warning +FILE = Colors.BLUE # File paths +FLAG = Colors.GREEN # Command line flags (like --version or -f) +INVALID = Colors.RED # Invalid values +PLACEHOLDER = Colors.MAGENTA_ITALIC # Values that need to be replaced +VALUE = Colors.GREEN # Values that are allowed + +RESET = Colors.RESET # Shortcut to reset the color diff --git a/src/disko_lib/messages/msgs.py b/src/disko_lib/messages/msgs.py new file mode 100644 index 0000000..1f6c273 --- /dev/null +++ b/src/disko_lib/messages/msgs.py @@ -0,0 +1,117 @@ +import json +from pathlib import Path +from typing import Any +from disko_lib.logging import ReadableMessage +from .colors import * + +ERR_ARGUMENTS_HELP_TXT = f"Provide either {PLACEHOLDER}disko_file{RESET} as the second argument or \ +{FLAG}--flake{RESET}/{FLAG}-f{RESET} {PLACEHOLDER}flake-uri{RESET}." + + +def err_command_failed(*, command: str, exit_code: int, stderr: str) -> ReadableMessage: + return ReadableMessage( + "error", + f""" + Command failed: {COMMAND}{command}{COMMAND} + Exit code: {INVALID}{exit_code}{RESET} + stderr: {stderr} + """, + ) + + +def err_eval_config_failed(*, args: dict[str, Any], stderr: str) -> ReadableMessage: + + return ReadableMessage( + "error", + f""" + Failed to evaluate disko config with args {INVALID}{args}{RESET}! + Stderr from {COMMAND}nix eval{RESET}:\n{stderr} + """, + ) + + +def err_file_not_found(*, path: Path) -> ReadableMessage: + return ReadableMessage("error", f"File not found: {FILE}{path}{RESET}") + + +def err_flake_uri_no_attr(*, flake_uri: str) -> list[ReadableMessage]: + return [ + ReadableMessage( + "error", + f"Flake URI {INVALID}{flake_uri}{RESET} has no attribute.", + ), + ReadableMessage( + "help", + f"Append an attribute like {VALUE}#{PLACEHOLDER}foo{RESET} to the flake URI.", + ), + ] + + +def err_missing_arguments() -> list[ReadableMessage]: + return [ + ReadableMessage( + "error", + f"Missing arguments!", + ), + ReadableMessage("help", ERR_ARGUMENTS_HELP_TXT), + ] + + +def err_too_many_arguments() -> list[ReadableMessage]: + return [ + ReadableMessage( + "error", + f"Too many arguments!", + ), + ReadableMessage("help", ERR_ARGUMENTS_HELP_TXT), + ] + + +def err_missing_mode(*, valid_modes: list[str]) -> list[ReadableMessage]: + modes_list = "\n".join([f" - {VALUE}{m}{RESET}" for m in valid_modes]) + return [ + ReadableMessage("error", "Missing mode!"), + ReadableMessage("help", "Allowed modes are:\n" + modes_list), + ] + + +def err_unsupported_pttype(*, device: Path, pttype: str) -> ReadableMessage: + return ReadableMessage( + "error", + f"Device {FILE}{device}{RESET} has unsupported partition type {INVALID}{pttype}{RESET}!", + ) + + +def warn_generate_partial_failure( + *, + partial_config: dict[Any, str], + failed_devices: list[str], + successful_devices: list[str], +) -> list[ReadableMessage]: + return [ + ReadableMessage( + "info", + f""" + Successfully generated config for {EM}some{RESET} devices. + Errors are printed above. The generated partial config is: + {json.dumps(partial_config, indent=2)} + """, + ), + ReadableMessage( + "warning", + f""" + Successfully generated config for {EM}some{RESET} devices, {EM_WARN}but not all{RESET}! + Failed devices: {", ".join(f"{INVALID}{d}{RESET}" for d in failed_devices)} + Successful devices: {", ".join(f"{VALUE}{d}{RESET}" for d in successful_devices)} + """, + ), + ReadableMessage( + "help", + f""" + The {INVALID}ERROR{RESET} messages are printed {EM}above the generated config{RESET}. + Take a look at them and see if you can fix or safely ignore them. + If you can't, but you need a solution now, you can try to use the generated config, + but there is {EM_WARN}no guarantee{RESET} that it will work! + """, + ), + ] diff --git a/src/disko_lib/result.py b/src/disko_lib/result.py index 49b4e21..ea4a9e7 100644 --- a/src/disko_lib/result.py +++ b/src/disko_lib/result.py @@ -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) diff --git a/src/disko_lib/run_cmd.py b/src/disko_lib/run_cmd.py index 308a16c..c9eb90f 100644 --- a/src/disko_lib/run_cmd.py +++ b/src/disko_lib/run_cmd.py @@ -1,5 +1,7 @@ import subprocess +from disko_lib.messages.msgs import err_command_failed + from .logging import debug from .result import DiskoError, DiskoResult, DiskoSuccess @@ -23,11 +25,9 @@ def run(args: list[str]) -> DiskoResult[str]: return DiskoSuccess(result.stdout, "run command") return DiskoError.single_message( - "ERR_COMMAND_FAILED", - { - "command": command, - "stderr": result.stderr, - "exit_code": result.returncode, - }, + err_command_failed, "run command", + command=command, + stderr=result.stderr, + exit_code=result.returncode, ) diff --git a/src/disko_lib/types/disk.py b/src/disko_lib/types/disk.py index 2b74cef..ea604f1 100644 --- a/src/disko_lib/types/disk.py +++ b/src/disko_lib/types/disk.py @@ -1,5 +1,10 @@ from typing import Any +from disko_lib.messages.msgs import ( + err_unsupported_pttype, + warn_generate_partial_failure, +) + from ..logging import DiskoMessage, debug from ..result import DiskoError, DiskoResult, DiskoSuccess from ..types.device import BlockDevice, list_block_devices @@ -12,9 +17,10 @@ def _generate_content(device: BlockDevice) -> DiskoResult[dict[str, Any]]: return gpt.generate_config(device) case _: return DiskoError.single_message( - "ERR_UNSUPPORTED_PTTYPE", - {"device": device.path, "pttype": device.pttype}, + err_unsupported_pttype, "generate disk content", + device=device.path, + pttype=device.pttype, ) @@ -63,12 +69,10 @@ def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[dict[str, An error_messages + [ DiskoMessage( - "WARN_GENERATE_PARTIAL_FAILURE", - { - "partial_config": {"disks": disks}, - "failed_devices": failed_devices, - "successful_devices": successful_devices, - }, + warn_generate_partial_failure, + partial_config={"disks": disks}, + failed_devices=failed_devices, + successful_devices=successful_devices, ) ], "generate disk config", diff --git a/tests/disko_lib/test_types_disk.py b/tests/disko_lib/test_types_disk.py index 2be88af..dc29a3f 100644 --- a/tests/disko_lib/test_types_disk.py +++ b/tests/disko_lib/test_types_disk.py @@ -2,6 +2,7 @@ import json from pathlib import Path, PosixPath import pytest +from disko_lib.messages import err_unsupported_pttype, warn_generate_partial_failure from disko_lib.result import DiskoError, DiskoSuccess from disko_lib.types import disk from disko_lib.types import device @@ -19,13 +20,13 @@ def test_generate_config_partial_failure_dos_table() -> None: assert isinstance(result, DiskoError) - assert result.messages[0].code == "ERR_UNSUPPORTED_PTTYPE" + assert result.messages[0].factory == err_unsupported_pttype assert result.messages[0].details == { "pttype": "dos", "device": PosixPath("/dev/sdc"), } - assert result.messages[1].code == "WARN_GENERATE_PARTIAL_FAILURE" + assert result.messages[1].factory == warn_generate_partial_failure with open(CURRENT_DIR / "generate-result.json") as f: assert result.messages[1].details["partial_config"] == json.load(f) assert result.messages[1].details["failed_devices"] == [PosixPath("/dev/sdc")]