@@ -352,16 +352,6 @@ if [[ -z $flake && -e /etc/nixos/flake.nix && -z $noFlake ]]; then
352352 flake="$(dirname "$(readlink -f /etc/nixos/flake.nix)")"
353353fi
354354
355−# Re-execute nixos-rebuild from the Nixpkgs tree.
356−# FIXME: get nixos-rebuild from $flake.
357−if [[ -z $_NIXOS_REBUILD_REEXEC && -n $canRun && -z $fast && -z $flake ]]; then
358− if p=$(runCmd nix-build --no-out-link --expr 'with import <nixpkgs/nixos> {}; config.system.build.nixos-rebuild' "${extraBuildFlags[@]}"); then
359− export _NIXOS_REBUILD_REEXEC=1
360− runCmd exec "$p/bin/nixos-rebuild" "${origArgs[@]}"
361− exit 1
362− fi
363−fi
364−
365355# For convenience, use the hostname as the default configuration to
366356# build from the flake.
367357if [[ -n $flake ]]; then
@@ -380,6 +370,40 @@ if [[ -n $flake ]]; then
380370 fi
381371fi
382372
373+
374+tmpDir=$(mktemp -t -d nixos-rebuild.XXXXXX)
375+
376+cleanup() {
377+ for ctrl in "$tmpDir"/ssh-*; do
378+ ssh -o ControlPath="$ctrl" -O exit dummyhost 2>/dev/null || true
379+ done
380+ rm -rf "$tmpDir"
381+}
382+trap cleanup EXIT
383+
384+
385+# Re-execute nixos-rebuild from the Nixpkgs tree.
386+if [[ -z $_NIXOS_REBUILD_REEXEC && -n $canRun && -z $fast ]]; then
387+ if [[ -z $flake ]]; then
388+ if p=$(runCmd nix-build --no-out-link --expr 'with import <nixpkgs/nixos> {}; config.system.build.nixos-rebuild' "${extraBuildFlags[@]}"); then
389+ SHOULD_REEXEC=1
390+ fi
391+ else
392+ runCmd nix "${flakeFlags[@]}" build --out-link "${tmpDir}/nixos-rebuild" "$flake#$flakeAttr.config.system.build.nixos-rebuild" "${extraBuildFlags[@]}" "${lockFlags[@]}"
393+ if p=$(readlink -e "${tmpDir}/nixos-rebuild"); then
394+ SHOULD_REEXEC=1
395+ fi
396+ fi
397+
398+ if [[ -n $SHOULD_REEXEC ]]; then
399+ export _NIXOS_REBUILD_REEXEC=1
400+ # Manually call cleanup as the EXIT trap is not triggered when using exec
401+ cleanup
402+ runCmd exec "$p/bin/nixos-rebuild" "${origArgs[@]}"
403+ exit 1
404+ fi
405+fi
406+
383407# Find configuration.nix and open editor instead of building.
384408if [ "$action" = edit ]; then
385409 if [[ -z $flake ]]; then
@@ -394,19 +418,8 @@ if [ "$action" = edit ]; then
394418 exit 1
395419fi
396420
397−
398−tmpDir=$(mktemp -t -d nixos-rebuild.XXXXXX)
399421SSHOPTS="$NIX_SSHOPTS -o ControlMaster=auto -o ControlPath=$tmpDir/ssh-%n -o ControlPersist=60"
400422
401−cleanup() {
402− for ctrl in "$tmpDir"/ssh-*; do
403− ssh -o ControlPath="$ctrl" -O exit dummyhost 2>/dev/null || true
404− done
405− rm -rf "$tmpDir"
406−}
407−trap cleanup EXIT
408−
409−
410423# First build Nix, since NixOS may require a newer version than the
411424# current one.
412425if [[ -n "$rollback" || "$action" = dry-build ]]; then