diff --git a/flake.nix b/flake.nix index f7b6282..8893727 100644 --- a/flake.nix +++ b/flake.nix @@ -99,6 +99,9 @@ (python3.withPackages (ps: [ ps.mypy # Static type checker ps.pytest # Test runner + + # Actual runtime depedencies + ps.pydantic # Validation of nixos configuration ])) ]); }; diff --git a/scripts/generate_python_types.py b/scripts/generate_python_types.py new file mode 100755 index 0000000..aa2243e --- /dev/null +++ b/scripts/generate_python_types.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 + +import io +import json +import sys +from typing import Any, Callable, Literal, Mapping, TypeGuard + + +def is_type( + type_field: dict[str, Any] +) -> TypeGuard[dict[Literal["default", "description", "type"], Any]]: + if not isinstance(type_field, dict): + return False + return set(type_field.keys()) == {"default", "description", "type"} + + +def parse_type( + containing_class: str, field_name: str, type_field: str | dict[str, Any] +) -> tuple[str, io.StringIO | None]: + """Parse a type field into a Python type annotation. + + If the type is a class itself, the second element of the tuple + will be a buffer containing the class definition. + """ + + if isinstance(type_field, str): + return _parse_simple_type(type_field), None + elif isinstance(type_field, dict): + if type_field.get("__isCompositeType"): + return _parse_composite_type(containing_class, field_name, type_field) + else: + class_name = f"{containing_class}_{field_name}" + class_code, inner_types_code = generate_class(class_name, type_field) + + if not inner_types_code: + inner_types_code = io.StringIO() + + inner_types_code.write("\n\n") + inner_types_code.write(class_code) + + return class_name, inner_types_code + + else: + raise ValueError(f"Invalid type field: {type_field}") + + +def _parse_composite_type( + containing_class: str, field_name: str, type_dict: dict[str, Any] +) -> tuple[str, io.StringIO | None]: + assert isinstance(type_dict["type"], str) + + type_name, type_code = None, None + if "subType" in type_dict: + try: + type_name, type_code = parse_type( + containing_class, field_name, type_dict["subType"] + ) + except Exception as e: + e.add_note(f"Error in subType {type_dict["subType"]}") + raise e + + match type_dict["type"]: + case "attrsOf": + return f"dict[str, {type_name}]", type_code + case "listOf": + return f"list[{type_name}]", type_code + case "nullOr": + return f"None | {type_name}", type_code + case "oneOf": + type_code = io.StringIO() + type_names = [] + for sub_type in type_dict["types"]: + try: + sub_type_name, sub_type_code = parse_type( + containing_class, field_name, sub_type + ) + except Exception as e: + e.add_note(f"Error in subType {sub_type}") + raise e + + type_names.append(sub_type_name) + if sub_type_code: + type_code.write(sub_type_code.getvalue()) + + # Can't use | syntax in all cases, Union always works + return f'Union[{", ".join(type_names)}]', type_code + case "enum": + return ( + f'Literal[{", ".join(f"{repr(value)}" for value in type_dict["choices"])}]', + None, + ) + case _: + return _parse_simple_type(type_dict["type"]), None + + +def _parse_simple_type(type_str: str) -> str: + match type_str: + case "str": + return "str" + case "absolute-pathname": + return "str" + case "bool": + return "bool" + case "int": + return "int" + case "anything": + return "Any" + case _: + # Probably a type alias, needs to be quoted in case the type is defined later + return f'"{type_str}"' + + +def parse_field( + containing_class: str, field_name: str, field: dict[str, Any] +) -> tuple[str, io.StringIO | None]: + if isinstance(field, str): + return _parse_simple_type(field), None + + if is_type(field): + return parse_type(containing_class, field_name, field["type"]) + + class_name = f"{containing_class}_{field_name}" + class_code, inner_types_code = generate_class(class_name, field) + + if not inner_types_code: + inner_types_code = io.StringIO() + + inner_types_code.write("\n\n") + inner_types_code.write(class_code) + + return class_name, inner_types_code + + +def generate_type_alias( + name: str, type_spec: str | dict[str, Any] +) -> io.StringIO | None: + buffer = io.StringIO() + + try: + type_code, sub_type_code = parse_type(name, "", type_spec) + except ValueError: + return None + + if sub_type_code: + buffer.write(sub_type_code.getvalue()) + buffer.write("\n\n") + + buffer.write(f"{name} = {type_code}") + buffer.write("\n\n") + + return buffer + + +def generate_class(name: str, fields: dict[str, Any]) -> tuple[str, io.StringIO | None]: + assert isinstance(fields, dict) + + contained_classes_buffer = io.StringIO() + + buffer = io.StringIO() + buffer.write(f"class {name}(BaseModel):\n") + + for field_name, field in fields.items(): + try: + type_name, type_code = parse_field(name, field_name, field) + except Exception as e: + e.add_note(f"Error in field {field_name}: {field}") + raise e + + if type_code: + contained_classes_buffer.write(type_code.getvalue()) + + buffer.write(f" {field_name}: {type_name}\n") + + if contained_classes_buffer.tell() == 0: + return buffer.getvalue(), None + + return buffer.getvalue(), contained_classes_buffer + + +def transform_dict_keys( + d: dict[str, Any], transform_fn: Callable[[str], str] +) -> dict[str, Any]: + if not isinstance(d, Mapping): + return d + + return {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: + assert isinstance(schema, dict) + + # Convert disallowed characters in Python identifiers + schema = transform_dict_keys(schema, lambda k: k.replace("-", "_")) + + buffer = io.StringIO() + + buffer.write( + """ +from typing import Any, Literal, Union +from pydantic import BaseModel + + +""" + ) + + for type_name, fields in schema.items(): + if "__isCompositeType" in fields: + try: + alias_content, type_code = _parse_composite_type(type_name, "", fields) + except Exception as e: + e.add_note(f"Error in composite type {type_name}") + raise e + + if type_code: + buffer.write(type_code.getvalue()) + buffer.write("\n\n") + + buffer.write(f"{type_name} = {alias_content}") + buffer.write("\n\n") + continue + + try: + class_code, inner_types_code = generate_class(type_name, fields) + except Exception as e: + e.add_note(f"Error in class {type_name}") + raise e + + if inner_types_code: + buffer.write(inner_types_code.getvalue()) + buffer.write("\n\n") + + buffer.write(class_code) + buffer.write("\n\n") + + buffer.write( + """ +class DiskoConfig(BaseModel): + disk: dict[str, disk] + lvm_vg: dict[str, lvm_vg] + mdadm: dict[str, mdadm] + nodev: dict[str, nodev] + zpool: dict[str, zpool] +""" + ) + + return buffer + + +def main(in_file: str, out_file: str) -> None: + with open(in_file) as f: + schema = json.load(f) + + code_buffer = generate_python_code(schema) + + with open(out_file, "w") as f: + f.write(code_buffer.getvalue()) + + +if __name__ == "__main__": + if len(sys.argv) != 3: + print( + """Usage: generate_python_types.py +Recommendation: Go to the root of this repository and run + + nix build .#checks.x86_64-linux.jsonTypes + +to generate the JSON schema file first, then run + + ./scripts/generate_python_types.py result src/disko_lib/config_types.py +""" + ) + sys.exit(1) + + main(sys.argv[1], sys.argv[2]) diff --git a/src/disko_lib/config_type.py b/src/disko_lib/config_type.py new file mode 100644 index 0000000..09197b1 --- /dev/null +++ b/src/disko_lib/config_type.py @@ -0,0 +1,257 @@ + +from typing import Any, Literal, Union +from pydantic import BaseModel + + + + +class btrfs_subvolumes_options_swap_options(BaseModel): + options: list[str] + path: str + priority: None | int + size: str + + +class btrfs_subvolumes_options_swap(BaseModel): + options: btrfs_subvolumes_options_swap_options + + +class btrfs_subvolumes_options(BaseModel): + extraArgs: list[str] + mountOptions: list[str] + mountpoint: None | str + name: str + swap: dict[str, btrfs_subvolumes_options_swap] + type: Literal['btrfs_subvol'] + + +class btrfs_subvolumes(BaseModel): + options: btrfs_subvolumes_options + + +class btrfs_swap_options(BaseModel): + options: list[str] + path: str + priority: None | int + size: str + + +class btrfs_swap(BaseModel): + options: btrfs_swap_options + + +class btrfs(BaseModel): + device: str + extraArgs: list[str] + mountOptions: list[str] + mountpoint: None | str + subvolumes: dict[str, btrfs_subvolumes] + swap: dict[str, btrfs_swap] + type: Literal['btrfs'] + + + + +deviceType = Union["btrfs", "filesystem", "gpt", "luks", "lvm_pv", "mdraid", "swap", "table", "zfs"] + +class disk(BaseModel): + content: "deviceType" + device: str + imageName: str + imageSize: str + name: str + type: Literal['disk'] + + +class filesystem(BaseModel): + device: str + extraArgs: list[str] + format: str + mountOptions: list[str] + mountpoint: None | str + type: Literal['filesystem'] + + + + +class gpt_partitions_options_hybrid_options(BaseModel): + mbrBootableFlag: bool + mbrPartitionType: None | str + + +class gpt_partitions_options_hybrid(BaseModel): + options: gpt_partitions_options_hybrid_options + + +class gpt_partitions_options(BaseModel): + _index: int + alignment: int + content: "partitionType" + device: str + end: str + hybrid: None | gpt_partitions_options_hybrid + label: str + name: str + priority: int + size: Union[Literal['100%'], str] + start: str + type: Union[str, str] + + +class gpt_partitions(BaseModel): + options: gpt_partitions_options + + +class gpt(BaseModel): + device: str + efiGptPartitionFirst: bool + partitions: dict[str, gpt_partitions] + type: Literal['gpt'] + + +class luks(BaseModel): + additionalKeyFiles: list[str] + askPassword: bool + content: "deviceType" + device: str + extraFormatArgs: list[str] + extraOpenArgs: list[str] + initrdUnlock: bool + keyFile: None | str + name: str + passwordFile: None | str + settings: dict[str, Any] + type: Literal['luks'] + + +class lvm_pv(BaseModel): + device: str + type: Literal['lvm_pv'] + vg: str + + + + +class lvm_vg_lvs_options(BaseModel): + content: "partitionType" + extraArgs: list[str] + lvm_type: None | Literal['mirror', 'raid0', 'raid1', 'raid4', 'raid5', 'raid6', 'thin-pool', 'thinlv'] + name: str + pool: None | str + priority: int + size: str + + +class lvm_vg_lvs(BaseModel): + options: lvm_vg_lvs_options + + +class lvm_vg(BaseModel): + lvs: dict[str, lvm_vg_lvs] + name: str + type: Literal['lvm_vg'] + + +class mdadm(BaseModel): + content: "deviceType" + level: int + metadata: Literal['1', '1.0', '1.1', '1.2', 'default', 'ddf', 'imsm'] + name: str + type: Literal['mdadm'] + + +class mdraid(BaseModel): + device: str + name: str + type: Literal['mdraid'] + + +class nodev(BaseModel): + device: str + fsType: str + mountOptions: list[str] + mountpoint: None | str + type: Literal['nodev'] + + + + +partitionType = Union["btrfs", "filesystem", "luks", "lvm_pv", "mdraid", "swap", "zfs"] + +class swap(BaseModel): + device: str + discardPolicy: None | Literal['once', 'pages', 'both'] + extraArgs: list[str] + mountOptions: list[str] + priority: None | int + randomEncryption: bool + resumeDevice: bool + type: Literal['swap'] + + + + +class table_partitions_options(BaseModel): + _index: int + bootable: bool + content: "partitionType" + end: str + flags: list[str] + fs_type: None | Literal['btrfs', 'ext2', 'ext3', 'ext4', 'fat16', 'fat32', 'hfs', 'hfs+', 'linux-swap', 'ntfs', 'reiserfs', 'udf', 'xfs'] + name: None | str + part_type: Literal['primary', 'logical', 'extended'] + start: str + + +class table_partitions(BaseModel): + options: table_partitions_options + + +class table(BaseModel): + device: str + format: Literal['gpt', 'msdos'] + partitions: list[table_partitions] + type: Literal['table'] + + +class zfs(BaseModel): + device: str + pool: str + type: Literal['zfs'] + + +class zfs_fs(BaseModel): + mountOptions: list[str] + mountpoint: None | str + name: str + options: dict[str, str] + type: Literal['zfs_fs'] + + +class zfs_volume(BaseModel): + content: "partitionType" + mountOptions: list[str] + name: str + options: dict[str, str] + size: None | str + type: Literal['zfs_volume'] + + +class zpool(BaseModel): + datasets: dict[str, Union["zfs_fs", "zfs_volume"]] + mode: Union[Literal['', 'mirror', 'raidz', 'raidz1', 'raidz2', 'raidz3'], dict[str, Any]] + mountOptions: list[str] + mountpoint: None | str + name: str + options: dict[str, str] + rootFsOptions: dict[str, str] + type: Literal['zpool'] + + + +class DiskoConfig(BaseModel): + disk: dict[str, disk] + lvm_vg: dict[str, lvm_vg] + mdadm: dict[str, mdadm] + nodev: dict[str, nodev] + zpool: dict[str, zpool] diff --git a/src/disko_lib/default.nix b/src/disko_lib/default.nix index c7659b8..779b223 100644 --- a/src/disko_lib/default.nix +++ b/src/disko_lib/default.nix @@ -631,26 +631,32 @@ let attrsOf = subType: { type = "attrsOf"; inherit subType; + "__isCompositeType" = true; }; listOf = subType: { type = "listOf"; inherit subType; + "__isCompositeType" = true; }; nullOr = subType: { type = "nullOr"; inherit subType; + "__isCompositeType" = true; }; oneOf = types: { type = "oneOf"; inherit types; + "__isCompositeType" = true; }; either = t1: t2: { type = "oneOf"; types = [ t1 t2 ]; + "__isCompositeType" = true; }; enum = choices: { type = "enum"; inherit choices; + "__isCompositeType" = true; }; anything = "anything"; nonEmptyStr = "str"; @@ -672,6 +678,7 @@ let subType = { types, ... }: { type = "oneOf"; types = lib.attrNames types; + "__isCompositeType" = true; }; mkCreateOption = option: "_create"; }; @@ -689,10 +696,12 @@ let partitionType = { type = "oneOf"; types = lib.attrNames diskoLib._partitionTypes; + "__isCompositeType" = true; }; deviceType = { type = "oneOf"; types = lib.attrNames diskoLib._deviceTypes; + "__isCompositeType" = true; }; }; };