name: Setup Rust and Prisma
description: Setup Rust and Prisma
inputs:
  target:
    description: toolchain target triple
    required: false
  save-cache:
    description: Whether to save the Rust cache
    required: false
    default: 'false'
  restore-cache:
    description: Whether to restore the Rust cache
    required: false
    default: 'true'
runs:
  using: 'composite'
  steps:
    - name: Install Rust
      id: toolchain
      uses: IronCoreLabs/rust-toolchain@v1
      with:
        target: ${{ inputs.target }}
        components: clippy, rustfmt

    - name: Cache Rust Dependencies
      if: ${{ inputs.restore-cache == 'true' }}
      uses: Swatinem/rust-cache@v2
      with:
        key: ${{ inputs.target }}
        save-if: ${{ inputs.save-cache }}
        shared-key: stable-cache

    - name: Cargo config.toml
      shell: bash
      run: echo '{}' | npx -y mustache - .cargo/config.toml.mustache .cargo/config.toml

    - name: Restore cached Prisma codegen
      id: cache-prisma-restore
      uses: actions/cache/restore@v4
      with:
        key: prisma-1-${{ runner.os }}-${{ hashFiles('./core/prisma/*', './crates/sync-generator/*', './Cargo.*') }}
        path: crates/prisma/src/**/*.rs

    - name: Generate Prisma client
      working-directory: core
      if: ${{ steps.cache-prisma-restore.outputs.cache-hit != 'true' }}
      shell: bash
      run: |
        set -euxo pipefail
        cargo prisma generate

        # Check if a new migration should be created due to changes in the schema
        cargo prisma migrate dev -n test --create-only --skip-generate
        _new_migrations="$(
          git ls-files --others --exclude-standard \
            | { grep '^prisma/migrations/' || true; } \
            | xargs sh -euxc '[ "$#" -lt 2 ] || grep -L "$@" || true' sh 'This is an empty migration' \
            | wc -l \
            | awk '{$1=$1};1'
        )"
        if [ "$_new_migrations" -gt 0 ]; then
            echo "::error file=core/prisma/schema.prisma,title=Missing migration::New migration should be generated due to changes in prisma schema"
            case "$GITHUB_REF" in
                "refs/heads/main" | "refs/heads/gh-readonly-queue/main/"* | "refs/tags/"*)
                    # Fail action if we are on main or a release tag, to avoid releasing an app with a broken db
                    exit 1
                    ;;
            esac
        fi

    - name: Save Prisma codegen
      id: cache-prisma-save
      if: ${{ steps.cache-prisma-restore.outputs.cache-hit != 'true' && (github.ref == 'refs/heads/main' || inputs.save-cache == 'true') }}
      uses: actions/cache/save@v4
      with:
        key: ${{ steps.cache-prisma-restore.outputs.cache-primary-key }}
        path: crates/prisma/src/**/*.rs
