feat: improve scripts and write tests

This commit is contained in:
alexm committed 2026-10-11 07:22:13 -04:00
1 parent bc3091647e
commit cf4bd07a8e
32 files changed
+3817 -723

No files matched your search

+40 -37
View File
@@ -1,53 +1,56 @@
#!/usr/bin/env python3
"""
Print the nixosConfigurations defined in flake.nix.
Print the hosts defined under nixosConfigurations in flake.nix, one per line.
Parses flake.nix directly (no `nix eval`, so it works without nix tooling
and is fast). Brace-matches to find the closing `}` of nixosConfigurations
so it handles nested attrsets correctly.
Parses flake.nix textually (no `nix eval`), so it is fast and works without
Nix installed. Comments, strings and ${} interpolations are ignored, so a
brace or a commented-out host can't confuse it.
Exit codes: 0 ok, 1 flake missing/unreadable/unrecognized, 2 usage.
"""
import re
from __future__ import annotations
import argparse
import sys
from pathlib import Path
def list_hosts(flake_path: Path) -> list[str]:
src = flake_path.read_text()
m = re.search(r"nixosConfigurations\s*=\s*\{", src)
if not m:
return []
# Brace-match to find the matching closing }.
depth, i, close = 0, m.end() - 1, None
while i < len(src):
c = src[i]
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
close = i
break
i += 1
block = src[m.end():close] if close is not None else ""
return re.findall(
r"^[ \t]*([A-Za-z_][\w-]*)\s*=\s*nixpkgs\.lib\.nixosSystem",
block,
re.M,
)
sys.path.insert(0, str(Path(__file__).resolve().parent))
import nixflake # noqa: E402
from nixflake import FlakeError # noqa: E402
def main() -> int:
flake = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("flake.nix")
if not flake.is_file():
print(f"[-] not a file: {flake}", file=sys.stderr)
def list_hosts(src: str) -> list[str]:
return [h.name for h in nixflake.find_hosts(src)]
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("flake", nargs="?", default="flake.nix", type=Path, help="path to flake.nix (default: ./flake.nix)")
args = p.parse_args(argv)
if not args.flake.is_file():
print(f"[-] not a file: {args.flake}", file=sys.stderr)
return 1
for name in list_hosts(flake):
try:
src = args.flake.read_bytes().decode("utf-8")
hosts = list_hosts(src)
except (OSError, UnicodeDecodeError) as e:
print(f"[-] cannot read {args.flake}: {e}", file=sys.stderr)
return 1
except FlakeError as e:
print(f"[-] {args.flake}: {e}", file=sys.stderr)
return 1
if not hosts:
print(f"[!] no hosts defined in {args.flake}", file=sys.stderr)
for name in hosts:
print(name)
return 0
if __name__ == "__main__":
sys.exit(main())
try:
sys.exit(main())
except BrokenPipeError: # e.g. `list-hosts.py | head -1`
sys.exit(0)