57 lines
1.7 KiB
Python
Executable File
57 lines
1.7 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Print the hosts defined under nixosConfigurations in flake.nix, one per line.
|
|
|
|
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.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
import nixflake # noqa: E402
|
|
from nixflake import FlakeError # noqa: E402
|
|
|
|
|
|
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
|
|
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__":
|
|
try:
|
|
sys.exit(main())
|
|
except BrokenPipeError: # e.g. `list-hosts.py | head -1`
|
|
sys.exit(0)
|