mirror of
https://github.com/nix-community/disko.git
synced 2026-12-01 21:43:29 +01:00
disko2: Fix all mypy type checking errors
Belongs to d382a3cccf, but I authored that
on another machine.
Making sure vscode uses mypy from the environment is very important now,
because some of these errors get triggered in different ways depending
on the version.
This commit is contained in:
1 parent
a0e8f7f587
commit
ae7891e21f
22 files changed
+190
-145
No files matched your search
Vendored
+2
-1
@@ -17,5 +17,6 @@
|
|||||||
],
|
],
|
||||||
"python.analysis.extraPaths": [
|
"python.analysis.extraPaths": [
|
||||||
"./src"
|
"./src"
|
||||||
]
|
],
|
||||||
|
"mypy-type-checker.importStrategy": "fromEnvironment"
|
||||||
}
|
}
|
||||||
+1
-1
@@ -42,9 +42,9 @@ warn_return_any = true
|
|||||||
warn_unreachable = true
|
warn_unreachable = true
|
||||||
# Miscellaneous strictness flags
|
# Miscellaneous strictness flags
|
||||||
no_implicit_reexport = true
|
no_implicit_reexport = true
|
||||||
strict_concatenate = true
|
|
||||||
strict_equality = true
|
strict_equality = true
|
||||||
extra_checks = true
|
extra_checks = true
|
||||||
|
enable_error_code = "ignore-without-code"
|
||||||
# Error message control
|
# Error message control
|
||||||
show_error_context = true
|
show_error_context = true
|
||||||
show_error_code_links = true
|
show_error_code_links = true
|
||||||
|
|||||||
@@ -3,12 +3,19 @@
|
|||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
from typing import Any, Callable, Literal, Mapping, TypeGuard
|
from typing import Any, Callable, Mapping, TypeGuard, TypeVar, TypedDict, cast
|
||||||
|
|
||||||
|
JsonDict = dict[str, "JsonValue"]
|
||||||
|
JsonValue = str | int | float | bool | None | list["JsonValue"] | JsonDict
|
||||||
|
|
||||||
|
|
||||||
def is_type(
|
class TypeDefinition(TypedDict):
|
||||||
type_field: dict[str, Any]
|
type: str | JsonDict
|
||||||
) -> TypeGuard[dict[Literal["default", "description", "type"], Any]]:
|
default: JsonValue
|
||||||
|
description: str
|
||||||
|
|
||||||
|
|
||||||
|
def is_type(type_field: JsonValue) -> TypeGuard[TypeDefinition]:
|
||||||
if not isinstance(type_field, dict):
|
if not isinstance(type_field, dict):
|
||||||
return False
|
return False
|
||||||
return set(type_field.keys()) == {"default", "description", "type"}
|
return set(type_field.keys()) == {"default", "description", "type"}
|
||||||
@@ -111,7 +118,7 @@ def _parse_simple_type(type_str: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def parse_field(
|
def parse_field(
|
||||||
containing_class: str, field_name: str, field: dict[str, Any]
|
containing_class: str, field_name: str, field: str | JsonDict
|
||||||
) -> tuple[str, io.StringIO | None]:
|
) -> tuple[str, io.StringIO | None]:
|
||||||
if isinstance(field, str):
|
if isinstance(field, str):
|
||||||
return _parse_simple_type(field), None
|
return _parse_simple_type(field), None
|
||||||
@@ -177,16 +184,20 @@ def generate_class(name: str, fields: dict[str, Any]) -> tuple[str, io.StringIO
|
|||||||
return buffer.getvalue(), contained_classes_buffer
|
return buffer.getvalue(), contained_classes_buffer
|
||||||
|
|
||||||
|
|
||||||
def transform_dict_keys(
|
T = TypeVar("T", bound=JsonValue)
|
||||||
d: dict[str, Any], transform_fn: Callable[[str], str]
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
|
def transform_dict_keys(d: T, transform_fn: Callable[[str], str]) -> T:
|
||||||
if not isinstance(d, Mapping):
|
if not isinstance(d, Mapping):
|
||||||
return d
|
return d
|
||||||
|
|
||||||
return {transform_fn(k): transform_dict_keys(v, transform_fn) for k, v in d.items()}
|
return cast(
|
||||||
|
T,
|
||||||
|
{transform_fn(k): transform_dict_keys(v, transform_fn) for k, v in d.items()},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def generate_python_code(schema: dict[str, dict[str, Any]]) -> io.StringIO:
|
def generate_python_code(schema: JsonDict) -> io.StringIO:
|
||||||
assert isinstance(schema, dict)
|
assert isinstance(schema, dict)
|
||||||
|
|
||||||
# Convert disallowed characters in Python identifiers
|
# Convert disallowed characters in Python identifiers
|
||||||
@@ -195,7 +206,11 @@ def generate_python_code(schema: dict[str, dict[str, Any]]) -> io.StringIO:
|
|||||||
buffer = io.StringIO()
|
buffer = io.StringIO()
|
||||||
|
|
||||||
buffer.write(
|
buffer.write(
|
||||||
"""
|
"""# File generated by scripts/generate_python_types.py
|
||||||
|
# Ignore warnings that decorators contain Any
|
||||||
|
# mypy: disable-error-code="misc"
|
||||||
|
# Disable auto-formatting for this file
|
||||||
|
# fmt: off
|
||||||
from typing import Any, Literal, Union
|
from typing import Any, Literal, Union
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
@@ -204,6 +219,7 @@ from pydantic import BaseModel
|
|||||||
)
|
)
|
||||||
|
|
||||||
for type_name, fields in schema.items():
|
for type_name, fields in schema.items():
|
||||||
|
assert isinstance(fields, dict)
|
||||||
if "__isCompositeType" in fields:
|
if "__isCompositeType" in fields:
|
||||||
try:
|
try:
|
||||||
alias_content, type_code = _parse_composite_type(type_name, "", fields)
|
alias_content, type_code = _parse_composite_type(type_name, "", fields)
|
||||||
|
|||||||
+7
-7
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
from typing import Any, Literal
|
from typing import Any, Literal, cast
|
||||||
|
|
||||||
from disko.mode_dev import run_dev
|
from disko.mode_dev import run_dev
|
||||||
from disko.mode_generate import run_generate
|
from disko.mode_generate import run_generate
|
||||||
@@ -10,7 +10,7 @@ from disko_lib.eval_config import eval_config
|
|||||||
from disko_lib.logging import LOGGER, debug, info
|
from disko_lib.logging import LOGGER, debug, info
|
||||||
from disko_lib.messages.msgs import err_missing_mode
|
from disko_lib.messages.msgs import err_missing_mode
|
||||||
from disko_lib.result import DiskoError, DiskoResult, exit_on_error
|
from disko_lib.result import DiskoError, DiskoResult, exit_on_error
|
||||||
from disko_lib.types.disk import generate_config
|
from disko_lib.json_types import JsonDict
|
||||||
|
|
||||||
Mode = Literal[
|
Mode = Literal[
|
||||||
"destroy",
|
"destroy",
|
||||||
@@ -46,18 +46,18 @@ MODE_DESCRIPTION: dict[Mode, str] = {
|
|||||||
|
|
||||||
def run_apply(
|
def run_apply(
|
||||||
*, mode: str, disko_file: str | None, flake: str | None, **_kwargs: dict[str, Any]
|
*, mode: str, disko_file: str | None, flake: str | None, **_kwargs: dict[str, Any]
|
||||||
) -> DiskoResult[dict[str, Any]]:
|
) -> DiskoResult[JsonDict]:
|
||||||
return eval_config(disko_file=disko_file, flake=flake)
|
return eval_config(disko_file=disko_file, flake=flake)
|
||||||
|
|
||||||
|
|
||||||
def run(
|
def run(
|
||||||
args: argparse.Namespace,
|
args: argparse.Namespace,
|
||||||
) -> DiskoResult[None | dict[str, Any]]:
|
) -> DiskoResult[None | JsonDict]:
|
||||||
if args.verbose:
|
if cast(bool, args.verbose):
|
||||||
LOGGER.setLevel("DEBUG")
|
LOGGER.setLevel("DEBUG")
|
||||||
debug("Enabled debug logging.")
|
debug("Enabled debug logging.")
|
||||||
|
|
||||||
match args.mode:
|
match cast(Mode | None, args.mode):
|
||||||
case None:
|
case None:
|
||||||
return DiskoError.single_message(
|
return DiskoError.single_message(
|
||||||
err_missing_mode, "select mode", valid_modes=[str(m) for m in ALL_MODES]
|
err_missing_mode, "select mode", valid_modes=[str(m) for m in ALL_MODES]
|
||||||
@@ -67,7 +67,7 @@ def run(
|
|||||||
case "dev":
|
case "dev":
|
||||||
return run_dev(args)
|
return run_dev(args)
|
||||||
case _:
|
case _:
|
||||||
return run_apply(**vars(args))
|
return run_apply(**vars(args)) # type: ignore[misc]
|
||||||
|
|
||||||
|
|
||||||
def parse_args() -> argparse.Namespace:
|
def parse_args() -> argparse.Namespace:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
from typing import Any
|
from typing import Any, cast
|
||||||
|
|
||||||
from disko_lib.ansi import Colors
|
from disko_lib.ansi import Colors
|
||||||
from disko_lib.eval_config import eval_config
|
from disko_lib.eval_config import eval_config
|
||||||
@@ -22,8 +22,8 @@ def run_dev_ansi() -> DiskoResult[None]:
|
|||||||
import inspect
|
import inspect
|
||||||
|
|
||||||
for name, value in inspect.getmembers(Colors):
|
for name, value in inspect.getmembers(Colors):
|
||||||
if value != "_" and not name.startswith("_") and name != "RESET":
|
if value != "_" and not name.startswith("_") and name != "RESET": # type: ignore[misc]
|
||||||
print("{:>30} {}".format(name, value + name + Colors.RESET))
|
print("{:>30} {}".format(name, value + name + Colors.RESET)) # type: ignore[misc]
|
||||||
|
|
||||||
return DiskoSuccess(None, "run disko dev ansi")
|
return DiskoSuccess(None, "run disko dev ansi")
|
||||||
|
|
||||||
@@ -41,13 +41,13 @@ def run_dev_eval(
|
|||||||
|
|
||||||
|
|
||||||
def run_dev(args: argparse.Namespace) -> DiskoResult[None]:
|
def run_dev(args: argparse.Namespace) -> DiskoResult[None]:
|
||||||
match args.dev_command:
|
match cast(str | None, args.dev_command):
|
||||||
case "lsblk":
|
case "lsblk":
|
||||||
return run_dev_lsblk()
|
return run_dev_lsblk()
|
||||||
case "ansi":
|
case "ansi":
|
||||||
return run_dev_ansi()
|
return run_dev_ansi()
|
||||||
case "eval":
|
case "eval":
|
||||||
return run_dev_eval(**vars(args))
|
return run_dev_eval(**vars(args)) # type: ignore[misc]
|
||||||
case _:
|
case _:
|
||||||
return DiskoError.single_message(
|
return DiskoError.single_message(
|
||||||
err_missing_mode, "select mode", valid_modes=["lsblk", "ansi", "eval"]
|
err_missing_mode, "select mode", valid_modes=["lsblk", "ansi", "eval"]
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
from typing import Any
|
|
||||||
from disko_lib.logging import info
|
from disko_lib.logging import info
|
||||||
from disko_lib.messages.msgs import warn_generate_partial_failure
|
from disko_lib.messages.msgs import warn_generate_partial_failure
|
||||||
from disko_lib.result import DiskoResult, DiskoError
|
from disko_lib.result import DiskoResult, DiskoError
|
||||||
from disko_lib.types.disk import generate_config
|
from disko_lib.types.disk import generate_config
|
||||||
from disko_lib.run_cmd import run
|
from disko_lib.run_cmd import run
|
||||||
|
from disko_lib.json_types import JsonDict
|
||||||
|
|
||||||
DEFAULT_CONFIG_FILE = "disko-config.nix"
|
DEFAULT_CONFIG_FILE = "disko-config.nix"
|
||||||
|
|
||||||
@@ -25,7 +25,7 @@ PARTIAL_FAILURE_COMMENT = """
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def run_generate() -> DiskoResult[dict[str, Any]]:
|
def run_generate() -> DiskoResult[JsonDict]:
|
||||||
generated_config_result = generate_config()
|
generated_config_result = generate_config()
|
||||||
generated_config = None
|
generated_config = None
|
||||||
|
|
||||||
|
|||||||
+11
-5
@@ -3,6 +3,8 @@
|
|||||||
# Inspired by rene-d's colors.py, published in 2018
|
# Inspired by rene-d's colors.py, published in 2018
|
||||||
# See https://gist.github.com/rene-d/9e584a7dd2935d0f461904b9f2950007
|
# See https://gist.github.com/rene-d/9e584a7dd2935d0f461904b9f2950007
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
class Colors:
|
class Colors:
|
||||||
"""
|
"""
|
||||||
@@ -163,13 +165,17 @@ class Colors:
|
|||||||
ATTR_STRIKE = "\033[9m"
|
ATTR_STRIKE = "\033[9m"
|
||||||
|
|
||||||
# cancel SGR codes if we don't write to a terminal
|
# cancel SGR codes if we don't write to a terminal
|
||||||
if not __import__("sys").stdout.isatty():
|
if not sys.stdout.isatty():
|
||||||
for _ in dir():
|
for _ in dir():
|
||||||
if isinstance(_, str) and _[0] != "_":
|
if isinstance(_, str) and _[0] != "_":
|
||||||
locals()[_] = ""
|
locals()[_] = "" # type: ignore[misc]
|
||||||
else:
|
else:
|
||||||
|
import platform
|
||||||
|
|
||||||
# set Windows console in VT mode
|
# set Windows console in VT mode
|
||||||
if __import__("platform").system() == "Windows":
|
if platform.system() == "Windows":
|
||||||
kernel32 = __import__("ctypes").windll.kernel32
|
import ctypes
|
||||||
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
|
|
||||||
|
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined, misc]
|
||||||
|
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7) # type: ignore[misc]
|
||||||
del kernel32
|
del kernel32
|
||||||
@@ -1,4 +1,8 @@
|
|||||||
|
# File generated by scripts/generate_python_types.py
|
||||||
|
# Ignore warnings that decorators contain Any
|
||||||
|
# mypy: disable-error-code="misc"
|
||||||
|
# Disable auto-formatting for this file
|
||||||
|
# fmt: off
|
||||||
from typing import Any, Literal, Union
|
from typing import Any, Literal, Union
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from typing import Any
|
from .json_types import JsonDict
|
||||||
|
|
||||||
|
|
||||||
def dict_diff(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
|
def dict_diff(left: JsonDict, right: JsonDict) -> JsonDict:
|
||||||
"""Return a dict that only contains the keys and values of `right`
|
"""Return a dict that only contains the keys and values of `right`
|
||||||
that are different from those in `left`.
|
that are different from those in `left`.
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ def dict_diff(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
|
|||||||
>>> dict_diff({"a": {"b": 1}}, {"a": {"b": 3}, "c": {"d": 4}})
|
>>> dict_diff({"a": {"b": 1}}, {"a": {"b": 3}, "c": {"d": 4}})
|
||||||
{'a': {'b': 3}, 'c': {'d': 4, '_new': True}}
|
{'a': {'b': 3}, 'c': {'d': 4, '_new': True}}
|
||||||
"""
|
"""
|
||||||
new_dict: dict[str, Any] = {}
|
new_dict: JsonDict = {}
|
||||||
|
|
||||||
for k, right_val in right.items():
|
for k, right_val in right.items():
|
||||||
left_val = left.get(k)
|
left_val = left.get(k)
|
||||||
@@ -32,12 +32,17 @@ def dict_diff(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
if not isinstance(right_val, dict):
|
if not isinstance(right_val, dict):
|
||||||
new_dict[k] = right[k]
|
new_dict[k] = right_val
|
||||||
continue
|
continue
|
||||||
|
|
||||||
new_dict[k] = dict_diff(left.get(k, {}), right[k])
|
if not isinstance(left_val, dict):
|
||||||
|
left_val = {}
|
||||||
|
|
||||||
|
diffed_right_val = dict_diff(left_val, right_val)
|
||||||
if not left_val:
|
if not left_val:
|
||||||
new_dict[k]["_new"] = True
|
diffed_right_val["_new"] = True
|
||||||
|
|
||||||
|
new_dict[k] = diffed_right_val
|
||||||
|
|
||||||
for k, left_val in left.items():
|
for k, left_val in left.items():
|
||||||
if k not in right:
|
if k not in right:
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import re
|
import re
|
||||||
from typing import Any
|
from typing import cast
|
||||||
|
|
||||||
|
from .json_types import JsonDict
|
||||||
|
|
||||||
from disko_lib.messages.msgs import (
|
from disko_lib.messages.msgs import (
|
||||||
err_eval_config_failed,
|
err_eval_config_failed,
|
||||||
@@ -30,7 +32,7 @@ assert (
|
|||||||
), f"Can't find `eval-config.nix`, expected it next to {__file__}"
|
), f"Can't find `eval-config.nix`, expected it next to {__file__}"
|
||||||
|
|
||||||
|
|
||||||
def _eval_config(args: dict[str, str]) -> DiskoResult[dict[str, Any]]:
|
def _eval_config(args: dict[str, str]) -> DiskoResult[JsonDict]:
|
||||||
args_as_json = json.dumps(args)
|
args_as_json = json.dumps(args)
|
||||||
|
|
||||||
result = run(
|
result = run(
|
||||||
@@ -43,14 +45,16 @@ def _eval_config(args: dict[str, str]) -> DiskoResult[dict[str, Any]]:
|
|||||||
err_eval_config_failed,
|
err_eval_config_failed,
|
||||||
"evaluate disko configuration",
|
"evaluate disko configuration",
|
||||||
args=args,
|
args=args,
|
||||||
stderr=result.messages[0].details["stderr"],
|
stderr=cast(str, result.messages[0].details["stderr"]),
|
||||||
)
|
)
|
||||||
|
|
||||||
# We trust the output of `nix eval` to be valid JSON
|
# We trust the output of `nix eval` to be valid JSON
|
||||||
return DiskoSuccess(json.loads(result.value), "evaluate disko config")
|
return DiskoSuccess(
|
||||||
|
cast(JsonDict, json.loads(result.value)), "evaluate disko config"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _eval_disko_file(config_file: Path) -> DiskoResult[dict[str, Any]]:
|
def _eval_disko_file(config_file: Path) -> DiskoResult[JsonDict]:
|
||||||
abs_path = config_file.absolute()
|
abs_path = config_file.absolute()
|
||||||
|
|
||||||
if not abs_path.exists():
|
if not abs_path.exists():
|
||||||
@@ -63,7 +67,7 @@ def _eval_disko_file(config_file: Path) -> DiskoResult[dict[str, Any]]:
|
|||||||
return _eval_config({"diskoFile": str(abs_path)})
|
return _eval_config({"diskoFile": str(abs_path)})
|
||||||
|
|
||||||
|
|
||||||
def _eval_flake(flake_uri: str) -> DiskoResult[dict[str, Any]]:
|
def _eval_flake(flake_uri: str) -> DiskoResult[JsonDict]:
|
||||||
# arg parser should not allow empty strings
|
# arg parser should not allow empty strings
|
||||||
assert len(flake_uri) > 0
|
assert len(flake_uri) > 0
|
||||||
|
|
||||||
@@ -71,9 +75,8 @@ def _eval_flake(flake_uri: str) -> DiskoResult[dict[str, Any]]:
|
|||||||
|
|
||||||
# Match can't be none if we receive at least one character
|
# Match can't be none if we receive at least one character
|
||||||
assert flake_match is not None
|
assert flake_match is not None
|
||||||
|
flake = cast(str, flake_match.group(1))
|
||||||
flake = flake_match.group(1)
|
flake_attr = cast(str, flake_match.group(2))
|
||||||
flake_attr = flake_match.group(2)
|
|
||||||
|
|
||||||
if not flake_attr:
|
if not flake_attr:
|
||||||
return DiskoError.single_message(
|
return DiskoError.single_message(
|
||||||
@@ -87,9 +90,7 @@ def _eval_flake(flake_uri: str) -> DiskoResult[dict[str, Any]]:
|
|||||||
return _eval_config({"flake": flake, "flakeAttr": flake_attr})
|
return _eval_config({"flake": flake, "flakeAttr": flake_attr})
|
||||||
|
|
||||||
|
|
||||||
def eval_config(
|
def eval_config(*, disko_file: str | None, flake: str | None) -> DiskoResult[JsonDict]:
|
||||||
*, disko_file: str | None, flake: str | None
|
|
||||||
) -> 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")
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
JsonDict = dict[str, "JsonValue"]
|
||||||
|
JsonValue = str | int | float | bool | None | list["JsonValue"] | JsonDict
|
||||||
@@ -9,6 +9,7 @@ from typing import (
|
|||||||
Literal,
|
Literal,
|
||||||
ParamSpec,
|
ParamSpec,
|
||||||
TypeAlias,
|
TypeAlias,
|
||||||
|
cast,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .ansi import Colors
|
from .ansi import Colors
|
||||||
@@ -68,16 +69,16 @@ MessageFactory: TypeAlias = Callable[P, ReadableMessage | list[ReadableMessage]]
|
|||||||
class DiskoMessage(Generic[P]):
|
class DiskoMessage(Generic[P]):
|
||||||
factory: MessageFactory[P]
|
factory: MessageFactory[P]
|
||||||
# Can't infer a TypedDict from a ParamSpec yet (mypy 1.10.1, python 3.12.5)
|
# 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
|
details: dict[str, object]
|
||||||
# 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:
|
def __init__(self, factory: MessageFactory[P], **details: P.kwargs) -> None:
|
||||||
self.factory = factory
|
self.factory = factory
|
||||||
self.details = details
|
self.details = details
|
||||||
|
|
||||||
def to_readable(self) -> list[ReadableMessage]:
|
def to_readable(self) -> list[ReadableMessage]:
|
||||||
result = self.factory(**self.details)
|
# This is only safe because the type of __init__ ensures that the
|
||||||
|
# keys in details are the same as the keys in the factory kwargs
|
||||||
|
result = self.factory(**self.details) # type: ignore[arg-type]
|
||||||
if isinstance(result, list):
|
if isinstance(result, list):
|
||||||
return result
|
return result
|
||||||
return [result]
|
return [result]
|
||||||
@@ -86,6 +87,9 @@ class DiskoMessage(Generic[P]):
|
|||||||
for msg in self.to_readable():
|
for msg in self.to_readable():
|
||||||
render_message(msg)
|
render_message(msg)
|
||||||
|
|
||||||
|
def is_message(self, factory: MessageFactory[Any]) -> bool:
|
||||||
|
return self.factory == factory # type: ignore[misc]
|
||||||
|
|
||||||
|
|
||||||
# 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.
|
||||||
# This will dedent the lines written in multiline f-strigns without breaking
|
# This will dedent the lines written in multiline f-strigns without breaking
|
||||||
@@ -93,8 +97,7 @@ class DiskoMessage(Generic[P]):
|
|||||||
def dedent_start_lines(lines: list[str]) -> list[str]:
|
def dedent_start_lines(lines: list[str]) -> list[str]:
|
||||||
spaces_prefix_match = re.match(r"^( *)", lines[0])
|
spaces_prefix_match = re.match(r"^( *)", lines[0])
|
||||||
# Regex will even match an empty string, match can't be none
|
# Regex will even match an empty string, match can't be none
|
||||||
assert spaces_prefix_match is not None
|
dedent_width = len(spaces_prefix_match.group(1)) # type: ignore[union-attr, misc]
|
||||||
dedent_width = len(spaces_prefix_match.group(1))
|
|
||||||
|
|
||||||
if dedent_width == 0:
|
if dedent_width == 0:
|
||||||
return lines
|
return lines
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
from typing import Any
|
|
||||||
from disko_lib.logging import ReadableMessage
|
from disko_lib.logging import ReadableMessage
|
||||||
|
|
||||||
|
|
||||||
@@ -16,7 +15,7 @@ def __bug_help_message(error_code: str) -> ReadableMessage:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def bug_success_without_context(*, value: Any) -> list[ReadableMessage]:
|
def bug_success_without_context(*, value: object) -> list[ReadableMessage]:
|
||||||
return [
|
return [
|
||||||
ReadableMessage(
|
ReadableMessage(
|
||||||
"bug",
|
"bug",
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
|
||||||
from disko_lib.logging import ReadableMessage
|
from disko_lib.logging import ReadableMessage
|
||||||
from .colors import PLACEHOLDER, RESET, FLAG, COMMAND, INVALID, FILE, VALUE, EM, EM_WARN
|
from .colors import PLACEHOLDER, RESET, FLAG, COMMAND, INVALID, FILE, VALUE, EM, EM_WARN
|
||||||
|
from ..json_types import JsonDict
|
||||||
|
|
||||||
ERR_ARGUMENTS_HELP_TXT = f"Provide either {PLACEHOLDER}disko_file{RESET} as the second argument or \
|
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}."
|
{FLAG}--flake{RESET}/{FLAG}-f{RESET} {PLACEHOLDER}flake-uri{RESET}."
|
||||||
@@ -19,7 +19,7 @@ def err_command_failed(*, command: str, exit_code: int, stderr: str) -> Readable
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def err_eval_config_failed(*, args: dict[str, Any], stderr: str) -> ReadableMessage:
|
def err_eval_config_failed(*, args: dict[str, str], stderr: str) -> ReadableMessage:
|
||||||
return ReadableMessage(
|
return ReadableMessage(
|
||||||
"error",
|
"error",
|
||||||
f"""
|
f"""
|
||||||
@@ -83,7 +83,7 @@ def err_unsupported_pttype(*, device: Path, pttype: str) -> ReadableMessage:
|
|||||||
|
|
||||||
def warn_generate_partial_failure(
|
def warn_generate_partial_failure(
|
||||||
*,
|
*,
|
||||||
partial_config: dict[Any, str],
|
partial_config: JsonDict,
|
||||||
failed_devices: list[str],
|
failed_devices: list[str],
|
||||||
successful_devices: list[str],
|
successful_devices: list[str],
|
||||||
) -> list[ReadableMessage]:
|
) -> list[ReadableMessage]:
|
||||||
|
|||||||
+12
-5
@@ -1,5 +1,5 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Any, Generic, Literal, ParamSpec, TypeVar
|
from typing import Any, Generic, Literal, ParamSpec, TypeVar, cast
|
||||||
|
|
||||||
from disko_lib.messages.bugs import bug_success_without_context
|
from disko_lib.messages.bugs import bug_success_without_context
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ class DiskoSuccess(Generic[T]):
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class DiskoError:
|
class DiskoError:
|
||||||
messages: list[DiskoMessage[Any]]
|
messages: list[DiskoMessage[object]]
|
||||||
context: str
|
context: str
|
||||||
success: Literal[False] = False
|
success: Literal[False] = False
|
||||||
|
|
||||||
@@ -26,18 +26,25 @@ class DiskoError:
|
|||||||
def single_message(
|
def single_message(
|
||||||
cls, factory: MessageFactory[P], context: str, *_: P.args, **details: P.kwargs
|
cls, factory: MessageFactory[P], context: str, *_: P.args, **details: P.kwargs
|
||||||
) -> "DiskoError":
|
) -> "DiskoError":
|
||||||
return cls([DiskoMessage(factory, **details)], context)
|
_factory = cast(MessageFactory[object], factory)
|
||||||
|
return cls([DiskoMessage(_factory, **details)], context)
|
||||||
|
|
||||||
def find_message(
|
def find_message(
|
||||||
self, message_factory: MessageFactory[P]
|
self, message_factory: MessageFactory[P]
|
||||||
) -> None | DiskoMessage[P]:
|
) -> None | DiskoMessage[P]:
|
||||||
for message in self.messages:
|
for message in self.messages:
|
||||||
if message.factory == message_factory:
|
if message.factory == message_factory:
|
||||||
return message
|
return cast(DiskoMessage[P], message)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def append(self, message: DiskoMessage[Any]) -> None:
|
||||||
|
self.messages.append(message) # type: ignore[misc]
|
||||||
|
|
||||||
DiskoResult = DiskoSuccess[T] | DiskoError
|
def extend(self, other_error: "DiskoError") -> None:
|
||||||
|
self.messages.extend(other_error.messages)
|
||||||
|
|
||||||
|
|
||||||
|
DiskoResult = DiskoSuccess[T] | DiskoError # type: ignore[misc, unused-ignore]
|
||||||
|
|
||||||
|
|
||||||
def exit_on_error(result: DiskoResult[T]) -> T:
|
def exit_on_error(result: DiskoResult[T]) -> T:
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any, cast
|
||||||
|
import typing
|
||||||
|
|
||||||
from ..result import DiskoError, DiskoResult, DiskoSuccess
|
from ..result import DiskoError, DiskoResult, DiskoSuccess
|
||||||
from ..run_cmd import run
|
from ..run_cmd import run
|
||||||
|
from ..json_types import JsonDict
|
||||||
|
|
||||||
# To see what other fields are available in the lsblk output and what
|
# To see what other fields are available in the lsblk output and what
|
||||||
# sort of values you can expect from them, run:
|
# sort of values you can expect from them, run:
|
||||||
@@ -68,14 +70,16 @@ class BlockDevice:
|
|||||||
children: list["BlockDevice"]
|
children: list["BlockDevice"]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_json_dict(cls, json_dict: dict[str, Any]) -> "BlockDevice":
|
def from_json_dict(cls, json_dict: JsonDict) -> "BlockDevice":
|
||||||
children = [
|
children_list = json_dict.get("children", [])
|
||||||
cls.from_json_dict(child_dict)
|
assert isinstance(children_list, list)
|
||||||
for child_dict in json_dict.get("children", [])
|
children = []
|
||||||
]
|
for child_dict in children_list:
|
||||||
|
assert isinstance(child_dict, dict)
|
||||||
|
children.append(cls.from_json_dict(child_dict))
|
||||||
|
|
||||||
# The mountpoints field will be a list containing a single null if there are no mountpoints
|
# The mountpoints field will be a list containing a single null if there are no mountpoints
|
||||||
mountpoints = json_dict["mountpoints"] or []
|
mountpoints = cast(list[str], json_dict["mountpoints"]) or []
|
||||||
if not any(mountpoints):
|
if not any(mountpoints):
|
||||||
mountpoints = []
|
mountpoints = []
|
||||||
|
|
||||||
@@ -83,30 +87,30 @@ class BlockDevice:
|
|||||||
# but some might be null. Set a default value for the fields we have observed to be optional.
|
# but some might be null. Set a default value for the fields we have observed to be optional.
|
||||||
return cls(
|
return cls(
|
||||||
children=children,
|
children=children,
|
||||||
id_link=json_dict["id-link"],
|
id_link=cast(str, json_dict["id-link"]),
|
||||||
fstype=json_dict["fstype"] or "",
|
fstype=cast(str, json_dict["fstype"]) or "",
|
||||||
fssize=json_dict["fssize"] or "",
|
fssize=cast(str, json_dict["fssize"]) or "",
|
||||||
fsuse_pct=json_dict["fsuse%"] or "",
|
fsuse_pct=cast(str, json_dict["fsuse%"]) or "",
|
||||||
kname=json_dict["kname"],
|
kname=cast(str, json_dict["kname"]),
|
||||||
label=json_dict["label"] or "",
|
label=cast(str, json_dict["label"]) or "",
|
||||||
model=json_dict["model"] or "",
|
model=cast(str, json_dict["model"]) or "",
|
||||||
partflags=json_dict["partflags"] or "",
|
partflags=cast(str, json_dict["partflags"]) or "",
|
||||||
partlabel=json_dict["partlabel"] or "",
|
partlabel=cast(str, json_dict["partlabel"]) or "",
|
||||||
partn=json_dict["partn"],
|
partn=cast(int, json_dict["partn"]),
|
||||||
parttype=json_dict["parttype"] or "",
|
parttype=cast(str, json_dict["parttype"]) or "",
|
||||||
parttypename=json_dict["parttypename"] or "",
|
parttypename=cast(str, json_dict["parttypename"]) or "",
|
||||||
partuuid=json_dict["partuuid"] or "",
|
partuuid=cast(str, json_dict["partuuid"]) or "",
|
||||||
path=Path(json_dict["path"]),
|
path=Path(cast(str, json_dict["path"])),
|
||||||
phy_sec=json_dict["phy-sec"],
|
phy_sec=cast(int, json_dict["phy-sec"]),
|
||||||
pttype=json_dict["pttype"],
|
pttype=cast(str, json_dict["pttype"]),
|
||||||
rev=json_dict["rev"] or "",
|
rev=cast(str, json_dict["rev"]) or "",
|
||||||
serial=json_dict["serial"] or "",
|
serial=cast(str, json_dict["serial"]) or "",
|
||||||
size=json_dict["size"],
|
size=cast(str, json_dict["size"]),
|
||||||
start=json_dict["start"] or "",
|
start=cast(str, json_dict["start"]) or "",
|
||||||
mountpoint=json_dict["mountpoint"] or "",
|
mountpoint=cast(str, json_dict["mountpoint"]) or "",
|
||||||
mountpoints=mountpoints,
|
mountpoints=mountpoints,
|
||||||
type=json_dict["type"],
|
type=cast(str, json_dict["type"]),
|
||||||
uuid=json_dict["uuid"] or "",
|
uuid=cast(str, json_dict["uuid"]) or "",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -124,7 +128,8 @@ def list_block_devices(lsblk_output: str = "") -> DiskoResult[list[BlockDevice]]
|
|||||||
lsblk_output = lsblk_result.value
|
lsblk_output = lsblk_result.value
|
||||||
|
|
||||||
# We trust the output of `lsblk` to be valid JSON
|
# We trust the output of `lsblk` to be valid JSON
|
||||||
lsblk_json: list[dict[str, Any]] = json.loads(lsblk_output)["blockdevices"]
|
output: JsonDict = json.loads(lsblk_output)
|
||||||
|
lsblk_json: list[JsonDict] = output["blockdevices"] # type: ignore[assignment]
|
||||||
|
|
||||||
blockdevices = [BlockDevice.from_json_dict(dev) for dev in lsblk_json]
|
blockdevices = [BlockDevice.from_json_dict(dev) for dev in lsblk_json]
|
||||||
|
|
||||||
|
|||||||
+17
-22
@@ -1,5 +1,4 @@
|
|||||||
from typing import Any
|
from typing import cast
|
||||||
|
|
||||||
from disko_lib.messages.msgs import (
|
from disko_lib.messages.msgs import (
|
||||||
err_unsupported_pttype,
|
err_unsupported_pttype,
|
||||||
warn_generate_partial_failure,
|
warn_generate_partial_failure,
|
||||||
@@ -8,10 +7,11 @@ from disko_lib.messages.msgs import (
|
|||||||
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
|
||||||
|
from ..json_types import JsonDict
|
||||||
from . import gpt
|
from . import gpt
|
||||||
|
|
||||||
|
|
||||||
def _generate_content(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
def _generate_content(device: BlockDevice) -> DiskoResult[JsonDict]:
|
||||||
match device.pttype:
|
match device.pttype:
|
||||||
case "gpt":
|
case "gpt":
|
||||||
return gpt.generate_config(device)
|
return gpt.generate_config(device)
|
||||||
@@ -24,7 +24,7 @@ def _generate_content(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[dict[str, Any]]:
|
def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[JsonDict]:
|
||||||
block_devices = devices
|
block_devices = devices
|
||||||
if not block_devices:
|
if not block_devices:
|
||||||
lsblk_result = list_block_devices()
|
lsblk_result = list_block_devices()
|
||||||
@@ -34,13 +34,10 @@ def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[dict[str, An
|
|||||||
|
|
||||||
block_devices = lsblk_result.value
|
block_devices = lsblk_result.value
|
||||||
|
|
||||||
if isinstance(block_devices, DiskoError):
|
|
||||||
return block_devices
|
|
||||||
|
|
||||||
debug(f"Generating config for devices {[d.path for d in block_devices]}")
|
debug(f"Generating config for devices {[d.path for d in block_devices]}")
|
||||||
|
|
||||||
disks = {}
|
disks: JsonDict = {}
|
||||||
error_messages = []
|
error = DiskoError([], "generate disk config")
|
||||||
failed_devices = []
|
failed_devices = []
|
||||||
successful_devices = []
|
successful_devices = []
|
||||||
|
|
||||||
@@ -48,7 +45,7 @@ def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[dict[str, An
|
|||||||
content = _generate_content(device)
|
content = _generate_content(device)
|
||||||
|
|
||||||
if isinstance(content, DiskoError):
|
if isinstance(content, DiskoError):
|
||||||
error_messages.extend(content.messages)
|
error.extend(content)
|
||||||
failed_devices.append(device.path)
|
failed_devices.append(device.path)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -59,21 +56,19 @@ def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[dict[str, An
|
|||||||
}
|
}
|
||||||
successful_devices.append(device.path)
|
successful_devices.append(device.path)
|
||||||
|
|
||||||
|
config: JsonDict = {"disks": disks}
|
||||||
|
|
||||||
if not failed_devices:
|
if not failed_devices:
|
||||||
return DiskoSuccess({"disks": disks}, "generate disk config")
|
return DiskoSuccess(config, "generate disk config")
|
||||||
|
|
||||||
if not successful_devices:
|
if successful_devices:
|
||||||
return DiskoError(error_messages, "generate disk config")
|
error.append(
|
||||||
|
|
||||||
return DiskoError(
|
|
||||||
error_messages
|
|
||||||
+ [
|
|
||||||
DiskoMessage(
|
DiskoMessage(
|
||||||
warn_generate_partial_failure,
|
warn_generate_partial_failure,
|
||||||
partial_config={"disks": disks},
|
partial_config=config,
|
||||||
failed_devices=failed_devices,
|
failed_devices=failed_devices,
|
||||||
successful_devices=successful_devices,
|
successful_devices=successful_devices,
|
||||||
)
|
),
|
||||||
],
|
)
|
||||||
"generate disk config",
|
|
||||||
)
|
return error
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
from typing import Any
|
|
||||||
from .device import BlockDevice
|
from .device import BlockDevice
|
||||||
from ..result import DiskoResult, DiskoSuccess
|
from ..result import DiskoResult, DiskoSuccess
|
||||||
|
from ..json_types import JsonDict
|
||||||
|
|
||||||
|
|
||||||
def generate_config(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
def generate_config(device: BlockDevice) -> DiskoResult[JsonDict]:
|
||||||
assert (
|
assert (
|
||||||
device.type == "part"
|
device.type == "part"
|
||||||
), f"BUG! filesystem.generate_config called with non-partition device {device.path}"
|
), f"BUG! filesystem.generate_config called with non-partition device {device.path}"
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
from typing import Any
|
|
||||||
from ..logging import debug
|
from ..logging import debug
|
||||||
from . import filesystem
|
from . import filesystem
|
||||||
from .device import BlockDevice
|
from .device import BlockDevice
|
||||||
from ..result import DiskoError, DiskoResult, DiskoSuccess
|
from ..result import DiskoError, DiskoResult, DiskoSuccess
|
||||||
|
from ..json_types import JsonDict
|
||||||
|
|
||||||
|
|
||||||
def _add_type_if_required(
|
def _add_type_if_required(device: BlockDevice, part_config: JsonDict) -> JsonDict:
|
||||||
device: BlockDevice, part_config: dict[str, Any]
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
type = {
|
type = {
|
||||||
"c12a7328-f81f-11d2-ba4b-00a0c93ec93b": "EF00", # EFI System
|
"c12a7328-f81f-11d2-ba4b-00a0c93ec93b": "EF00", # EFI System
|
||||||
"21686148-6449-6e6f-744e-656564454649": "EF02", # BIOS boot
|
"21686148-6449-6e6f-744e-656564454649": "EF02", # BIOS boot
|
||||||
@@ -26,22 +24,22 @@ def _generate_name(device: BlockDevice) -> str:
|
|||||||
return f"PARTUUID:{device.partuuid}"
|
return f"PARTUUID:{device.partuuid}"
|
||||||
|
|
||||||
|
|
||||||
def _generate_content(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
def _generate_content(device: BlockDevice) -> DiskoResult[JsonDict]:
|
||||||
match device.fstype:
|
match device.fstype:
|
||||||
# TODO: Add filesystems that are not supported by `mkfs` here
|
# TODO: Add filesystems that are not supported by `mkfs` here
|
||||||
case _:
|
case _:
|
||||||
return filesystem.generate_config(device)
|
return filesystem.generate_config(device)
|
||||||
|
|
||||||
|
|
||||||
def generate_config(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
def generate_config(device: BlockDevice) -> DiskoResult[JsonDict]:
|
||||||
assert (
|
assert (
|
||||||
device.pttype == "gpt"
|
device.pttype == "gpt"
|
||||||
), f"BUG! gpt.generate_config called with non-gpt device {device.path}"
|
), f"BUG! gpt.generate_config called with non-gpt device {device.path}"
|
||||||
|
|
||||||
debug(f"Generating GPT config for device {device.path}")
|
debug(f"Generating GPT config for device {device.path}")
|
||||||
|
|
||||||
partitions = {}
|
partitions: JsonDict = {}
|
||||||
error_messages = []
|
error = DiskoError([], "generate gpt config")
|
||||||
failed_partitions = []
|
failed_partitions = []
|
||||||
successful_partitions = []
|
successful_partitions = []
|
||||||
|
|
||||||
@@ -49,7 +47,7 @@ def generate_config(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
|||||||
content = _generate_content(partition)
|
content = _generate_content(partition)
|
||||||
|
|
||||||
if isinstance(content, DiskoError):
|
if isinstance(content, DiskoError):
|
||||||
error_messages.extend(content.messages)
|
error.extend(content)
|
||||||
failed_partitions.append(partition.path)
|
failed_partitions.append(partition.path)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -61,4 +59,4 @@ def generate_config(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
|||||||
if not failed_partitions:
|
if not failed_partitions:
|
||||||
return DiskoSuccess({"partitions": partitions}, "generate gpt config")
|
return DiskoSuccess({"partitions": partitions}, "generate gpt config")
|
||||||
|
|
||||||
return DiskoError(error_messages, "generate gpt config")
|
return error
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
from disko_lib.eval_config import eval_config
|
from disko_lib.eval_config import eval_config
|
||||||
from disko_lib.messages.msgs import err_missing_arguments, err_too_many_arguments
|
from disko_lib.messages.msgs import err_missing_arguments, err_too_many_arguments
|
||||||
from disko_lib.result import DiskoError, DiskoSuccess
|
from disko_lib.result import DiskoError, DiskoSuccess
|
||||||
|
from disko_lib.json_types import JsonDict
|
||||||
|
|
||||||
CURRENT_DIR = Path(__file__).parent
|
CURRENT_DIR = Path(__file__).parent
|
||||||
ROOT_DIR = CURRENT_DIR.parent.parent.parent
|
ROOT_DIR = CURRENT_DIR.parent.parent.parent
|
||||||
@@ -13,14 +15,14 @@ assert (ROOT_DIR / "flake.nix").exists()
|
|||||||
def test_eval_config_missing_arguments() -> None:
|
def test_eval_config_missing_arguments() -> None:
|
||||||
result = eval_config(disko_file=None, flake=None)
|
result = eval_config(disko_file=None, flake=None)
|
||||||
assert isinstance(result, DiskoError)
|
assert isinstance(result, DiskoError)
|
||||||
assert result.messages[0].factory == err_missing_arguments
|
assert result.messages[0].is_message(err_missing_arguments)
|
||||||
assert result.context == "validate args"
|
assert result.context == "validate args"
|
||||||
|
|
||||||
|
|
||||||
def test_eval_config_too_many_arguments() -> None:
|
def test_eval_config_too_many_arguments() -> None:
|
||||||
result = eval_config(disko_file="foo", flake="bar")
|
result = eval_config(disko_file="foo", flake="bar")
|
||||||
assert isinstance(result, DiskoError)
|
assert isinstance(result, DiskoError)
|
||||||
assert result.messages[0].factory == err_too_many_arguments
|
assert result.messages[0].is_message(err_too_many_arguments)
|
||||||
assert result.context == "validate args"
|
assert result.context == "validate args"
|
||||||
|
|
||||||
|
|
||||||
@@ -29,7 +31,7 @@ def test_eval_config_disk_file() -> None:
|
|||||||
result = eval_config(disko_file=str(disko_file_path), flake=None)
|
result = eval_config(disko_file=str(disko_file_path), flake=None)
|
||||||
assert isinstance(result, DiskoSuccess)
|
assert isinstance(result, DiskoSuccess)
|
||||||
with open(CURRENT_DIR / "file-simple-efi-result.json") as f:
|
with open(CURRENT_DIR / "file-simple-efi-result.json") as f:
|
||||||
expected_result = json.load(f)
|
expected_result = cast(JsonDict, json.load(f))
|
||||||
assert result.value == expected_result
|
assert result.value == expected_result
|
||||||
|
|
||||||
|
|
||||||
@@ -37,5 +39,5 @@ def test_eval_config_flake_testmachine() -> None:
|
|||||||
result = eval_config(disko_file=None, flake=f"{ROOT_DIR}#testmachine")
|
result = eval_config(disko_file=None, flake=f"{ROOT_DIR}#testmachine")
|
||||||
assert isinstance(result, DiskoSuccess)
|
assert isinstance(result, DiskoSuccess)
|
||||||
with open(CURRENT_DIR / "flake-testmachine-result.json") as f:
|
with open(CURRENT_DIR / "flake-testmachine-result.json") as f:
|
||||||
expected_result = json.load(f)
|
expected_result = cast(JsonDict, json.load(f))
|
||||||
assert result.value == expected_result
|
assert result.value == expected_result
|
||||||
@@ -1,14 +1,15 @@
|
|||||||
from disko_lib.dict_diff import dict_diff
|
from disko_lib.dict_diff import dict_diff
|
||||||
|
from disko_lib.json_types import JsonDict
|
||||||
|
|
||||||
|
|
||||||
def test_dict_diff_basic() -> None:
|
def test_dict_diff_basic() -> None:
|
||||||
left = {
|
left: JsonDict = {
|
||||||
"a": 1,
|
"a": 1,
|
||||||
"b": 2,
|
"b": 2,
|
||||||
"c": 3,
|
"c": 3,
|
||||||
"d": 4,
|
"d": 4,
|
||||||
}
|
}
|
||||||
right = {
|
right: JsonDict = {
|
||||||
"a": 1,
|
"a": 1,
|
||||||
"b": 3,
|
"b": 3,
|
||||||
"c": 4,
|
"c": 4,
|
||||||
@@ -39,12 +40,12 @@ def test_dict_diff_basic() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_dict_diff_arrays() -> None:
|
def test_dict_diff_arrays() -> None:
|
||||||
left = {
|
left: JsonDict = {
|
||||||
"a": [1, 2, 3],
|
"a": [1, 2, 3],
|
||||||
"b": [4, 5, 6],
|
"b": [4, 5, 6],
|
||||||
"c": [7, 8, 9],
|
"c": [7, 8, 9],
|
||||||
}
|
}
|
||||||
right = {
|
right: JsonDict = {
|
||||||
"a": [1, 2, 3],
|
"a": [1, 2, 3],
|
||||||
"b": [4, 5, 7],
|
"b": [4, 5, 7],
|
||||||
"c": [7, 8, 9],
|
"c": [7, 8, 9],
|
||||||
@@ -69,7 +70,7 @@ def test_dict_diff_arrays() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_dict_diff_nested() -> None:
|
def test_dict_diff_nested() -> None:
|
||||||
left = {
|
left: JsonDict = {
|
||||||
"a": {
|
"a": {
|
||||||
"b": {
|
"b": {
|
||||||
"c": 1,
|
"c": 1,
|
||||||
@@ -87,7 +88,7 @@ def test_dict_diff_nested() -> None:
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
right = {
|
right: JsonDict = {
|
||||||
"a": {
|
"a": {
|
||||||
"b": {
|
"b": {
|
||||||
"c": 1,
|
"c": 1,
|
||||||
|
|||||||
@@ -19,15 +19,15 @@ def test_generate_config_partial_failure_dos_table() -> None:
|
|||||||
|
|
||||||
assert isinstance(result, DiskoError)
|
assert isinstance(result, DiskoError)
|
||||||
|
|
||||||
assert result.messages[0].factory == err_unsupported_pttype
|
assert result.messages[0].is_message(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].factory == warn_generate_partial_failure
|
assert result.messages[1].is_message(warn_generate_partial_failure)
|
||||||
with open(CURRENT_DIR / "partial_failure_dos_table-generate-result.json") as f:
|
with open(CURRENT_DIR / "partial_failure_dos_table-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) # type: ignore[misc]
|
||||||
assert result.messages[1].details["failed_devices"] == [PosixPath("/dev/sdc")]
|
assert result.messages[1].details["failed_devices"] == [PosixPath("/dev/sdc")]
|
||||||
assert result.messages[1].details["successful_devices"] == [
|
assert result.messages[1].details["successful_devices"] == [
|
||||||
PosixPath("/dev/sda"),
|
PosixPath("/dev/sda"),
|
||||||
|
|||||||
Reference in new issue
Block a user