grapevine/bin/nix-build-and-cache
Benjamin Lee 3f89bc4a7c
allow 'nix build'-specific nix-build-and-cache args
We need --no-link for the complement script.

I picked the syntax for this as an analogy with
'cargo rustc --cargo-args -- --rustc-args', but not sure how I feel
about it.
2024-09-24 11:25:52 -07:00

98 lines
2.6 KiB
Bash
Executable file

#!/usr/bin/env bash
set -euo pipefail
toplevel="$(git rev-parse --show-toplevel)"
# Build and cache the specified arguments
#
# Usage: nix-build-and-cache just [args...] -- [build-only-args...]
#
# Arguments after the '--' (build-only-args) will only be passed to the
# 'nix build' command, while arguments before '--' will also be passed to any
# other nix command using the installable list. This is useful for things like
# '--no-link', which are only relevant to 'nix build'.
just() {
build_args=()
args=()
build_only_mode=0
for arg in "$@"; do
if [ "$build_only_mode" = 1 ]; then
build_args+=( "$arg" )
elif [ "$arg" = "--" ]; then
# Everything after the -- is passed only to 'nix build'
build_only_mode=1
else
args+=( "$arg" )
build_args+=( "$arg" )
fi
done
if command -v nom &> /dev/null; then
nom build "${build_args[@]}"
else
nix build "${build_args[@]}"
fi
if [ -z ${ATTIC_TOKEN+x} ]; then
echo "\$ATTIC_TOKEN is unset, skipping uploading to the binary cache"
return
fi
nix run --inputs-from "$toplevel" attic -- \
login \
"$ATTIC_SERVER" \
"$ATTIC_ENDPOINT" \
"$ATTIC_TOKEN"
# Find all output paths of the installables and their build dependencies
readarray -t derivations < <(nix path-info --derivation "${args[@]}")
cache=()
for derivation in "${derivations[@]}"; do
cache+=(
"$(nix-store --query --requisites --include-outputs "$derivation")"
)
done
# Upload them to Attic
#
# Use `xargs` and a here-string because something would probably explode if
# several thousand arguments got passed to a command at once. Hopefully no
# store paths include a newline in them.
(
IFS=$'\n'
nix shell --inputs-from "$toplevel" attic -c xargs \
attic push "$ATTIC_SERVER:$ATTIC_CACHE" <<< "${cache[*]}"
)
}
# Build and cache things needed for CI
ci() {
cache=(
--inputs-from "$toplevel"
# Keep sorted
"$toplevel#devShells.x86_64-linux.default"
"$toplevel#devShells.x86_64-linux.all-features"
attic#default
nixpkgs#direnv
nixpkgs#jq
nixpkgs#nix-direnv
)
just "${cache[@]}"
}
# Build and cache all the package outputs
packages() {
declare -a cache="($(
nix flake show --json 2> /dev/null |
nix run --inputs-from "$toplevel" nixpkgs#jq -- \
-r \
'.packages."x86_64-linux" | keys | map("'"$toplevel"'#" + .) | @sh'
))"
just "${cache[@]}"
}
eval "$@"