#!/usr/bin/env bash # # Recompute flake.nix's Go `vendorHash` (and create flake.lock if missing) using # Docker, so you don't need Nix installed locally. # # Run this after changing dependencies (go.mod / go.sum). Editing application # code does NOT require it — vendorHash only covers the fetched module sources. # # ./scripts/update_flake.sh # # Overridable via env: NIX_IMAGE (default nixos/nix), NIX_VOLUME (a Docker # volume used to cache the Nix store between the two builds). set -euo pipefail NIX_IMAGE="${NIX_IMAGE:-nixos/nix:latest}" NIX_VOLUME="${NIX_VOLUME:-deepsky-nix-store}" FAKE_HASH="sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" command -v docker >/dev/null || { echo "error: docker is required" >&2; exit 1; } command -v git >/dev/null || { echo "error: git is required" >&2; exit 1; } cd "$(git rev-parse --show-toplevel)" FLAKE="flake.nix" [ -f "$FLAKE" ] || { echo "error: $FLAKE not found" >&2; exit 1; } # Restore flake.nix if we bail out partway through. backup="$(mktemp)" cp "$FLAKE" "$backup" cleanup() { if [ "${1:-1}" != "ok" ]; then echo "error: aborting; restoring $FLAKE" >&2 cp "$backup" "$FLAKE" fi rm -f "$backup" } trap 'cleanup fail' EXIT # Portable in-place rewrite of the vendorHash line (BSD/GNU sed differ on -i). set_vendor_hash() { local tmp tmp="$(mktemp)" sed -E 's|vendorHash = "[^"]*";|vendorHash = "'"$1"'";|' "$FLAKE" >"$tmp" mv "$tmp" "$FLAKE" grep -q "vendorHash = \"$1\";" "$FLAKE" || { echo "error: failed to rewrite vendorHash in $FLAKE" >&2; exit 1; } } run_nix() { docker run --rm \ -e NIX_CONFIG="experimental-features = nix-command flakes sandbox = false" \ -v "$PWD":/work -v "$NIX_VOLUME":/nix -w /work \ "$NIX_IMAGE" "$@" } # Nix flakes only see git-tracked files, so the flake must be staged at least. git add "$FLAKE" # 1. Force a known-wrong hash so the build reports the correct one. set_vendor_hash "$FAKE_HASH" git add "$FLAKE" echo "==> Computing vendorHash via Docker (this first build is meant to fail)…" log="$(mktemp)" run_nix nix build --no-link '.#default' --print-build-logs >"$log" 2>&1 || true real="$(grep -oE 'got:[[:space:]]+sha256-[A-Za-z0-9+/]{43}=' "$log" | grep -oE 'sha256-[A-Za-z0-9+/]{43}=' | tail -n1 || true)" if [ -z "$real" ]; then echo "error: could not determine vendorHash. Full build output:" >&2 cat "$log" >&2 rm -f "$log" exit 1 fi rm -f "$log" echo "==> vendorHash: $real" # 2. Write the real hash, then verify the build and pin flake.lock. set_vendor_hash "$real" git add "$FLAKE" echo "==> Verifying build and writing flake.lock…" run_nix nix build --no-link '.#default' --print-build-logs git add flake.lock 2>/dev/null || true trap - EXIT cleanup ok echo "==> Done. Review and commit flake.nix and flake.lock."