name: setup rust
description: Setup rust toolchain and caches.

inputs:
  toolchain-version:
    description: Rust toolchain version to use.
    required: true

  builder-triple:
    description: Target-triple of builder system.
    required: true

  targets:
    description: Comma-separated list of additional targets to install.
    default: ""

  components:
    description: Comma-separated list of components installed with the toolchain.
    default: ""
    required: true

  cache-key:
    description: Cache-busting key. If you set this to anything other than its default, it will bust all caches and prevent sharing caches with other workflows.
    required: true
    default: init

outputs:
  toolchain_cache_hit:
    description: Did the toolchain cache hit?
    value: ${{ steps.cache-rust-toolchain.outputs.cache-hit }}

  target_cache_hit:
    description: Did the target cache hit?
    value: ${{ steps.cache-rust-target.outputs.cache-hit }}

runs:
  using: composite

  steps:
    - name: Cache Rust toolchain
      id: cache-rust-toolchain
      uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
      with:
        path: |
          ~/.cargo/bin/
          ~/.cargo/registry/index/
          ~/.cargo/registry/cache/
          ~/.cargo/git/db/
          ~/.rustup/toolchains
        key: rust-toolchain-${{ inputs.cache-key }}-${{ inputs.builder-triple }}-${{ inputs.toolchain-version }}-targets=${{ env.targets }}-components=${{ case(inputs.components == '', 'none', inputs.components) }}
        restore-keys:
          rust-toolchain-${{ inputs.cache-key }}-${{ inputs.builder-triple }}-${{ inputs.toolchain-version }}-targets=${{ env.targets }}-components=
          rust-toolchain-${{ inputs.cache-key }}-${{ inputs.builder-triple }}-${{ inputs.toolchain-version }}-targets=

    - name: Install Rust toolchain
      id: install-toolchain
      if: steps.cache-rust-toolchain.outputs.cache-hit != 'true' || inputs.builder-triple == 'nightly' || inputs.builder-triple == 'beta' || inputs.builder-triple == 'stable'
      uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9 # master 4/22/2026
      with:
        toolchain: ${{ inputs.toolchain-version }}
        components: ${{ inputs.components }}
        targets: ${{ inputs.builder-triple }},${{ inputs.targets }}

    - name: Cache target/
      id: cache-rust-target
      uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
      with:
        path: |
          target/
        key: rust-target-${{ inputs.cache-key }}-${{ inputs.builder-triple }}-${{ inputs.toolchain-version }}-${{ hashFiles('**/Cargo.lock') }}
        restore-keys:
          rust-target-${{ inputs.cache-key }}-${{ inputs.builder-triple }}-${{ inputs.toolchain-version }}-

    - name: Set toolchain override
      shell: bash
      run: rustup override set ${{ inputs.toolchain-version }}
