on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]

name: Generate R package using savvy

jobs:
  generate_pkg:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@nightly

      - name: check wrapper file generation
        run: |
          cargo run --manifest-path ./savvy-cli/Cargo.toml -- update ./R-package/

          # If there's any change, exit with non-zero status
          # (the code is derived from https://stackoverflow.com/a/3879077)
          git add ./R-package/
          git update-index --refresh
          if ! git diff-index --quiet HEAD -- ./R-package/; then
            echo
            echo "some change on wrapper file generation was detected!"
            echo
            git diff ./R-package/
            exit 1
          fi

      - uses: r-lib/actions/setup-r@v2
        with:
          use-public-rspm: true

      - uses: r-lib/actions/setup-r-dependencies@v2
        with:
          extra-packages: |
            any::rcmdcheck
            any::devtools
            any::usethis
          working-directory: R-package  # this isn't the actual R package, but this is needed to avoid an error

      - name: create tempdir
        run: echo "TEMP_DIR=$(mktemp -d)" >> ${GITHUB_ENV}

      - name: create package
        run: |
          Rscript -e "usethis::create_package('${{ runner.temp }}/sawy')"
          cargo run --manifest-path ./savvy-cli/Cargo.toml -- init ${{ runner.temp }}/sawy
          cd ${{ runner.temp }}/sawy
          sed -i '/savvy/ s|".*"|{ path = "${{ github.workspace }}" }|' src/rust/Cargo.toml
          Rscript -e "usethis::use_mit_license('foo')"
          Rscript -e "devtools::document()"

      - uses: r-lib/actions/check-r-package@v2
        with:
          args: 'c("--no-manual")'
          working-directory: ${{ runner.temp }}/sawy
        env:
          MAKEFLAGS: -j2   # cf. https://github.com/yutannihilation/savvy/issues/355#issuecomment-2740005471
          PROFILE_OVERRIDE: dev

      - name: Run Rust tests
        run: |
          cargo test --manifest-path ${{ runner.temp }}/sawy/src/rust/Cargo.toml
          cargo r-test ${{ runner.temp }}/sawy/src/rust
