name: Sonar Cloud

on:
  push:
    branches: [ master ]
    paths-ignore:
      - 'Docs/**'
      - '**.md'
  pull_request:
    branches: [ master ]
    paths-ignore:
      - 'Docs/**'
      - '**.md'

jobs:
  check-secret:
    runs-on: ubuntu-latest
    outputs:
      sonar-token: ${{ steps.sonar-token.outputs.defined }}
    steps:
      - id: sonar-token
        if: ${{ env.SONAR_TOKEN != '' }}
        run: echo "defined=true" >> $GITHUB_OUTPUT
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          
  build:
    name: Build
    needs: [check-secret]
    if: needs.check-secret.outputs.sonar-token == 'true'
    runs-on: ubuntu-latest
    env:
      BUILD_WRAPPER_OUT_DIR: build_wrapper_output_directory # Directory where build-wrapper output will be placed
      CLANG_VERSION: 14
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Shallow clones should be disabled for a better relevancy of analysis
      - name: Install sonar-scanner and build-wrapper
        uses: SonarSource/sonarcloud-github-c-cpp@v2
      - name: Configure CMake
        run: |
            cd ${{github.workspace}}/Build/
            ./cmake_linux_clang_gcc.sh ReleaseCoverage clang++-${{ env.CLANG_VERSION }}
      - name: Run build-wrapper
        run: |
          build-wrapper-linux-x86-64 --out-dir ${{ env.BUILD_WRAPPER_OUT_DIR }} cmake --build ${{github.workspace}}/Build/Linux_ReleaseCoverage
      - name: Run unit tests and create coverage report
        run: |
          cd ${{github.workspace}}/Build/Linux_ReleaseCoverage/
          cmake --build . --target test
          llvm-profdata-${{ env.CLANG_VERSION }} merge -sparse default.profraw -o default.profdata
          llvm-cov-${{ env.CLANG_VERSION }} show -format=text UnitTests -instr-profile=default.profdata > coverage.txt
      - name: Run sonar-scanner
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        run: |
          sonar-scanner --define sonar.cfamily.build-wrapper-output="${{ env.BUILD_WRAPPER_OUT_DIR }}" --define sonar.cfamily.llvm-cov.reportPath="${{github.workspace}}/Build/Linux_ReleaseCoverage/coverage.txt"
