mirror of
https://github.com/nix-community/disko.git
synced 2026-11-30 13:03:28 +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": [
|
||||
"./src"
|
||||
]
|
||||
],
|
||||
"mypy-type-checker.importStrategy": "fromEnvironment"
|
||||
}
|
||||
+1
-1
@@ -42,9 +42,9 @@ warn_return_any = true
|
||||
warn_unreachable = true
|
||||
# Miscellaneous strictness flags
|
||||
no_implicit_reexport = true
|
||||
strict_concatenate = true
|
||||
strict_equality = true
|
||||
extra_checks = true
|
||||
enable_error_code = "ignore-without-code"
|
||||
# Error message control
|
||||
show_error_context = true
|
||||
show_error_code_links = true
|
||||
|
||||
@@ -3,12 +3,19 @@
|
||||
import io
|
||||
import json
|
||||
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(
|
||||
type_field: dict[str, Any]
|
||||
) -> TypeGuard[dict[Literal["default", "description", "type"], Any]]:
|
||||
class TypeDefinition(TypedDict):
|
||||
type: str | JsonDict
|
||||
default: JsonValue
|
||||
description: str
|
||||
|
||||
|
||||
def is_type(type_field: JsonValue) -> TypeGuard[TypeDefinition]:
|
||||
if not isinstance(type_field, dict):
|
||||
return False
|
||||
return set(type_field.keys()) == {"default", "description", "type"}
|
||||
@@ -111,7 +118,7 @@ def _parse_simple_type(type_str: str) -> str:
|
||||
|
||||
|
||||
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]:
|
||||
if isinstance(field, str):
|
||||
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
|
||||
|
||||
|
||||
def transform_dict_keys(
|
||||
d: dict[str, Any], transform_fn: Callable[[str], str]
|
||||
) -> dict[str, Any]:
|
||||
T = TypeVar("T", bound=JsonValue)
|
||||
|
||||
|
||||
def transform_dict_keys(d: T, transform_fn: Callable[[str], str]) -> T:
|
||||
if not isinstance(d, Mapping):
|
||||
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)
|
||||
|
||||
# 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.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 pydantic import BaseModel
|
||||
|
||||
@@ -204,6 +219,7 @@ from pydantic import BaseModel
|
||||
)
|
||||
|
||||
for type_name, fields in schema.items():
|
||||
assert isinstance(fields, dict)
|
||||
if "__isCompositeType" in fields:
|
||||
try:
|
||||
alias_content, type_code = _parse_composite_type(type_name, "", fields)
|
||||
|
||||
+7
-7
@@ -2,7 +2,7 @@
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from typing import Any, Literal
|
||||
from typing import Any, Literal, cast
|
||||
|
||||
from disko.mode_dev import run_dev
|
||||
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.messages.msgs import err_missing_mode
|
||||
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[
|
||||
"destroy",
|
||||
@@ -46,18 +46,18 @@ MODE_DESCRIPTION: dict[Mode, str] = {
|
||||
|
||||
def run_apply(
|
||||
*, 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)
|
||||
|
||||
|
||||
def run(
|
||||
args: argparse.Namespace,
|
||||
) -> DiskoResult[None | dict[str, Any]]:
|
||||
if args.verbose:
|
||||
) -> DiskoResult[None | JsonDict]:
|
||||
if cast(bool, args.verbose):
|
||||
LOGGER.setLevel("DEBUG")
|
||||
debug("Enabled debug logging.")
|
||||
|
||||
match args.mode:
|
||||
match cast(Mode | None, args.mode):
|
||||
case None:
|
||||
return DiskoError.single_message(
|
||||
err_missing_mode, "select mode", valid_modes=[str(m) for m in ALL_MODES]
|
||||
@@ -67,7 +67,7 @@ def run(
|
||||
case "dev":
|
||||
return run_dev(args)
|
||||
case _:
|
||||
return run_apply(**vars(args))
|
||||
return run_apply(**vars(args)) # type: ignore[misc]
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import argparse
|
||||
import json
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
|
||||
from disko_lib.ansi import Colors
|
||||
from disko_lib.eval_config import eval_config
|
||||
@@ -22,8 +22,8 @@ def run_dev_ansi() -> DiskoResult[None]:
|
||||
import inspect
|
||||
|
||||
for name, value in inspect.getmembers(Colors):
|
||||
if value != "_" and not name.startswith("_") and name != "RESET":
|
||||
print("{:>30} {}".format(name, value + name + Colors.RESET))
|
||||
if value != "_" and not name.startswith("_") and name != "RESET": # type: ignore[misc]
|
||||
print("{:>30} {}".format(name, value + name + Colors.RESET)) # type: ignore[misc]
|
||||
|
||||
return DiskoSuccess(None, "run disko dev ansi")
|
||||
|
||||
@@ -41,13 +41,13 @@ def run_dev_eval(
|
||||
|
||||
|
||||
def run_dev(args: argparse.Namespace) -> DiskoResult[None]:
|
||||
match args.dev_command:
|
||||
match cast(str | None, args.dev_command):
|
||||
case "lsblk":
|
||||
return run_dev_lsblk()
|
||||
case "ansi":
|
||||
return run_dev_ansi()
|
||||
case "eval":
|
||||
return run_dev_eval(**vars(args))
|
||||
return run_dev_eval(**vars(args)) # type: ignore[misc]
|
||||
case _:
|
||||
return DiskoError.single_message(
|
||||
err_missing_mode, "select mode", valid_modes=["lsblk", "ansi", "eval"]
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
from disko_lib.logging import info
|
||||
from disko_lib.messages.msgs import warn_generate_partial_failure
|
||||
from disko_lib.result import DiskoResult, DiskoError
|
||||
from disko_lib.types.disk import generate_config
|
||||
from disko_lib.run_cmd import run
|
||||
from disko_lib.json_types import JsonDict
|
||||
|
||||
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 = None
|
||||
|
||||
|
||||
+11
-5
@@ -3,6 +3,8 @@
|
||||
# Inspired by rene-d's colors.py, published in 2018
|
||||
# See https://gist.github.com/rene-d/9e584a7dd2935d0f461904b9f2950007
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
class Colors:
|
||||
"""
|
||||
@@ -163,13 +165,17 @@ class Colors:
|
||||
ATTR_STRIKE = "\033[9m"
|
||||
|
||||
# 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():
|
||||
if isinstance(_, str) and _[0] != "_":
|
||||
locals()[_] = ""
|
||||
locals()[_] = "" # type: ignore[misc]
|
||||
else:
|
||||
import platform
|
||||
|
||||
# set Windows console in VT mode
|
||||
if __import__("platform").system() == "Windows":
|
||||
kernel32 = __import__("ctypes").windll.kernel32
|
||||
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
|
||||
if platform.system() == "Windows":
|
||||
import ctypes
|
||||
|
||||
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined, misc]
|
||||
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7) # type: ignore[misc]
|
||||
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 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`
|
||||
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}})
|
||||
{'a': {'b': 3}, 'c': {'d': 4, '_new': True}}
|
||||
"""
|
||||
new_dict: dict[str, Any] = {}
|
||||
new_dict: JsonDict = {}
|
||||
|
||||
for k, right_val in right.items():
|
||||
left_val = left.get(k)
|
||||
@@ -32,12 +32,17 @@ def dict_diff(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
|
||||
continue
|
||||
|
||||
if not isinstance(right_val, dict):
|
||||
new_dict[k] = right[k]
|
||||
new_dict[k] = right_val
|
||||
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:
|
||||
new_dict[k]["_new"] = True
|
||||
diffed_right_val["_new"] = True
|
||||
|
||||
new_dict[k] = diffed_right_val
|
||||
|
||||
for k, left_val in left.items():
|
||||
if k not in right:
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
from typing import cast
|
||||
|
||||
from .json_types import JsonDict
|
||||
|
||||
from disko_lib.messages.msgs import (
|
||||
err_eval_config_failed,
|
||||
@@ -30,7 +32,7 @@ assert (
|
||||
), 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)
|
||||
|
||||
result = run(
|
||||
@@ -43,14 +45,16 @@ def _eval_config(args: dict[str, str]) -> DiskoResult[dict[str, Any]]:
|
||||
err_eval_config_failed,
|
||||
"evaluate disko configuration",
|
||||
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
|
||||
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()
|
||||
|
||||
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)})
|
||||
|
||||
|
||||
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
|
||||
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
|
||||
assert flake_match is not None
|
||||
|
||||
flake = flake_match.group(1)
|
||||
flake_attr = flake_match.group(2)
|
||||
flake = cast(str, flake_match.group(1))
|
||||
flake_attr = cast(str, flake_match.group(2))
|
||||
|
||||
if not flake_attr:
|
||||
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})
|
||||
|
||||
|
||||
def eval_config(
|
||||
*, disko_file: str | None, flake: str | None
|
||||
) -> DiskoResult[dict[str, Any]]:
|
||||
def eval_config(*, disko_file: str | None, flake: str | None) -> DiskoResult[JsonDict]:
|
||||
# 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")
|
||||
|
||||
@@ -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,
|
||||
ParamSpec,
|
||||
TypeAlias,
|
||||
cast,
|
||||
)
|
||||
|
||||
from .ansi import Colors
|
||||
@@ -68,16 +69,16 @@ MessageFactory: TypeAlias = Callable[P, ReadableMessage | list[ReadableMessage]]
|
||||
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]
|
||||
details: dict[str, object]
|
||||
|
||||
def __init__(self, factory: MessageFactory[P], **details: P.kwargs) -> None:
|
||||
self.factory = factory
|
||||
self.details = details
|
||||
|
||||
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):
|
||||
return result
|
||||
return [result]
|
||||
@@ -86,6 +87,9 @@ class DiskoMessage(Generic[P]):
|
||||
for msg in self.to_readable():
|
||||
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.
|
||||
# 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]:
|
||||
spaces_prefix_match = re.match(r"^( *)", lines[0])
|
||||
# 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))
|
||||
dedent_width = len(spaces_prefix_match.group(1)) # type: ignore[union-attr, misc]
|
||||
|
||||
if dedent_width == 0:
|
||||
return lines
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from typing import Any
|
||||
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 [
|
||||
ReadableMessage(
|
||||
"bug",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from disko_lib.logging import ReadableMessage
|
||||
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 \
|
||||
{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(
|
||||
"error",
|
||||
f"""
|
||||
@@ -83,7 +83,7 @@ def err_unsupported_pttype(*, device: Path, pttype: str) -> ReadableMessage:
|
||||
|
||||
def warn_generate_partial_failure(
|
||||
*,
|
||||
partial_config: dict[Any, str],
|
||||
partial_config: JsonDict,
|
||||
failed_devices: list[str],
|
||||
successful_devices: list[str],
|
||||
) -> list[ReadableMessage]:
|
||||
|
||||
+12
-5
@@ -1,5 +1,5 @@
|
||||
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
|
||||
|
||||
@@ -18,7 +18,7 @@ class DiskoSuccess(Generic[T]):
|
||||
|
||||
@dataclass
|
||||
class DiskoError:
|
||||
messages: list[DiskoMessage[Any]]
|
||||
messages: list[DiskoMessage[object]]
|
||||
context: str
|
||||
success: Literal[False] = False
|
||||
|
||||
@@ -26,18 +26,25 @@ class DiskoError:
|
||||
def single_message(
|
||||
cls, factory: MessageFactory[P], context: str, *_: P.args, **details: P.kwargs
|
||||
) -> "DiskoError":
|
||||
return cls([DiskoMessage(factory, **details)], context)
|
||||
_factory = cast(MessageFactory[object], factory)
|
||||
return cls([DiskoMessage(_factory, **details)], context)
|
||||
|
||||
def find_message(
|
||||
self, message_factory: MessageFactory[P]
|
||||
) -> None | DiskoMessage[P]:
|
||||
for message in self.messages:
|
||||
if message.factory == message_factory:
|
||||
return message
|
||||
return cast(DiskoMessage[P], message)
|
||||
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:
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
import typing
|
||||
|
||||
from ..result import DiskoError, DiskoResult, DiskoSuccess
|
||||
from ..run_cmd import run
|
||||
from ..json_types import JsonDict
|
||||
|
||||
# To see what other fields are available in the lsblk output and what
|
||||
# sort of values you can expect from them, run:
|
||||
@@ -68,14 +70,16 @@ class BlockDevice:
|
||||
children: list["BlockDevice"]
|
||||
|
||||
@classmethod
|
||||
def from_json_dict(cls, json_dict: dict[str, Any]) -> "BlockDevice":
|
||||
children = [
|
||||
cls.from_json_dict(child_dict)
|
||||
for child_dict in json_dict.get("children", [])
|
||||
]
|
||||
def from_json_dict(cls, json_dict: JsonDict) -> "BlockDevice":
|
||||
children_list = json_dict.get("children", [])
|
||||
assert isinstance(children_list, list)
|
||||
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
|
||||
mountpoints = json_dict["mountpoints"] or []
|
||||
mountpoints = cast(list[str], json_dict["mountpoints"]) or []
|
||||
if not any(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.
|
||||
return cls(
|
||||
children=children,
|
||||
id_link=json_dict["id-link"],
|
||||
fstype=json_dict["fstype"] or "",
|
||||
fssize=json_dict["fssize"] or "",
|
||||
fsuse_pct=json_dict["fsuse%"] or "",
|
||||
kname=json_dict["kname"],
|
||||
label=json_dict["label"] or "",
|
||||
model=json_dict["model"] or "",
|
||||
partflags=json_dict["partflags"] or "",
|
||||
partlabel=json_dict["partlabel"] or "",
|
||||
partn=json_dict["partn"],
|
||||
parttype=json_dict["parttype"] or "",
|
||||
parttypename=json_dict["parttypename"] or "",
|
||||
partuuid=json_dict["partuuid"] or "",
|
||||
path=Path(json_dict["path"]),
|
||||
phy_sec=json_dict["phy-sec"],
|
||||
pttype=json_dict["pttype"],
|
||||
rev=json_dict["rev"] or "",
|
||||
serial=json_dict["serial"] or "",
|
||||
size=json_dict["size"],
|
||||
start=json_dict["start"] or "",
|
||||
mountpoint=json_dict["mountpoint"] or "",
|
||||
id_link=cast(str, json_dict["id-link"]),
|
||||
fstype=cast(str, json_dict["fstype"]) or "",
|
||||
fssize=cast(str, json_dict["fssize"]) or "",
|
||||
fsuse_pct=cast(str, json_dict["fsuse%"]) or "",
|
||||
kname=cast(str, json_dict["kname"]),
|
||||
label=cast(str, json_dict["label"]) or "",
|
||||
model=cast(str, json_dict["model"]) or "",
|
||||
partflags=cast(str, json_dict["partflags"]) or "",
|
||||
partlabel=cast(str, json_dict["partlabel"]) or "",
|
||||
partn=cast(int, json_dict["partn"]),
|
||||
parttype=cast(str, json_dict["parttype"]) or "",
|
||||
parttypename=cast(str, json_dict["parttypename"]) or "",
|
||||
partuuid=cast(str, json_dict["partuuid"]) or "",
|
||||
path=Path(cast(str, json_dict["path"])),
|
||||
phy_sec=cast(int, json_dict["phy-sec"]),
|
||||
pttype=cast(str, json_dict["pttype"]),
|
||||
rev=cast(str, json_dict["rev"]) or "",
|
||||
serial=cast(str, json_dict["serial"]) or "",
|
||||
size=cast(str, json_dict["size"]),
|
||||
start=cast(str, json_dict["start"]) or "",
|
||||
mountpoint=cast(str, json_dict["mountpoint"]) or "",
|
||||
mountpoints=mountpoints,
|
||||
type=json_dict["type"],
|
||||
uuid=json_dict["uuid"] or "",
|
||||
type=cast(str, json_dict["type"]),
|
||||
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
|
||||
|
||||
# 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]
|
||||
|
||||
|
||||
+17
-22
@@ -1,5 +1,4 @@
|
||||
from typing import Any
|
||||
|
||||
from typing import cast
|
||||
from disko_lib.messages.msgs import (
|
||||
err_unsupported_pttype,
|
||||
warn_generate_partial_failure,
|
||||
@@ -8,10 +7,11 @@ from disko_lib.messages.msgs import (
|
||||
from ..logging import DiskoMessage, debug
|
||||
from ..result import DiskoError, DiskoResult, DiskoSuccess
|
||||
from ..types.device import BlockDevice, list_block_devices
|
||||
from ..json_types import JsonDict
|
||||
from . import gpt
|
||||
|
||||
|
||||
def _generate_content(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
||||
def _generate_content(device: BlockDevice) -> DiskoResult[JsonDict]:
|
||||
match device.pttype:
|
||||
case "gpt":
|
||||
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
|
||||
if not 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
|
||||
|
||||
if isinstance(block_devices, DiskoError):
|
||||
return block_devices
|
||||
|
||||
debug(f"Generating config for devices {[d.path for d in block_devices]}")
|
||||
|
||||
disks = {}
|
||||
error_messages = []
|
||||
disks: JsonDict = {}
|
||||
error = DiskoError([], "generate disk config")
|
||||
failed_devices = []
|
||||
successful_devices = []
|
||||
|
||||
@@ -48,7 +45,7 @@ def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[dict[str, An
|
||||
content = _generate_content(device)
|
||||
|
||||
if isinstance(content, DiskoError):
|
||||
error_messages.extend(content.messages)
|
||||
error.extend(content)
|
||||
failed_devices.append(device.path)
|
||||
continue
|
||||
|
||||
@@ -59,21 +56,19 @@ def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[dict[str, An
|
||||
}
|
||||
successful_devices.append(device.path)
|
||||
|
||||
config: JsonDict = {"disks": disks}
|
||||
|
||||
if not failed_devices:
|
||||
return DiskoSuccess({"disks": disks}, "generate disk config")
|
||||
return DiskoSuccess(config, "generate disk config")
|
||||
|
||||
if not successful_devices:
|
||||
return DiskoError(error_messages, "generate disk config")
|
||||
|
||||
return DiskoError(
|
||||
error_messages
|
||||
+ [
|
||||
if successful_devices:
|
||||
error.append(
|
||||
DiskoMessage(
|
||||
warn_generate_partial_failure,
|
||||
partial_config={"disks": disks},
|
||||
partial_config=config,
|
||||
failed_devices=failed_devices,
|
||||
successful_devices=successful_devices,
|
||||
)
|
||||
],
|
||||
"generate disk config",
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
return error
|
||||
@@ -1,9 +1,9 @@
|
||||
from typing import Any
|
||||
from .device import BlockDevice
|
||||
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 (
|
||||
device.type == "part"
|
||||
), 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 . import filesystem
|
||||
from .device import BlockDevice
|
||||
from ..result import DiskoError, DiskoResult, DiskoSuccess
|
||||
from ..json_types import JsonDict
|
||||
|
||||
|
||||
def _add_type_if_required(
|
||||
device: BlockDevice, part_config: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
def _add_type_if_required(device: BlockDevice, part_config: JsonDict) -> JsonDict:
|
||||
type = {
|
||||
"c12a7328-f81f-11d2-ba4b-00a0c93ec93b": "EF00", # EFI System
|
||||
"21686148-6449-6e6f-744e-656564454649": "EF02", # BIOS boot
|
||||
@@ -26,22 +24,22 @@ def _generate_name(device: BlockDevice) -> str:
|
||||
return f"PARTUUID:{device.partuuid}"
|
||||
|
||||
|
||||
def _generate_content(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
||||
def _generate_content(device: BlockDevice) -> DiskoResult[JsonDict]:
|
||||
match device.fstype:
|
||||
# TODO: Add filesystems that are not supported by `mkfs` here
|
||||
case _:
|
||||
return filesystem.generate_config(device)
|
||||
|
||||
|
||||
def generate_config(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
||||
def generate_config(device: BlockDevice) -> DiskoResult[JsonDict]:
|
||||
assert (
|
||||
device.pttype == "gpt"
|
||||
), f"BUG! gpt.generate_config called with non-gpt device {device.path}"
|
||||
|
||||
debug(f"Generating GPT config for device {device.path}")
|
||||
|
||||
partitions = {}
|
||||
error_messages = []
|
||||
partitions: JsonDict = {}
|
||||
error = DiskoError([], "generate gpt config")
|
||||
failed_partitions = []
|
||||
successful_partitions = []
|
||||
|
||||
@@ -49,7 +47,7 @@ def generate_config(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
||||
content = _generate_content(partition)
|
||||
|
||||
if isinstance(content, DiskoError):
|
||||
error_messages.extend(content.messages)
|
||||
error.extend(content)
|
||||
failed_partitions.append(partition.path)
|
||||
continue
|
||||
|
||||
@@ -61,4 +59,4 @@ def generate_config(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
||||
if not failed_partitions:
|
||||
return DiskoSuccess({"partitions": partitions}, "generate gpt config")
|
||||
|
||||
return DiskoError(error_messages, "generate gpt config")
|
||||
return error
|
||||
@@ -1,9 +1,11 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
from disko_lib.eval_config import eval_config
|
||||
from disko_lib.messages.msgs import err_missing_arguments, err_too_many_arguments
|
||||
from disko_lib.result import DiskoError, DiskoSuccess
|
||||
from disko_lib.json_types import JsonDict
|
||||
|
||||
CURRENT_DIR = Path(__file__).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:
|
||||
result = eval_config(disko_file=None, flake=None)
|
||||
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"
|
||||
|
||||
|
||||
def test_eval_config_too_many_arguments() -> None:
|
||||
result = eval_config(disko_file="foo", flake="bar")
|
||||
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"
|
||||
|
||||
|
||||
@@ -29,7 +31,7 @@ def test_eval_config_disk_file() -> None:
|
||||
result = eval_config(disko_file=str(disko_file_path), flake=None)
|
||||
assert isinstance(result, DiskoSuccess)
|
||||
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
|
||||
|
||||
|
||||
@@ -37,5 +39,5 @@ def test_eval_config_flake_testmachine() -> None:
|
||||
result = eval_config(disko_file=None, flake=f"{ROOT_DIR}#testmachine")
|
||||
assert isinstance(result, DiskoSuccess)
|
||||
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
|
||||
@@ -1,14 +1,15 @@
|
||||
from disko_lib.dict_diff import dict_diff
|
||||
from disko_lib.json_types import JsonDict
|
||||
|
||||
|
||||
def test_dict_diff_basic() -> None:
|
||||
left = {
|
||||
left: JsonDict = {
|
||||
"a": 1,
|
||||
"b": 2,
|
||||
"c": 3,
|
||||
"d": 4,
|
||||
}
|
||||
right = {
|
||||
right: JsonDict = {
|
||||
"a": 1,
|
||||
"b": 3,
|
||||
"c": 4,
|
||||
@@ -39,12 +40,12 @@ def test_dict_diff_basic() -> None:
|
||||
|
||||
|
||||
def test_dict_diff_arrays() -> None:
|
||||
left = {
|
||||
left: JsonDict = {
|
||||
"a": [1, 2, 3],
|
||||
"b": [4, 5, 6],
|
||||
"c": [7, 8, 9],
|
||||
}
|
||||
right = {
|
||||
right: JsonDict = {
|
||||
"a": [1, 2, 3],
|
||||
"b": [4, 5, 7],
|
||||
"c": [7, 8, 9],
|
||||
@@ -69,7 +70,7 @@ def test_dict_diff_arrays() -> None:
|
||||
|
||||
|
||||
def test_dict_diff_nested() -> None:
|
||||
left = {
|
||||
left: JsonDict = {
|
||||
"a": {
|
||||
"b": {
|
||||
"c": 1,
|
||||
@@ -87,7 +88,7 @@ def test_dict_diff_nested() -> None:
|
||||
},
|
||||
},
|
||||
}
|
||||
right = {
|
||||
right: JsonDict = {
|
||||
"a": {
|
||||
"b": {
|
||||
"c": 1,
|
||||
|
||||
@@ -19,15 +19,15 @@ def test_generate_config_partial_failure_dos_table() -> None:
|
||||
|
||||
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 == {
|
||||
"pttype": "dos",
|
||||
"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:
|
||||
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["successful_devices"] == [
|
||||
PosixPath("/dev/sda"),
|
||||
|
||||
Reference in new issue
Block a user