mirror of
https://github.com/nix-community/disko.git
synced 2026-12-02 22:13:28 +01:00
disko2: Add evaluation for configs and flakes
This commit is contained in:
1 parent
ed506048a4
commit
8acd24950d
8 files changed
+277
-27
No files matched your search
Vendored
+13
-1
@@ -5,7 +5,7 @@
|
|||||||
"version": "0.2.0",
|
"version": "0.2.0",
|
||||||
"configurations": [
|
"configurations": [
|
||||||
{
|
{
|
||||||
"name": "Python Debugger: disko2",
|
"name": "disko2 mount disko_file",
|
||||||
"type": "debugpy",
|
"type": "debugpy",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "${workspaceFolder}/disko2",
|
"program": "${workspaceFolder}/disko2",
|
||||||
@@ -14,6 +14,18 @@
|
|||||||
"mount",
|
"mount",
|
||||||
"example/simple-efi.nix"
|
"example/simple-efi.nix"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "disko2 mount flake",
|
||||||
|
"type": "debugpy",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${workspaceFolder}/disko2",
|
||||||
|
"console": "integratedTerminal",
|
||||||
|
"args": [
|
||||||
|
"mount",
|
||||||
|
"--flake",
|
||||||
|
".#testmachine"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -17,6 +17,7 @@ let
|
|||||||
};
|
};
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
|
inherit eval;
|
||||||
lib = lib.warn "the .lib.lib output is deprecated" diskoLib;
|
lib = lib.warn "the .lib.lib output is deprecated" diskoLib;
|
||||||
|
|
||||||
# legacy alias
|
# legacy alias
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Literal, Union
|
from typing import Any, Literal
|
||||||
|
|
||||||
from lib.logging import LOGGER, DiskoMessage, debug, info
|
from lib.eval_config import eval_disko_file, eval_flake
|
||||||
|
from lib.logging import LOGGER, debug, info
|
||||||
from lib.result import DiskoError, DiskoSuccess, DiskoResult, exit_on_error
|
from lib.result import DiskoError, DiskoSuccess, DiskoResult, exit_on_error
|
||||||
|
|
||||||
Mode = Literal[
|
Mode = Literal[
|
||||||
@@ -33,21 +35,17 @@ MODE_DESCRIPTION: dict[Mode, str] = {
|
|||||||
|
|
||||||
|
|
||||||
def run_apply(
|
def run_apply(
|
||||||
*, mode: str, disko_file: Path | None, flake: str | None
|
*, mode: str, disko_file: str | None, flake: str | None, **_kwargs: dict[str, Any]
|
||||||
) -> DiskoResult[dict[str, Any]]:
|
) -> DiskoResult[dict[str, Any]]:
|
||||||
if flake is None and disko_file is None:
|
# match would be nicer, but mypy doesn't understand type narrowing in tuples
|
||||||
return DiskoError([DiskoMessage("ERR_MISSING_ARGUMENTS")], "validate args")
|
if not disko_file and not flake:
|
||||||
if flake is not None and disko_file is not None:
|
return DiskoError.single_message("ERR_MISSING_ARGUMENTS", {}, "validate args")
|
||||||
return DiskoError([DiskoMessage("ERR_TOO_MANY_ARGUMENTS")], "validate args")
|
if not disko_file and flake:
|
||||||
|
return eval_flake(flake)
|
||||||
|
if disko_file and not flake:
|
||||||
|
return eval_disko_file(Path(disko_file))
|
||||||
|
|
||||||
return DiskoSuccess(
|
return DiskoError.single_message("ERR_TOO_MANY_ARGUMENTS", {}, "validate args")
|
||||||
{
|
|
||||||
"mode": mode,
|
|
||||||
"disko_file": disko_file,
|
|
||||||
"flake": flake,
|
|
||||||
},
|
|
||||||
"apply configuration",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def run_generate() -> DiskoResult[Literal["generate"]]:
|
def run_generate() -> DiskoResult[Literal["generate"]]:
|
||||||
@@ -57,14 +55,13 @@ def run_generate() -> DiskoResult[Literal["generate"]]:
|
|||||||
def run(
|
def run(
|
||||||
args: argparse.Namespace,
|
args: argparse.Namespace,
|
||||||
) -> DiskoResult[Literal["generate"] | dict[str, Any]]:
|
) -> DiskoResult[Literal["generate"] | dict[str, Any]]:
|
||||||
if args.verbose == True:
|
if args.verbose:
|
||||||
LOGGER.setLevel("DEBUG")
|
LOGGER.setLevel("DEBUG")
|
||||||
debug("Enabled debug logging.")
|
debug("Enabled debug logging.")
|
||||||
|
|
||||||
if args.mode == None:
|
if not args.mode:
|
||||||
return DiskoError(
|
return DiskoError.single_message(
|
||||||
[DiskoMessage("ERR_MISSING_MODE", {"valid_modes": ALL_MODES})],
|
"ERR_MISSING_MODE", {"valid_modes": ALL_MODES}, "select mode"
|
||||||
"select mode",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if args.mode == "generate":
|
if args.mode == "generate":
|
||||||
@@ -122,7 +119,7 @@ def main() -> None:
|
|||||||
args = parse_args()
|
args = parse_args()
|
||||||
result = run(args)
|
result = run(args)
|
||||||
output = exit_on_error(result)
|
output = exit_on_error(result)
|
||||||
info(str(output))
|
info("Output:\n" + json.dumps(output, indent=2))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
{ pkgs ? import <nixpkgs> { }
|
||||||
|
, lib ? pkgs.lib
|
||||||
|
, flake ? null
|
||||||
|
, flakeAttr ? null
|
||||||
|
, diskoFile ? null
|
||||||
|
, rootMountPoint ? "/mnt"
|
||||||
|
, ...
|
||||||
|
}@args:
|
||||||
|
let
|
||||||
|
disko = import ./. {
|
||||||
|
inherit rootMountPoint;
|
||||||
|
inherit lib;
|
||||||
|
};
|
||||||
|
|
||||||
|
flake' = (builtins.getFlake flake);
|
||||||
|
|
||||||
|
hasDiskoFile = diskoFile != null;
|
||||||
|
|
||||||
|
hasFlakeDiskoConfig = lib.hasAttrByPath [ "diskoConfigurations" flakeAttr ] flake';
|
||||||
|
|
||||||
|
hasFlakeDiskoModule =
|
||||||
|
lib.hasAttrByPath [ "nixosConfigurations" flakeAttr "config" "disko" "devices" ] flake';
|
||||||
|
|
||||||
|
diskFormat =
|
||||||
|
let
|
||||||
|
diskoConfig =
|
||||||
|
if hasDiskoFile then
|
||||||
|
import diskoFile
|
||||||
|
else
|
||||||
|
flake'.diskoConfigurations.${flakeAttr};
|
||||||
|
in
|
||||||
|
if builtins.isFunction diskoConfig then
|
||||||
|
diskoConfig ({ inherit lib; } // args)
|
||||||
|
else
|
||||||
|
diskoConfig;
|
||||||
|
|
||||||
|
evaluatedConfig =
|
||||||
|
if hasDiskoFile || hasFlakeDiskoConfig then
|
||||||
|
disko.eval diskFormat
|
||||||
|
else if (lib.traceValSeq hasFlakeDiskoModule) then
|
||||||
|
flake'.nixosConfigurations.${flakeAttr}
|
||||||
|
else
|
||||||
|
(builtins.abort "couldn't find `diskoConfigurations.${flakeAttr}` or `nixosConfigurations.${flakeAttr}.config.disko.devices`");
|
||||||
|
|
||||||
|
diskoConfig = evaluatedConfig.config.disko.devices;
|
||||||
|
|
||||||
|
finalConfig = lib.filterAttrsRecursive (name: value: !lib.hasPrefix "_" name) diskoConfig;
|
||||||
|
in
|
||||||
|
finalConfig
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from lib.run_cmd import run
|
||||||
|
from lib.result import DiskoError, DiskoResult, DiskoSuccess
|
||||||
|
|
||||||
|
NIX_BASE_CMD = [
|
||||||
|
"nix",
|
||||||
|
"--extra-experimental-features",
|
||||||
|
"nix-command",
|
||||||
|
"--extra-experimental-features",
|
||||||
|
"flakes",
|
||||||
|
]
|
||||||
|
|
||||||
|
NIX_EVAL_EXPR_CMD = NIX_BASE_CMD + ["eval", "--impure", "--json", "--expr"]
|
||||||
|
|
||||||
|
EVAL_CONFIG_NIX = Path(__file__).absolute().parent / "eval-config.nix"
|
||||||
|
assert (
|
||||||
|
EVAL_CONFIG_NIX.exists()
|
||||||
|
), f"Can't find `eval-config.nix`, expected it next to {__file__}"
|
||||||
|
|
||||||
|
|
||||||
|
def eval_config(args: dict[str, str]) -> DiskoResult[dict[str, Any]]:
|
||||||
|
args_as_json = json.dumps(args)
|
||||||
|
|
||||||
|
result = run(
|
||||||
|
NIX_EVAL_EXPR_CMD
|
||||||
|
+ [f"import {EVAL_CONFIG_NIX} (builtins.fromJSON ''{args_as_json}'')"]
|
||||||
|
)
|
||||||
|
|
||||||
|
if isinstance(result, DiskoError):
|
||||||
|
return DiskoError.single_message(
|
||||||
|
"ERR_EVAL_CONFIG_FAILED",
|
||||||
|
{"args": args, "stderr": result.messages[0].details["stderr"]},
|
||||||
|
"evaluate disko configuration",
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
# We trust the output of `nix eval` to be valid JSON
|
||||||
|
return DiskoSuccess(json.loads(result.value), "evaluate disko config")
|
||||||
|
|
||||||
|
|
||||||
|
def eval_disko_file(config_file: Path) -> DiskoResult[dict[str, Any]]:
|
||||||
|
abs_path = config_file.absolute()
|
||||||
|
|
||||||
|
if not abs_path.exists():
|
||||||
|
return DiskoError.single_message(
|
||||||
|
"ERR_FILE_NOT_FOUND",
|
||||||
|
{"path": abs_path},
|
||||||
|
"evaluate disko_file",
|
||||||
|
)
|
||||||
|
|
||||||
|
return eval_config({"diskoFile": str(abs_path)})
|
||||||
|
|
||||||
|
|
||||||
|
def eval_flake(flake_uri: str) -> DiskoResult[dict[str, Any]]:
|
||||||
|
# arg parser should not allow empty strings
|
||||||
|
assert len(flake_uri) > 0
|
||||||
|
|
||||||
|
flake_match = re.match(r"^([^#]+)(?:#(.*))?$", flake_uri)
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
if not flake_attr:
|
||||||
|
return DiskoError.single_message(
|
||||||
|
"ERR_FLAKE_URI_NO_ATTR", {"flake_uri": flake_uri}, "evaluate flake"
|
||||||
|
)
|
||||||
|
|
||||||
|
flake_path = Path(flake)
|
||||||
|
if flake_path.exists():
|
||||||
|
flake = str(flake_path.absolute())
|
||||||
|
|
||||||
|
return eval_config({"flake": flake, "flakeAttr": flake_attr})
|
||||||
+76
-3
@@ -1,8 +1,7 @@
|
|||||||
# Logging functionality and global logging configuration
|
# Logging functionality and global logging configuration
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from enum import Enum
|
|
||||||
import logging
|
import logging
|
||||||
import textwrap
|
import re
|
||||||
from typing import Any, Literal, assert_never
|
from typing import Any, Literal, assert_never
|
||||||
|
|
||||||
from lib.ansi import Colors
|
from lib.ansi import Colors
|
||||||
@@ -32,6 +31,10 @@ class ReadableMessage:
|
|||||||
# Note: Sort them alphabetically when adding new ones!
|
# Note: Sort them alphabetically when adding new ones!
|
||||||
MessageCode = Literal[
|
MessageCode = Literal[
|
||||||
"BUG_SUCCESS_WITHOUT_CONTEXT",
|
"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_ARGUMENTS",
|
||||||
"ERR_MISSING_MODE",
|
"ERR_MISSING_MODE",
|
||||||
"ERR_TOO_MANY_ARGUMENTS",
|
"ERR_TOO_MANY_ARGUMENTS",
|
||||||
@@ -76,6 +79,44 @@ def to_readable(message: DiskoMessage) -> list[ReadableMessage]:
|
|||||||
),
|
),
|
||||||
bug_help_message(message.code),
|
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":
|
case "ERR_MISSING_ARGUMENTS":
|
||||||
return [
|
return [
|
||||||
ReadableMessage(
|
ReadableMessage(
|
||||||
@@ -106,6 +147,36 @@ def to_readable(message: DiskoMessage) -> list[ReadableMessage]:
|
|||||||
assert_never(c)
|
assert_never(c)
|
||||||
|
|
||||||
|
|
||||||
|
# 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
|
||||||
|
# indentation for verbatim output that is inserted at the end
|
||||||
|
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))
|
||||||
|
|
||||||
|
if dedent_width == 0:
|
||||||
|
return lines
|
||||||
|
|
||||||
|
match_indent_regex = re.compile(f"^ {{1,{dedent_width}}}")
|
||||||
|
|
||||||
|
dedented_lines = []
|
||||||
|
stop_dedenting = False
|
||||||
|
for line in lines:
|
||||||
|
if not line.startswith(" "):
|
||||||
|
stop_dedenting = True
|
||||||
|
|
||||||
|
if stop_dedenting:
|
||||||
|
dedented_lines.append(line)
|
||||||
|
continue
|
||||||
|
|
||||||
|
dedented_line = re.sub(match_indent_regex, "", line)
|
||||||
|
dedented_lines.append(dedented_line)
|
||||||
|
|
||||||
|
return dedented_lines
|
||||||
|
|
||||||
|
|
||||||
def render_message(message: ReadableMessage) -> None:
|
def render_message(message: ReadableMessage) -> None:
|
||||||
bg_color = {
|
bg_color = {
|
||||||
"bug": Colors.BG_RED,
|
"bug": Colors.BG_RED,
|
||||||
@@ -143,7 +214,7 @@ def render_message(message: ReadableMessage) -> None:
|
|||||||
"debug": LOGGER.debug,
|
"debug": LOGGER.debug,
|
||||||
}[message.type]
|
}[message.type]
|
||||||
|
|
||||||
msg_lines = textwrap.dedent(message.msg).splitlines()
|
msg_lines = message.msg.strip("\n").splitlines()
|
||||||
|
|
||||||
# "WARNING:" is 8 characters long, center in 10 for space on each side
|
# "WARNING:" is 8 characters long, center in 10 for space on each side
|
||||||
title = f"{bg_color}{title_raw + ":":^10}{RESET}"
|
title = f"{bg_color}{title_raw + ":":^10}{RESET}"
|
||||||
@@ -152,6 +223,8 @@ def render_message(message: ReadableMessage) -> None:
|
|||||||
log_msg(f" {title} {msg_lines[0]}")
|
log_msg(f" {title} {msg_lines[0]}")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
msg_lines = dedent_start_lines(msg_lines)
|
||||||
|
|
||||||
log_msg(f"{decor_color}╭─{title} {msg_lines[0]}")
|
log_msg(f"{decor_color}╭─{title} {msg_lines[0]}")
|
||||||
|
|
||||||
for line in msg_lines[1:]:
|
for line in msg_lines[1:]:
|
||||||
|
|||||||
+8
-2
@@ -1,7 +1,7 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Generic, Literal, TypeVar
|
from typing import Any, Generic, Literal, TypeVar
|
||||||
|
|
||||||
from lib.logging import DiskoMessage, debug, print_msg
|
from lib.logging import DiskoMessage, debug, print_msg, MessageCode
|
||||||
|
|
||||||
T = TypeVar("T", covariant=True)
|
T = TypeVar("T", covariant=True)
|
||||||
|
|
||||||
@@ -19,6 +19,12 @@ class DiskoError:
|
|||||||
context: str
|
context: str
|
||||||
success: Literal[False] = False
|
success: Literal[False] = False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def single_message(
|
||||||
|
cls, code: MessageCode, details: dict[str, Any], context: str
|
||||||
|
) -> "DiskoError":
|
||||||
|
return cls([DiskoMessage(code, details)], context)
|
||||||
|
|
||||||
|
|
||||||
DiskoResult = DiskoSuccess[T] | DiskoError
|
DiskoResult = DiskoSuccess[T] | DiskoError
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import subprocess
|
||||||
|
|
||||||
|
from lib.logging import debug
|
||||||
|
from lib.result import DiskoError, DiskoResult, DiskoSuccess
|
||||||
|
|
||||||
|
|
||||||
|
def run(args: list[str]) -> DiskoResult[str]:
|
||||||
|
command = " ".join(args)
|
||||||
|
debug(f"Running: {command}")
|
||||||
|
|
||||||
|
result = subprocess.run(args, capture_output=True, text=True)
|
||||||
|
|
||||||
|
debug(
|
||||||
|
f"""
|
||||||
|
Ran: {command}
|
||||||
|
Exit code: {result.returncode}
|
||||||
|
Stdout: {result.stdout}
|
||||||
|
Stderr: {result.stderr}
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.returncode == 0:
|
||||||
|
return DiskoSuccess(result.stdout, "run command")
|
||||||
|
|
||||||
|
return DiskoError.single_message(
|
||||||
|
"ERR_COMMAND_FAILED",
|
||||||
|
{
|
||||||
|
"command": command,
|
||||||
|
"stderr": result.stderr,
|
||||||
|
"exit_code": result.returncode,
|
||||||
|
},
|
||||||
|
"run command",
|
||||||
|
)
|
||||||
Reference in new issue
Block a user