diff --git a/.vscode/launch.json b/.vscode/launch.json index 87755f6..cf28c70 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -5,7 +5,7 @@ "version": "0.2.0", "configurations": [ { - "name": "Python Debugger: disko2", + "name": "disko2 mount disko_file", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/disko2", @@ -14,6 +14,18 @@ "mount", "example/simple-efi.nix" ] + }, + { + "name": "disko2 mount flake", + "type": "debugpy", + "request": "launch", + "program": "${workspaceFolder}/disko2", + "console": "integratedTerminal", + "args": [ + "mount", + "--flake", + ".#testmachine" + ] } ] } \ No newline at end of file diff --git a/default.nix b/default.nix index bf3570e..65e4903 100644 --- a/default.nix +++ b/default.nix @@ -17,6 +17,7 @@ let }; in { + inherit eval; lib = lib.warn "the .lib.lib output is deprecated" diskoLib; # legacy alias diff --git a/disko2 b/disko2 index 9aecbe0..f28ef3b 100755 --- a/disko2 +++ b/disko2 @@ -1,10 +1,12 @@ #!/usr/bin/env python3 import argparse +import json 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 Mode = Literal[ @@ -33,21 +35,17 @@ MODE_DESCRIPTION: dict[Mode, str] = { 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]]: - if flake is None and disko_file is None: - return DiskoError([DiskoMessage("ERR_MISSING_ARGUMENTS")], "validate args") - if flake is not None and disko_file is not None: - return DiskoError([DiskoMessage("ERR_TOO_MANY_ARGUMENTS")], "validate args") + # 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") + 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( - { - "mode": mode, - "disko_file": disko_file, - "flake": flake, - }, - "apply configuration", - ) + return DiskoError.single_message("ERR_TOO_MANY_ARGUMENTS", {}, "validate args") def run_generate() -> DiskoResult[Literal["generate"]]: @@ -57,14 +55,13 @@ def run_generate() -> DiskoResult[Literal["generate"]]: def run( args: argparse.Namespace, ) -> DiskoResult[Literal["generate"] | dict[str, Any]]: - if args.verbose == True: + if args.verbose: LOGGER.setLevel("DEBUG") debug("Enabled debug logging.") - if args.mode == None: - return DiskoError( - [DiskoMessage("ERR_MISSING_MODE", {"valid_modes": ALL_MODES})], - "select mode", + if not args.mode: + return DiskoError.single_message( + "ERR_MISSING_MODE", {"valid_modes": ALL_MODES}, "select mode" ) if args.mode == "generate": @@ -122,7 +119,7 @@ def main() -> None: args = parse_args() result = run(args) output = exit_on_error(result) - info(str(output)) + info("Output:\n" + json.dumps(output, indent=2)) if __name__ == "__main__": diff --git a/lib/eval-config.nix b/lib/eval-config.nix new file mode 100644 index 0000000..8866213 --- /dev/null +++ b/lib/eval-config.nix @@ -0,0 +1,49 @@ +{ pkgs ? import { } +, 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 diff --git a/lib/eval_config.py b/lib/eval_config.py new file mode 100644 index 0000000..5715e85 --- /dev/null +++ b/lib/eval_config.py @@ -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}) diff --git a/lib/logging.py b/lib/logging.py index b8885d2..a4dee4e 100644 --- a/lib/logging.py +++ b/lib/logging.py @@ -1,8 +1,7 @@ # Logging functionality and global logging configuration from dataclasses import dataclass, field -from enum import Enum import logging -import textwrap +import re from typing import Any, Literal, assert_never from lib.ansi import Colors @@ -32,6 +31,10 @@ class ReadableMessage: # Note: Sort them alphabetically when adding new ones! MessageCode = Literal[ "BUG_SUCCESS_WITHOUT_CONTEXT", + "ERR_COMMAND_FAILED", + "ERR_EVAL_CONFIG_FAILED", + "ERR_FILE_NOT_FOUND", + "ERR_FLAKE_URI_NO_ATTR", "ERR_MISSING_ARGUMENTS", "ERR_MISSING_MODE", "ERR_TOO_MANY_ARGUMENTS", @@ -76,6 +79,44 @@ def to_readable(message: DiskoMessage) -> list[ReadableMessage]: ), bug_help_message(message.code), ] + case "ERR_COMMAND_FAILED": + return [ + ReadableMessage( + "error", + f""" + Command failed: {COMMAND}{message.details['command']}{COMMAND} + Exit code: {INVALID}{message.details['exit_code']}{RESET} + stderr: {message.details['stderr']} + """, + ) + ] + case "ERR_EVAL_CONFIG_FAILED": + return [ + ReadableMessage( + "error", + f""" + Failed to evaluate disko config with args {INVALID}{message.details['args']}{RESET}! + Stderr from {COMMAND}nix eval{RESET}:\n{message.details['stderr']} + """, + ) + ] + case "ERR_FILE_NOT_FOUND": + return [ + ReadableMessage( + "error", f"File not found: {FILE}{message.details['path']}{RESET}" + ) + ] + case "ERR_FLAKE_URI_NO_ATTR": + return [ + ReadableMessage( + "error", + f"Flake URI {INVALID}{message.details['flake_uri']}{RESET} has no attribute.", + ), + ReadableMessage( + "help", + f"Append an attribute like {VALUE}#{PLACEHOLDER}foo{RESET} to the flake URI.", + ), + ] case "ERR_MISSING_ARGUMENTS": return [ ReadableMessage( @@ -106,6 +147,36 @@ def to_readable(message: DiskoMessage) -> list[ReadableMessage]: 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: bg_color = { "bug": Colors.BG_RED, @@ -143,7 +214,7 @@ def render_message(message: ReadableMessage) -> None: "debug": LOGGER.debug, }[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 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]}") return + msg_lines = dedent_start_lines(msg_lines) + log_msg(f"{decor_color}╭─{title} {msg_lines[0]}") for line in msg_lines[1:]: diff --git a/lib/result.py b/lib/result.py index 30e3369..b11d4c4 100644 --- a/lib/result.py +++ b/lib/result.py @@ -1,7 +1,7 @@ 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) @@ -19,6 +19,12 @@ class DiskoError: context: str 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 diff --git a/lib/run_cmd.py b/lib/run_cmd.py new file mode 100644 index 0000000..9cc3fd4 --- /dev/null +++ b/lib/run_cmd.py @@ -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", + )