# Setup Rust / Cargo environment, tools, and shell completions _setup_cargo() { [ -n "$ZSH_VERSION" ] && setopt localoptions nonomatch nullglob _add_to_path() { [ -d "$1" ] || return 0 case ":$PATH:" in *":$1:"*) ;; *) PATH="$1:$PATH"; export PATH ;; esac } # 1. Respect or detect CARGO_HOME and RUSTUP_HOME if [ -z "$CARGO_HOME" ] && [ -d "$HOME/.cargo" ]; then export CARGO_HOME="$HOME/.cargo" fi if [ -z "$RUSTUP_HOME" ] && [ -d "$HOME/.rustup" ]; then export RUSTUP_HOME="$HOME/.rustup" fi _cargo_dir="${CARGO_HOME:-$HOME/.cargo}" # 2. Source official env file if present, or add bin directory to PATH if [ -f "$_cargo_dir/env" ]; then \. "$_cargo_dir/env" elif [ -d "$_cargo_dir/bin" ]; then _add_to_path "$_cargo_dir/bin" fi # 3. Fallback search for system or alternative Cargo/Rust locations if not in PATH if ! command -v cargo >/dev/null 2>&1; then for _cand in \ "/usr/local/cargo/bin" \ "/opt/homebrew/opt/rust/bin" \ "/usr/local/opt/rust/bin" \ "/opt/homebrew/bin" \ "/usr/local/bin" \ "$HOME/.local/bin" do if [ -x "$_cand/cargo" ]; then _add_to_path "$_cand" break fi done fi # 4. Enable shell completions if available and files are present if command -v cargo >/dev/null 2>&1; then _rustup_dir="${RUSTUP_HOME:-$HOME/.rustup}" if [ -n "$BASH_VERSION" ]; then for _comp in \ "$_rustup_dir"/toolchains/*/etc/bash_completion.d/cargo \ "$_rustup_dir"/toolchains/*/etc/bash_completion.d/rustup \ "/opt/homebrew/etc/bash_completion.d/cargo" \ "/usr/share/bash-completion/completions/cargo" do if [ -r "$_comp" ]; then \. "$_comp" fi done elif [ -n "$ZSH_VERSION" ]; then for _zsh_comp_dir in "$_rustup_dir"/toolchains/*/share/zsh/site-functions; do if [ -d "$_zsh_comp_dir" ]; then case " ${fpath[*]} " in *" $_zsh_comp_dir "*) ;; *) fpath=("$_zsh_comp_dir" "${fpath[@]}") ;; esac fi done fi fi } _setup_cargo unset -f _setup_cargo _add_to_path