#!/usr/bin/env python3 """ Scaffold a new NixOS host and register it in flake.nix. Creates hosts//{default.nix,hardware.nix} and adds a ` = nixpkgs.lib.nixosSystem { ... };` entry to nixosConfigurations, cloning an existing host's entry when possible so local customizations carry over. Everything is computed and validated in memory before the first byte is written, and the write phase is rolled back if any step fails, so a failed run never leaves a half-registered host behind. Exit codes: 0 ok, 1 error, 2 usage, 130 interrupted. """ from __future__ import annotations import argparse import os import re import shutil import subprocess import sys import tempfile from dataclasses import dataclass, field from pathlib import Path from textwrap import dedent sys.path.insert(0, str(Path(__file__).resolve().parent)) import nixflake # noqa: E402 (needs the sys.path tweak above) from nixflake import FlakeError, HostEntry # noqa: E402 # -------------------------------------------------------------------------- # Output helpers # -------------------------------------------------------------------------- _COLOR = sys.stderr.isatty() and "NO_COLOR" not in os.environ def _c(code: str) -> str: return f"\033[{code}m" if _COLOR else "" def log(msg: str) -> None: print(f"{_c('32')}[+]{_c('0')} {msg}", file=sys.stderr) def warn(msg: str) -> None: print(f"{_c('33')}[!]{_c('0')} {msg}", file=sys.stderr) class RegisterError(Exception): """A user-facing failure; message is printed without a traceback.""" # -------------------------------------------------------------------------- # Hostname validation # -------------------------------------------------------------------------- # RFC 1123 label, restricted further so it is also a legal bare Nix attribute # name: lowercase, starts with a letter, no trailing dash, at most 63 chars. HOST_RE = re.compile(r"^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$") def validate_hostname(name: str) -> None: if not HOST_RE.fullmatch(name): raise RegisterError( f"invalid hostname {name!r}: use lowercase letters, digits and hyphens, " "start with a letter, end with a letter or digit, max 63 characters" ) if name in nixflake.NIX_KEYWORDS: raise RegisterError(f"invalid hostname {name!r}: reserved word in Nix") # -------------------------------------------------------------------------- # Templates # # These contain Nix code, which is full of braces, so they must NOT go # through str.format() or f-strings. Placeholders are @UPPER_CASE@ tokens # replaced by render(), which fails loudly on any leftover token. # -------------------------------------------------------------------------- DEFAULT_NIX_TEMPLATE = dedent("""\ { pkgs, ... }: { imports = [ ./hardware.nix ../../modules/core.nix ../../modules/plasma.nix ../../modules/security.nix ]; networking.hostName = "@NAME@"; boot.loader.systemd-boot.enable = true; boot.loader.efi.canTouchEfiVariables = true; boot.kernelPackages = pkgs.linuxPackages_latest; networking.networkmanager.enable = true; programs.zsh.enable = true; programs.nix-ld.enable = true; programs.nix-ld.libraries = with pkgs; [ stdenv.cc.cc.lib zlib ]; users.users.alex = { isNormalUser = true; shell = pkgs.zsh; extraGroups = [ "wheel" "networkmanager" ]; }; programs._1password.enable = true; programs._1password-gui = { enable = true; polkitPolicyOwners = [ "alex" ]; }; system.stateVersion = "26.05"; } """) HARDWARE_PLACEHOLDER_MARKER = "PLACEHOLDER hardware.nix" # capture-hardware.sh greps for this PLACEHOLDER_HARDWARE = dedent("""\ # PLACEHOLDER hardware.nix for host "@NAME@". # # Replace this file with the output of `nixos-generate-config --show-hardware-config` # run on the target machine. The justfile has a helper for this: # # just capture-hardware @NAME@ # # Until then, this file intentionally does nothing useful and the host # will not build. { lib, ... }: { # nixpkgs hostPlatform; change if not x86_64-linux. nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux"; # Intentionally empty. See note above. } """) # Used only when there is no existing host to clone. @I@ is the base indent. DEFAULT_FLAKE_ENTRY = dedent("""\ @I@@NAME@ = nixpkgs.lib.nixosSystem { @I@ inherit system; @I@ specialArgs = { inherit inputs; }; @I@ modules = [ @I@ ./hosts/@NAME@ @I@ home-manager.nixosModules.home-manager @I@ { @I@ home-manager = { @I@ useGlobalPkgs = true; @I@ useUserPackages = true; @I@ users.alex = import ./home/alex; @I@ extraSpecialArgs = { inherit inputs; }; @I@ sharedModules = [ inputs.plasma-manager.homeModules.plasma-manager ]; @I@ }; @I@ } @I@ ]; @I@}; """) _TOKEN_RE = re.compile(r"@[A-Z][A-Z_]*@") def render(template: str, **values: str) -> str: """Substitute ``@KEY@`` tokens. Unlike str.format this is brace-safe.""" out = template for key, value in values.items(): out = out.replace(f"@{key.upper()}@", value) leftover = _TOKEN_RE.search(out) if leftover: raise RuntimeError(f"BUG: unreplaced template token {leftover.group(0)}") return out # -------------------------------------------------------------------------- # flake.nix editing (pure functions: text in, text out) # -------------------------------------------------------------------------- @dataclass class FlakeEdit: new_src: str template_used: str | None stale_template_lines: list[str] = field(default_factory=list) def plan_flake_edit(src: str, name: str, template: str | None) -> FlakeEdit: """Return ``src`` with a new host entry for ``name`` inserted. If ``template`` names an existing host, its entry is cloned (renamed, with ``./hosts/