disko2: Add basic logging setup

This commit is contained in:
Felix Uhl committed 2024-10-29 20:43:18 +01:00
1 parent db29851652
commit ffa1b89bb0
5 files changed
+456 -36

No files matched your search

+56 -36
View File
@@ -1,47 +1,71 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import argparse import argparse
from enum import Enum
from pathlib import Path from pathlib import Path
from typing import Literal
from lib.logging import DiskoMessage, info
from lib.result import DiskoError, DiskoSuccess, DiskoResult, exit_on_error
class Mode(Enum): Mode = Literal[
DESTROY = "destroy" "destroy", "format", "mount", "destroy,format,mount", "format,mount", "generate"
FORMAT = "format" ]
MOUNT = "mount"
DESTROY_FORMAT_MOUNT = "destroy,format,mount"
FORMAT_MOUNT = "format,mount"
GENERATE = "generate"
# Modes to apply an existing configuration # Modes to apply an existing configuration
APPLY_MODES = [ APPLY_MODES: list[Mode] = [
Mode.DESTROY, "destroy",
Mode.FORMAT, "format",
Mode.MOUNT, "mount",
Mode.DESTROY_FORMAT_MOUNT, "destroy,format,mount",
Mode.FORMAT_MOUNT, "format,mount",
] ]
ALL_MODES: list[Mode] = APPLY_MODES + ["generate"]
MODE_DESCRIPTION = { MODE_DESCRIPTION: dict[Mode, str] = {
Mode.DESTROY: "Destroy the partition tables on the specified disks", "destroy": "Destroy the partition tables on the specified disks",
Mode.FORMAT: "Change formatting and filesystems on the specified disks", "format": "Change formatting and filesystems on the specified disks",
Mode.MOUNT: "Mount the specified disks", "mount": "Mount the specified disks",
Mode.DESTROY_FORMAT_MOUNT: "Run destroy, format and mount in sequence", "destroy,format,mount": "Run destroy, format and mount in sequence",
Mode.FORMAT_MOUNT: "Run format and mount in sequence", "format,mount": "Run format and mount in sequence",
Mode.GENERATE: "Generate a disko configuration file from the system's current state", "generate": "Generate a disko configuration file from the system's current state",
} }
def run_apply(*, mode: str, disko_file=Path | None, flake=str): def run_apply(*, mode: str, disko_file: Path | None, flake: str | None) -> DiskoResult:
print(f"{mode=} {disko_file=} {flake=}") 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")
return DiskoSuccess(
{
"mode": mode,
"disko_file": disko_file,
"flake": flake,
},
"apply configuration",
)
def run_generate(): def run_generate() -> DiskoResult:
print("generate") return DiskoSuccess("generate", "generate config")
def parse_args(): def run(args: argparse.Namespace) -> DiskoResult:
if args.mode == None:
return DiskoError(
[DiskoMessage("ERR_MISSING_MODE", {"valid_modes": ALL_MODES})],
"select mode",
)
if args.mode == "generate":
return run_generate()
return run_apply(**vars(args))
def parse_args() -> argparse.Namespace:
root_parser = argparse.ArgumentParser( root_parser = argparse.ArgumentParser(
prog="disko2", prog="disko2",
description="Automated disk partitioning and formatting tool for NixOS", description="Automated disk partitioning and formatting tool for NixOS",
@@ -51,7 +75,7 @@ def parse_args():
def create_apply_parser(mode: Mode) -> argparse.ArgumentParser: def create_apply_parser(mode: Mode) -> argparse.ArgumentParser:
parser = mode_parsers.add_parser( parser = mode_parsers.add_parser(
mode.value, mode,
help=MODE_DESCRIPTION[mode], help=MODE_DESCRIPTION[mode],
) )
parser.add_argument( parser.add_argument(
@@ -73,20 +97,16 @@ def parse_args():
# Other commands # Other commands
generate_parser = mode_parsers.add_parser( generate_parser = mode_parsers.add_parser(
"generate", "generate",
help=MODE_DESCRIPTION[Mode.GENERATE], help=MODE_DESCRIPTION["generate"],
) )
return root_parser.parse_args() return root_parser.parse_args()
def main(): def main() -> None:
args = parse_args() args = parse_args()
if args.mode == None: result = run(args)
print("No mode specified") output = exit_on_error(result)
exit(1) info(str(output))
elif args.mode == "generate":
run_generate()
else:
run_apply(**vars(args))
if __name__ == "__main__": if __name__ == "__main__":
View File
Whitespace-only changes.
Executable
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
# ANSI escape sequences for coloring and formatting text
# Inspired by rene-d's colors.py, published in 2018
# See https://gist.github.com/rene-d/9e584a7dd2935d0f461904b9f2950007
# Run as a script to see all available colors and styles
class Colors:
"""
ANSI escape sequences
These constants were generated using nushell with the following command:
nix run nixpkgs#nushell -- -c '
ansi -l
| where name !~ "^xterm"
| each { |line|
$'"'"'($line.name | str upcase) = "($line.code | str replace "\\e" "\\033")"'"'"'
}
| print -r'
I then removed many useless codes that are related to cursor movement, clearing the screen, etc.
"""
GREEN = "\033[32m"
GREEN_BOLD = "\033[1;32m"
GREEN_ITALIC = "\033[3;32m"
GREEN_DIMMED = "\033[2;32m"
GREEN_REVERSE = "\033[7;32m"
BG_GREEN = "\033[42m"
LIGHT_GREEN = "\033[92m"
LIGHT_GREEN_BOLD = "\033[1;92m"
LIGHT_GREEN_UNDERLINE = "\033[4;92m"
LIGHT_GREEN_ITALIC = "\033[3;92m"
LIGHT_GREEN_DIMMED = "\033[2;92m"
LIGHT_GREEN_REVERSE = "\033[7;92m"
BG_LIGHT_GREEN = "\033[102m"
RED = "\033[31m"
RED_BOLD = "\033[1;31m"
RED_UNDERLINE = "\033[4;31m"
RED_ITALIC = "\033[3;31m"
RED_DIMMED = "\033[2;31m"
RED_REVERSE = "\033[7;31m"
BG_RED = "\033[41m"
LIGHT_RED = "\033[91m"
LIGHT_RED_BOLD = "\033[1;91m"
LIGHT_RED_UNDERLINE = "\033[4;91m"
LIGHT_RED_ITALIC = "\033[3;91m"
LIGHT_RED_DIMMED = "\033[2;91m"
LIGHT_RED_REVERSE = "\033[7;91m"
BG_LIGHT_RED = "\033[101m"
BLUE = "\033[34m"
BLUE_BOLD = "\033[1;34m"
BLUE_UNDERLINE = "\033[4;34m"
BLUE_ITALIC = "\033[3;34m"
BLUE_DIMMED = "\033[2;34m"
BLUE_REVERSE = "\033[7;34m"
BG_BLUE = "\033[44m"
LIGHT_BLUE = "\033[94m"
LIGHT_BLUE_BOLD = "\033[1;94m"
LIGHT_BLUE_UNDERLINE = "\033[4;94m"
LIGHT_BLUE_ITALIC = "\033[3;94m"
LIGHT_BLUE_DIMMED = "\033[2;94m"
LIGHT_BLUE_REVERSE = "\033[7;94m"
BG_LIGHT_BLUE = "\033[104m"
BLACK = "\033[30m"
BLACK_BOLD = "\033[1;30m"
BLACK_UNDERLINE = "\033[4;30m"
BLACK_ITALIC = "\033[3;30m"
BLACK_DIMMED = "\033[2;30m"
BLACK_REVERSE = "\033[7;30m"
BG_BLACK = "\033[40m"
LIGHT_GRAY = "\033[97m"
LIGHT_GRAY_BOLD = "\033[1;97m"
LIGHT_GRAY_UNDERLINE = "\033[4;97m"
LIGHT_GRAY_ITALIC = "\033[3;97m"
LIGHT_GRAY_DIMMED = "\033[2;97m"
LIGHT_GRAY_REVERSE = "\033[7;97m"
BG_LIGHT_GRAY = "\033[107m"
YELLOW = "\033[33m"
YELLOW_BOLD = "\033[1;33m"
YELLOW_UNDERLINE = "\033[4;33m"
YELLOW_ITALIC = "\033[3;33m"
YELLOW_DIMMED = "\033[2;33m"
YELLOW_REVERSE = "\033[7;33m"
BG_YELLOW = "\033[43m"
LIGHT_YELLOW = "\033[93m"
LIGHT_YELLOW_BOLD = "\033[1;93m"
LIGHT_YELLOW_UNDERLINE = "\033[4;93m"
LIGHT_YELLOW_ITALIC = "\033[3;93m"
LIGHT_YELLOW_DIMMED = "\033[2;93m"
LIGHT_YELLOW_REVERSE = "\033[7;93m"
BG_LIGHT_YELLOW = "\033[103m"
PURPLE = "\033[35m"
PURPLE_BOLD = "\033[1;35m"
PURPLE_UNDERLINE = "\033[4;35m"
PURPLE_ITALIC = "\033[3;35m"
PURPLE_DIMMED = "\033[2;35m"
PURPLE_REVERSE = "\033[7;35m"
BG_PURPLE = "\033[45m"
LIGHT_PURPLE = "\033[95m"
LIGHT_PURPLE_BOLD = "\033[1;95m"
LIGHT_PURPLE_UNDERLINE = "\033[4;95m"
LIGHT_PURPLE_ITALIC = "\033[3;95m"
LIGHT_PURPLE_DIMMED = "\033[2;95m"
LIGHT_PURPLE_REVERSE = "\033[7;95m"
BG_LIGHT_PURPLE = "\033[105m"
MAGENTA = "\033[35m"
MAGENTA_BOLD = "\033[1;35m"
MAGENTA_UNDERLINE = "\033[4;35m"
MAGENTA_ITALIC = "\033[3;35m"
MAGENTA_DIMMED = "\033[2;35m"
MAGENTA_REVERSE = "\033[7;35m"
BG_MAGENTA = "\033[45m"
LIGHT_MAGENTA = "\033[95m"
LIGHT_MAGENTA_BOLD = "\033[1;95m"
LIGHT_MAGENTA_UNDERLINE = "\033[4;95m"
LIGHT_MAGENTA_ITALIC = "\033[3;95m"
LIGHT_MAGENTA_DIMMED = "\033[2;95m"
LIGHT_MAGENTA_REVERSE = "\033[7;95m"
BG_LIGHT_MAGENTA = "\033[105m"
CYAN = "\033[36m"
CYAN_BOLD = "\033[1;36m"
CYAN_UNDERLINE = "\033[4;36m"
CYAN_ITALIC = "\033[3;36m"
CYAN_DIMMED = "\033[2;36m"
CYAN_REVERSE = "\033[7;36m"
BG_CYAN = "\033[46m"
LIGHT_CYAN = "\033[96m"
LIGHT_CYAN_BOLD = "\033[1;96m"
LIGHT_CYAN_UNDERLINE = "\033[4;96m"
LIGHT_CYAN_ITALIC = "\033[3;96m"
LIGHT_CYAN_DIMMED = "\033[2;96m"
LIGHT_CYAN_REVERSE = "\033[7;96m"
BG_LIGHT_CYAN = "\033[106m"
WHITE = "\033[37m"
WHITE_BOLD = "\033[1;37m"
WHITE_UNDERLINE = "\033[4;37m"
WHITE_ITALIC = "\033[3;37m"
WHITE_DIMMED = "\033[2;37m"
WHITE_REVERSE = "\033[7;37m"
BG_WHITE = "\033[47m"
DARK_GRAY = "\033[90m"
DARK_GRAY_BOLD = "\033[1;90m"
DARK_GRAY_UNDERLINE = "\033[4;90m"
DARK_GRAY_ITALIC = "\033[3;90m"
DARK_GRAY_DIMMED = "\033[2;90m"
DARK_GRAY_REVERSE = "\033[7;90m"
BG_DARK_GRAY = "\033[100m"
DEFAULT = "\033[39m"
DEFAULT_BOLD = "\033[1;39m"
DEFAULT_UNDERLINE = "\033[4;39m"
DEFAULT_ITALIC = "\033[3;39m"
DEFAULT_DIMMED = "\033[2;39m"
DEFAULT_REVERSE = "\033[7;39m"
BG_DEFAULT = "\033[49m"
RESET = "\033[0m"
ATTR_NORMAL = "\033[0m"
ATTR_BOLD = "\033[1m"
ATTR_DIMMED = "\033[2m"
ATTR_ITALIC = "\033[3m"
ATTR_UNDERLINE = "\033[4m"
ATTR_BLINK = "\033[5m"
ATTR_HIDDEN = "\033[8m"
ATTR_STRIKE = "\033[9m"
# cancel SGR codes if we don't write to a terminal
if not __import__("sys").stdout.isatty():
for _ in dir():
if isinstance(_, str) and _[0] != "_":
locals()[_] = ""
else:
# set Windows console in VT mode
if __import__("platform").system() == "Windows":
kernel32 = __import__("ctypes").windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
del kernel32
if __name__ == "__main__":
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))
+179
View File
@@ -0,0 +1,179 @@
# Logging functionality and global logging configuration
from dataclasses import dataclass, field
from enum import Enum
import logging
import textwrap
from typing import Any, Literal, assert_never
from lib.ansi import Colors
logging.basicConfig(format="%(message)s", level=logging.INFO)
LOGGER = logging.getLogger("disko_logger")
# Color definitions. Note: Sort them alphabetically when adding new ones!
COMMAND = Colors.CYAN_ITALIC # Commands that were run or can be run
FILE = Colors.BLUE # File paths
FLAG = Colors.GREEN # Command line flags (like --version or -f)
INVALID = Colors.RED # Invalid values
PLACEHOLDER = Colors.MAGENTA_ITALIC # Values that need to be replaced
VALUE = Colors.GREEN # Values that are allowed
RESET = Colors.RESET # Shortcut to reset the color
@dataclass
class ReadableMessage:
type: Literal["bug", "error", "warning", "info", "help", "debug"]
msg: str
# Codes for every single message that disko can print
# Note: Sort them alphabetically when adding new ones!
MessageCode = Literal[
"BUG_SUCCESS_WITHOUT_CONTEXT",
"ERR_MISSING_ARGUMENTS",
"ERR_MISSING_MODE",
"ERR_TOO_MANY_ARGUMENTS",
]
@dataclass
class DiskoMessage:
code: MessageCode
details: dict[str, Any] = field(default_factory=dict)
ERR_ARGUMENTS_HELP_TXT = f"Provide either {PLACEHOLDER}disko_file{RESET} as the second argument or \
{FLAG}--flake{RESET}/{FLAG}-f{RESET} {PLACEHOLDER}flake-uri{RESET}."
def bug_help_message(error_code: MessageCode) -> ReadableMessage:
return ReadableMessage(
"help",
f"""
Please report this bug!
First, check if has already been reported at
https://github.com/nix-community/disko/issues?q=is%3Aissue+{error_code}
If not, open a new issue at
https://github.com/nix-community/disko/issues/new?title={error_code}
and include the full logs printed above!
""",
)
def to_readable(message: DiskoMessage) -> list[ReadableMessage]:
match message.code:
case "BUG_SUCCESS_WITHOUT_CONTEXT":
return [
ReadableMessage(
"bug",
f"""
Success message without context!
Returned value:
{message.details['value']}
""",
),
bug_help_message(message.code),
]
case "ERR_MISSING_ARGUMENTS":
return [
ReadableMessage(
"error",
f"Missing arguments!",
),
ReadableMessage("help", ERR_ARGUMENTS_HELP_TXT),
]
case "ERR_TOO_MANY_ARGUMENTS":
return [
ReadableMessage(
"error",
f"Too many arguments!",
),
ReadableMessage("help", ERR_ARGUMENTS_HELP_TXT),
]
case "ERR_MISSING_MODE":
modes_list = "\n".join(
[f" - {VALUE}{m}{RESET}" for m in message.details["valid_modes"]]
)
return [
ReadableMessage("error", "Missing mode!"),
ReadableMessage("help", "Allowed modes are:\n" + modes_list),
]
# We could also remove these two lines, but assert_never emits a better error message
case _ as c:
assert_never(c)
def render_message(message: ReadableMessage) -> None:
bg_color = {
"bug": Colors.BG_RED,
"error": Colors.BG_RED,
"warning": Colors.BG_YELLOW,
"info": Colors.BG_GREEN,
"help": Colors.BG_LIGHT_MAGENTA,
"debug": Colors.BG_LIGHT_CYAN,
}[message.type]
decor_color = {
"bug": Colors.RED,
"error": Colors.RED,
"warning": Colors.YELLOW,
"info": Colors.GREEN,
"help": Colors.LIGHT_MAGENTA,
"debug": Colors.LIGHT_CYAN,
}[message.type]
title_raw = {
"bug": "BUG",
"error": "ERROR",
"warning": "WARNING",
"info": "INFO",
"help": "HELP",
"debug": "DEBUG",
}[message.type]
log_msg = {
"bug": LOGGER.error,
"error": LOGGER.error,
"warning": LOGGER.warning,
"info": LOGGER.info,
"help": LOGGER.info,
"debug": LOGGER.debug,
}[message.type]
msg_lines = textwrap.dedent(message.msg).splitlines()
# "WARNING:" is 8 characters long, center in 10 for space on each side
title = f"{bg_color}{title_raw + ":":^10}{RESET}"
if len(msg_lines) == 1:
log_msg(f" {title} {msg_lines[0]}")
return
log_msg(f"{decor_color}╭─{title} {msg_lines[0]}")
for line in msg_lines[1:]:
log_msg(f"{decor_color}│ {RESET} {line}")
log_msg(f"{decor_color}╰───────────{RESET}") # Exactly as long as the heading
def print_msg(code: MessageCode, details: dict[str, Any]) -> None:
for msg in to_readable(DiskoMessage(code, details)):
render_message(msg)
def debug(msg: str) -> None:
# Check debug level immediately to avoid unnecessary formatting
if LOGGER.isEnabledFor(logging.DEBUG):
render_message(ReadableMessage("debug", str(msg)))
# In general, only debug messages should be logged directly, all other
# messages should be wrapped in a DiskoResult for easier testing
# Info is exposed only for testing during initial development of disko2
# TODO: Remove this function and use DiskoResult instead
def info(msg: str) -> None:
render_message(ReadableMessage("info", str(msg)))
+36
View File
@@ -0,0 +1,36 @@
from dataclasses import dataclass
from typing import Literal, Union
from lib.logging import DiskoMessage, debug, print_msg
@dataclass
class DiskoSuccess:
value: object
context: None | str = None
success: Literal[True] = True
@dataclass
class DiskoError:
messages: list[DiskoMessage]
context: str
success: Literal[False] = False
DiskoResult = Union[DiskoSuccess, DiskoError]
def exit_on_error(result: DiskoResult) -> object:
if isinstance(result, DiskoSuccess):
if result.context is None:
print_msg("BUG_SUCCESS_WITHOUT_CONTEXT", {"value": result.value})
else:
debug(f"Success in '{result.context}'")
debug(f"Returned value: {result.value}")
return result.value
for message in result.messages:
print_msg(message.code, message.details)
exit(1)