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

+5 -3
View File
@@ -8,6 +8,8 @@ from typing import Any, Literal, assert_never
from disko_lib.ansi import disko_dev_ansi from disko_lib.ansi import disko_dev_ansi
from disko_lib.eval_config import eval_disko_file, eval_flake from disko_lib.eval_config import eval_disko_file, eval_flake
from disko_lib.logging import LOGGER, debug, info 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.result import DiskoError, DiskoSuccess, DiskoResult, exit_on_error
from disko_lib.types.disk import generate_config from disko_lib.types.disk import generate_config
from disko_lib.types.device import disko_dev_lsblk from disko_lib.types.device import disko_dev_lsblk
@@ -49,13 +51,13 @@ def run_apply(
) -> DiskoResult[dict[str, Any]]: ) -> DiskoResult[dict[str, Any]]:
# match would be nicer, but mypy doesn't understand type narrowing in tuples # match would be nicer, but mypy doesn't understand type narrowing in tuples
if not disko_file and not flake: 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: if not disko_file and flake:
return eval_flake(flake) return eval_flake(flake)
if disko_file and not flake: if disko_file and not flake:
return eval_disko_file(Path(disko_file)) 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]]: def run_generate() -> DiskoResult[dict[str, Any]]:
@@ -82,7 +84,7 @@ def run(
match args.mode: match args.mode:
case None: case None:
return DiskoError.single_message( 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": case "generate":
return run_generate() return run_generate()
+12 -5
View File
@@ -3,6 +3,12 @@ from pathlib import Path
import re import re
from typing import Any 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 .run_cmd import run
from .result import DiskoError, DiskoResult, DiskoSuccess 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): if isinstance(result, DiskoError):
return DiskoError.single_message( return DiskoError.single_message(
"ERR_EVAL_CONFIG_FAILED", err_eval_config_failed,
{"args": args, "stderr": result.messages[0].details["stderr"]},
"evaluate disko configuration", "evaluate disko configuration",
args=args,
stderr=result.messages[0].details["stderr"],
) )
return result return result
@@ -47,9 +54,9 @@ def eval_disko_file(config_file: Path) -> DiskoResult[dict[str, Any]]:
if not abs_path.exists(): if not abs_path.exists():
return DiskoError.single_message( return DiskoError.single_message(
"ERR_FILE_NOT_FOUND", err_file_not_found,
{"path": abs_path},
"evaluate disko_file", "evaluate disko_file",
path=abs_path,
) )
return eval_config({"diskoFile": str(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: if not flake_attr:
return DiskoError.single_message( 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) flake_path = Path(flake)
+30 -170
View File
@@ -1,190 +1,55 @@
# Logging functionality and global logging configuration # Logging functionality and global logging configuration
from dataclasses import dataclass, field from dataclasses import dataclass
import json
import logging import logging
import re import re
from typing import Any, Literal, assert_never from typing import (
Any,
Callable,
Generic,
Literal,
ParamSpec,
TypeAlias,
)
from .ansi import Colors from .ansi import Colors
from .messages.colors import RESET
logging.basicConfig(format="%(message)s", level=logging.INFO) logging.basicConfig(format="%(message)s", level=logging.INFO)
LOGGER = logging.getLogger("disko_logger") 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 @dataclass
class ReadableMessage: class ReadableMessage:
type: Literal["bug", "error", "warning", "info", "help", "debug"] type: Literal["bug", "error", "warning", "info", "help", "debug"]
msg: str msg: str
# Codes for every single message that disko can print P = ParamSpec("P")
# Note: Sort them alphabetically when adding new ones!
MessageCode = Literal[ MessageFactory: TypeAlias = Callable[P, ReadableMessage | list[ReadableMessage]]
"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",
]
@dataclass @dataclass
class DiskoMessage: class DiskoMessage(Generic[P]):
code: MessageCode factory: MessageFactory[P]
details: dict[str, Any] = field(default_factory=dict) # 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 \ def to_readable(self) -> list[ReadableMessage]:
{FLAG}--flake{RESET}/{FLAG}-f{RESET} {PLACEHOLDER}flake-uri{RESET}." result = self.factory(**self.details)
if isinstance(result, list):
return result
return [result]
def print(self) -> None:
def bug_help_message(error_code: MessageCode) -> ReadableMessage: for msg in self.to_readable():
return ReadableMessage( render_message(msg)
"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)
# Dedent lines based on the indent of the first line until a non-indented line is hit. # 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 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: def debug(msg: str) -> None:
# Check debug level immediately to avoid unnecessary formatting # Check debug level immediately to avoid unnecessary formatting
if LOGGER.isEnabledFor(logging.DEBUG): if LOGGER.isEnabledFor(logging.DEBUG):
+3
View File
@@ -0,0 +1,3 @@
# Re-export all messages
from .msgs import * # noqa
from .bugs import * # noqa
+30
View File
@@ -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"),
]
+14
View File
@@ -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
+117
View File
@@ -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!
""",
),
]
+10 -7
View File
@@ -1,9 +1,12 @@
from dataclasses import dataclass 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) T = TypeVar("T", covariant=True)
P = ParamSpec("P")
@dataclass @dataclass
@@ -15,15 +18,15 @@ class DiskoSuccess(Generic[T]):
@dataclass @dataclass
class DiskoError: class DiskoError:
messages: list[DiskoMessage] messages: list[DiskoMessage[Any]]
context: str context: str
success: Literal[False] = False success: Literal[False] = False
@classmethod @classmethod
def single_message( def single_message(
cls, code: MessageCode, details: dict[str, Any], context: str cls, factory: MessageFactory[P], context: str, *_: P.args, **details: P.kwargs
) -> "DiskoError": ) -> "DiskoError":
return cls([DiskoMessage(code, details)], context) return cls([DiskoMessage(factory, **details)], context)
DiskoResult = DiskoSuccess[T] | DiskoError DiskoResult = DiskoSuccess[T] | DiskoError
@@ -32,13 +35,13 @@ DiskoResult = DiskoSuccess[T] | DiskoError
def exit_on_error(result: DiskoResult[T]) -> T: def exit_on_error(result: DiskoResult[T]) -> T:
if isinstance(result, DiskoSuccess): if isinstance(result, DiskoSuccess):
if result.context is None: if result.context is None:
print_msg("BUG_SUCCESS_WITHOUT_CONTEXT", {"value": result.value}) DiskoMessage(bug_success_without_context, value=result.value).print()
else: else:
debug(f"Success in '{result.context}'") debug(f"Success in '{result.context}'")
debug(f"Returned value: {result.value}") debug(f"Returned value: {result.value}")
return result.value return result.value
for message in result.messages: for message in result.messages:
print_msg(message.code, message.details) message.print()
exit(1) exit(1)
+6 -6
View File
@@ -1,5 +1,7 @@
import subprocess import subprocess
from disko_lib.messages.msgs import err_command_failed
from .logging import debug from .logging import debug
from .result import DiskoError, DiskoResult, DiskoSuccess from .result import DiskoError, DiskoResult, DiskoSuccess
@@ -23,11 +25,9 @@ def run(args: list[str]) -> DiskoResult[str]:
return DiskoSuccess(result.stdout, "run command") return DiskoSuccess(result.stdout, "run command")
return DiskoError.single_message( return DiskoError.single_message(
"ERR_COMMAND_FAILED", err_command_failed,
{
"command": command,
"stderr": result.stderr,
"exit_code": result.returncode,
},
"run command", "run command",
command=command,
stderr=result.stderr,
exit_code=result.returncode,
) )
+12 -8
View File
@@ -1,5 +1,10 @@
from typing import Any from typing import Any
from disko_lib.messages.msgs import (
err_unsupported_pttype,
warn_generate_partial_failure,
)
from ..logging import DiskoMessage, debug from ..logging import DiskoMessage, debug
from ..result import DiskoError, DiskoResult, DiskoSuccess from ..result import DiskoError, DiskoResult, DiskoSuccess
from ..types.device import BlockDevice, list_block_devices 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) return gpt.generate_config(device)
case _: case _:
return DiskoError.single_message( return DiskoError.single_message(
"ERR_UNSUPPORTED_PTTYPE", err_unsupported_pttype,
{"device": device.path, "pttype": device.pttype},
"generate disk content", "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 error_messages
+ [ + [
DiskoMessage( DiskoMessage(
"WARN_GENERATE_PARTIAL_FAILURE", warn_generate_partial_failure,
{ partial_config={"disks": disks},
"partial_config": {"disks": disks}, failed_devices=failed_devices,
"failed_devices": failed_devices, successful_devices=successful_devices,
"successful_devices": successful_devices,
},
) )
], ],
"generate disk config", "generate disk config",
+3 -2
View File
@@ -2,6 +2,7 @@ import json
from pathlib import Path, PosixPath from pathlib import Path, PosixPath
import pytest import pytest
from disko_lib.messages import err_unsupported_pttype, warn_generate_partial_failure
from disko_lib.result import DiskoError, DiskoSuccess from disko_lib.result import DiskoError, DiskoSuccess
from disko_lib.types import disk from disko_lib.types import disk
from disko_lib.types import device from disko_lib.types import device
@@ -19,13 +20,13 @@ def test_generate_config_partial_failure_dos_table() -> None:
assert isinstance(result, DiskoError) 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 == { assert result.messages[0].details == {
"pttype": "dos", "pttype": "dos",
"device": PosixPath("/dev/sdc"), "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: with open(CURRENT_DIR / "generate-result.json") as f:
assert result.messages[1].details["partial_config"] == json.load(f) assert result.messages[1].details["partial_config"] == json.load(f)
assert result.messages[1].details["failed_devices"] == [PosixPath("/dev/sdc")] assert result.messages[1].details["failed_devices"] == [PosixPath("/dev/sdc")]