Skip to content

Instantly share code, notes, and snippets.

@skull-squadron
Created October 5, 2025 10:57
Show Gist options
  • Save skull-squadron/664502c6589b1a89833e98647b4862fb to your computer and use it in GitHub Desktop.
Save skull-squadron/664502c6589b1a89833e98647b4862fb to your computer and use it in GitHub Desktop.
Rust setup script to automatically install the correct toolchain, components, and tool crates
#!/usr/bin/env bash
set -eEuo pipefail
# Should live as: {{project}}/bin/setup
# Requires:
# - {{project}}/.config/setup-install-tool-crates.txt
# - {{project}}/rust-toolchain.toml
cd "${TOP_DIR:-$(cd "$(dirname "$0")" && cd .. && pwd)}"
readarray -t packages < <(sed 's/#.*//;/^[[:space:]]*$/d' .config/setup-install-tool-crates.txt)
toolchain=$(sed '/channel/!d;s/"$//;s/.*"//' rust-toolchain.toml)
readarray -t components < <(sed '/components/!d;s/"]$//;s/.*\["//;s/", "/\n/g' rust-toolchain.toml)
has() {
command -v "$@" &>/dev/null
}
die() {
echo >&2 "$@"
exit 1
}
rustup_component_list() {
rustup component list --toolchain "$1" |
sed '/installed/!d;s/[[:space:]].*//'
}
list_includes() {
local -n arr="$1"
local val="$2" i
for i in "${arr[@]}"; do
[[ "$i" = "$val" ]] && return 0
done
return 1
}
cargo_install() {
echo "cargo install $1 --locked"
cargo install "$1" --locked
}
sccache_checked=
check_sccache() {
if [[ "$sccache_checked" = 1 ]]; then
return
fi
sccache_checked=1
if ! has sccache && list_includes packages sccache; then
(
unset RUSTC_WRAPPER
cargo_install sccache
)
fi
}
has cargo || die 'Cargo is not installed. Please install Rust and Cargo first.'
has rustup || die 'Rustup is not installed. Please install Rustup first.'
if ! rustup toolchain list | grep -q "^$toolchain-"; then
echo "Installing Rust toolchain $toolchain..."
rustup toolchain install "$toolchain"
fi
for c in "${components[@]}"; do
if rustup_component_list "$toolchain" | grep -q "^$c-"; then
echo >&2 "Rust component $c is already installed, skipping."
continue
fi
echo "Installing Rust component $c..."
rustup component add --toolchain "$toolchain" "$c"
done
for p in "${packages[@]}"; do
if cargo install --list | grep -q "^$p v"; then
echo >&2 "$p crate utility is already installed, skipping."
continue
fi
check_sccache
[[ "$p" = sccache ]] || cargo_install "$p"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment