mirror of
https://github.com/nix-community/disko.git
synced 2026-11-30 21:13:28 +01:00
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:
1 parent
4db452e40a
commit
a6944c6bea
11 files changed
+242
-201
No files matched your search
@@ -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)
|
||||
|
||||
+30
-170
@@ -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):
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Re-export all messages
|
||||
from .msgs import * # noqa
|
||||
from .bugs import * # noqa
|
||||
@@ -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"),
|
||||
]
|
||||
@@ -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
|
||||
@@ -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
@@ -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)
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user