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

+129 -68
View File
@@ -1,82 +1,143 @@
#!/usr/bin/env bash
# Generate hardware.nix for a registered host.
# Generate hosts/<name>/hardware.nix for a registered host.
#
# Run this on the NEW machine (the one whose hardware you want captured),
# inside this repo. Two contexts are auto-detected:
# Run this on the NEW machine (the one whose hardware you want to capture),
# from inside this repo. It works in two situations, detected automatically:
#
# * from the installer, with the target system mounted at /mnt:
# uses `nixos-generate-config --root /mnt`
# * on an already-running NixOS system: describes the running system
#
# The new file is generated into a temporary file and only moved into place
# once it looks valid, so a failure never destroys an existing hardware.nix.
set -euo pipefail
NAME=""
REPO_ROOT="."
SCRIPT_DIR="$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")" && pwd -P)"
# shellcheck source=lib/common.sh
source "$SCRIPT_DIR/lib/common.sh"
while (($#)); do
case "$1" in
--repo-root) REPO_ROOT="${2:?missing path}"; shift 2 ;;
-h|--help)
awk '/^#!/ {next} /^[^#]/ {exit} {sub(/^# ?/, ""); print}' "$0"
exit 0 ;;
-*) echo "[-] unknown flag: $1" >&2; exit 1 ;;
*)
if [[ -z "$NAME" ]]; then
NAME="$1"; shift
else
echo "[-] unexpected positional arg: $1" >&2; exit 1
fi
;;
esac
done
usage() {
cat <<'EOF'
Usage: capture-hardware.sh [options] NAME
if [[ -z "$NAME" ]]; then
echo "[-] usage: $0 <name>" >&2
exit 1
fi
NAME host to capture (must already exist under hosts/;
create it with `just register-host NAME`)
--repo-root DIR repository root (default: current directory)
--install-root DIR where the installer mounts the target (default: /mnt)
-f, --force overwrite an existing, non-placeholder hardware.nix
without asking
-h, --help show this help
cd "$REPO_ROOT"
target="hosts/${NAME}/hardware.nix"
Exit codes: 0 ok, 1 usage/precondition error, 2 not on NixOS, 3 generation failed.
EOF
}
if [[ ! -d "hosts/${NAME}" ]]; then
echo "[-] hosts/${NAME} does not exist." >&2
echo " Run \`just register-host ${NAME}\` first." >&2
exit 1
fi
# Placeholder files written by register-host.py contain this marker.
PLACEHOLDER_MARKER="PLACEHOLDER hardware.nix"
if ! command -v nixos-generate-config >/dev/null 2>&1; then
echo "[-] nixos-generate-config not found." >&2
echo " Run this on a NixOS machine (running system or installer ISO)." >&2
exit 2
fi
NAME="" REPO_ROOT="." INSTALL_ROOT="/mnt" FORCE=0
TMP_FILE=""
cleanup() { [[ -z "$TMP_FILE" ]] || rm -f -- "$TMP_FILE"; }
trap cleanup EXIT
# Detect installer-mounted-at-/mnt vs running-system.
extra_args=()
if mountpoint -q /mnt 2>/dev/null && [[ -d /mnt/etc ]]; then
echo "[+] Detected mounted target at /mnt — using --root /mnt"
extra_args+=(--root /mnt)
elif mountpoint -q /mnt 2>/dev/null; then
echo "[!] /mnt is mounted but doesn't look like a NixOS target (no /mnt/etc)."
echo " Continuing as if on a running system. Edit hardware.nix afterwards"
echo " if disks aren't permanent."
fi
# Confirm before overwriting a non-placeholder hardware.nix.
if [[ -f "$target" ]] && ! grep -q 'PLACEHOLDER hardware.nix' "$target"; then
echo "[!] $target already exists and doesn't look like a placeholder." >&2
if [[ -t 0 ]]; then
read -r -p "Overwrite? (yes/[no]) " confirm
[[ "$confirm" == "yes" ]] || { echo "aborted."; exit 1; }
else
echo "[-] non-interactive; refusing to overwrite. Delete $target first." >&2
exit 1
parse_args() {
while (($#)); do
case "$1" in
--repo-root) need_value "$@"; REPO_ROOT="$2"; shift 2 ;;
--install-root) need_value "$@"; INSTALL_ROOT="$2"; shift 2 ;;
-f|--force) FORCE=1; shift ;;
-h|--help) usage; exit 0 ;;
--) shift; break ;;
-*) die "unknown option: $1 (see --help)" 1 ;;
*)
[[ -z "$NAME" ]] || die "unexpected extra argument: $1" 1
NAME="$1"; shift ;;
esac
done
# Anything left after `--` is the (single) name.
if (($#)); then
[[ -z "$NAME" && $# -eq 1 ]] || die "unexpected extra argument(s): $*" 1
NAME="$1"
fi
fi
[[ -n "$NAME" ]] || { usage >&2; exit 1; }
valid_hostname "$NAME" \
|| die "invalid hostname '$NAME' (lowercase letters, digits, hyphens; must start with a letter)" 1
}
echo "[+] Generating hardware config..."
# The redirect runs in the user's shell BEFORE sudo, so the file is owned
# by the invoking user. sudo is needed because nixos-generate-config
# probes /proc, /sys, and may need to read mounted filesystems.
sudo nixos-generate-config --show-hardware-config "${extra_args[@]}" > "$target"
echo "[+] Wrote $target"
main() {
parse_args "$@"
if command -v git >/dev/null && git rev-parse >/dev/null 2>&1; then
echo "[+] git diff:"
git --no-pager diff -- "$target" || true
fi
[[ -d "$REPO_ROOT" ]] || die "repo root not found: $REPO_ROOT" 1
cd -- "$REPO_ROOT"
[[ -f flake.nix ]] || die "no flake.nix in $PWD; run from the repo root or pass --repo-root" 1
local host_dir="hosts/${NAME}"
local target="${host_dir}/hardware.nix"
[[ -d "$host_dir" ]] || die "${host_dir} does not exist. Run \`just register-host ${NAME}\` first." 1
command -v nixos-generate-config >/dev/null 2>&1 \
|| die "nixos-generate-config not found. Run this on a NixOS machine (running system or installer ISO)." 2
# sudo is only needed when we aren't root already.
local -a as_root=()
if ((EUID != 0)); then
command -v sudo >/dev/null 2>&1 || die "not root and sudo is not installed" 1
as_root=(sudo)
fi
# Installer with the target mounted vs. running system.
local -a extra_args=()
if command -v mountpoint >/dev/null 2>&1 && mountpoint -q -- "$INSTALL_ROOT" 2>/dev/null; then
if [[ -d "$INSTALL_ROOT/etc" ]]; then
log "Detected mounted target at $INSTALL_ROOT; using --root $INSTALL_ROOT"
extra_args=(--root "$INSTALL_ROOT")
else
warn "$INSTALL_ROOT is mounted but doesn't look like a NixOS target (no etc/)."
warn "Continuing as if on a running system; check the filesystems in hardware.nix afterwards."
fi
fi
# Don't silently replace a real, hand-edited hardware.nix.
if [[ -e "$target" ]] && ! grep -q -- "$PLACEHOLDER_MARKER" "$target" 2>/dev/null; then
warn "$target already exists and is not a placeholder."
if ((FORCE)); then
warn "--force given; overwriting."
elif [[ -t 0 ]]; then
local confirm
read -r -p "Overwrite? (yes/[no]) " confirm || confirm=""
[[ "$confirm" == "yes" ]] || die "aborted." 1
else
die "non-interactive; refusing to overwrite. Pass --force or delete $target first." 1
fi
fi
# Generate into a temp file in the same directory (so the final mv is an
# atomic rename), validate it, then move it into place.
TMP_FILE="$(mktemp "${host_dir}/.hardware.nix.XXXXXX")"
log "Generating hardware config..."
# The redirect is performed by this shell before sudo runs, so the file is
# owned by the invoking user. sudo is needed because nixos-generate-config
# probes /proc, /sys and mounted filesystems.
if ! "${as_root[@]+"${as_root[@]}"}" nixos-generate-config --show-hardware-config \
"${extra_args[@]+"${extra_args[@]}"}" > "$TMP_FILE"; then
die "nixos-generate-config failed; $target was left untouched." 3
fi
if [[ ! -s "$TMP_FILE" ]] || ! grep -Eq '^\{' "$TMP_FILE"; then
die "nixos-generate-config produced no usable output; $target was left untouched." 3
fi
chmod 644 -- "$TMP_FILE"
mv -f -- "$TMP_FILE" "$target"
TMP_FILE=""
log "Wrote $target"
if command -v git >/dev/null 2>&1 && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
log "git diff:"
git --no-pager diff -- "$target" || true
info "Flakes only see git-tracked files: git add $target"
fi
}
main "$@"