# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#   Unai Martinez-Corral                                                                                               #
#                                                                                                                      #
# ==================================================================================================================== #
# Copyright 2020-2025 The pyTooling Authors                                                                            #
#                                                                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
# you may not use this file except in compliance with the License.                                                     #
# You may obtain a copy of the License at                                                                              #
#                                                                                                                      #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
#                                                                                                                      #
# Unless required by applicable law or agreed to in writing, software                                                  #
# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
# See the License for the specific language governing permissions and                                                  #
# limitations under the License.                                                                                       #
#                                                                                                                      #
# SPDX-License-Identifier: Apache-2.0                                                                                  #
# ==================================================================================================================== #
name: Publish Unit Test Results

on:
  workflow_call:
    inputs:
      ubuntu_image_version:
        description: 'Ubuntu image version.'
        required: false
        default: '24.04'
        type: string
      unittest_artifacts_pattern:
        required: false
        default: '*-UnitTestReportSummary-XML-*'
        type: string
      merged_junit_filename:
        description: 'Filename of the merged JUnit Test Summary.'
        required: false
        default: 'Unittesting.xml'
        type: string
      merged_junit_artifact:
        description: 'Name of the merged JUnit Test Summary artifact.'
        required: false
        default: ''
        type: string
      merge-input-dialect:
        description: 'JUnit dialect used to load and parse inputs for merging.'
        required: false
        default: 'pyTest-JUnit'
        type: string
      merge-output-dialect:
        description: 'JUnit dialect used for writing the merged report.'
        required: false
        default: 'pyTest-JUnit'
        type: string
      additional_merge_args:
        description: 'Additional merging arguments.'
        required: false
        default: '"--pytest=rewrite-dunder-init;reduce-depth:pytest.tests.unit"'
        type: string
      testsuite-summary-name:
        description: 'Set TestsuiteSummary name.'
        required: false
        default: ''
        type: string
      publish:
        description: 'Publish test report summary via Dorny Test-Reporter'
        required: false
        default: 'true'
        type: string
      report_title:
        description: 'Title of the summary report in the pipeline''s sidebar'
        required: false
        default: 'Unit Test Results'
        type: string
      dorny:
        description: 'Publish merged unittest results via Dorny Test-Reporter.'
        required: false
        default: 'true'
        type: string
      codecov:
        description: 'Publish merged unittest results to Codecov.'
        required: false
        default: 'false'
        type: string
      codecov_flags:
        description: 'Flags applied to the upload to Codecov'
        required: false
        default: 'unittest'
        type: string
    secrets:
      CODECOV_TOKEN:
        description: 'Token to push result to Codecov.'
        required: false

jobs:
  PublishTestResults:
    name: 📊 Publish Test Results
    runs-on: "ubuntu-${{ inputs.ubuntu_image_version }}"
    if: always()

    steps:
      - name: ⏬ Checkout repository
        uses: actions/checkout@v6

      - name: 📥 Download Artifacts
        uses: pyTooling/download-artifact@v7
        with:
          pattern: ${{ inputs.unittest_artifacts_pattern }}
          path:    artifacts

      - name: 🔎 Inspect extracted artifact (tarball)
        run: |
          tree -pash artifacts

      - name: 🔧 Install pyEDAA.Reports (JUunit Parser and Merger)
        run: |
          python -m pip install --disable-pip-version-check --break-system-packages -U pyEDAA.Reports

      - name: Rename JUnit files and move them all into 'junit/'
        run: |
          mkdir -p junit
          find artifacts/ -type f -path "*.xml" -exec sh -c 'cp -v $0 "junit/$(basename $(dirname $0)).$(basename $0)"' {} ';'
          tree -pash junit

      - name: 🔁 Merge JUnit Unit Test Summaries
        run: |
          if [[ -n "${{ inputs.testsuite-summary-name }}" ]]; then
            name="\"--name=${{ inputs.testsuite-summary-name }}\""
          fi
          pyedaa-reports -v unittest $name "--merge=${{ inputs.merge-input-dialect }}:junit/*.xml" ${{ inputs.additional_merge_args }} "--output=${{ inputs.merge-output-dialect }}:${{ inputs.merged_junit_filename }}"
          printf "%s\n" "cat ${{ inputs.merged_junit_filename }}"
          cat ${{ inputs.merged_junit_filename }}

      - name: 📊 Publish Unit Test Results
        uses: dorny/test-reporter@v2
        id: test-reporter
        if: ( inputs.dorny  == 'true' || inputs.publish  == 'true' ) && inputs.report_title != ''
        continue-on-error: true
        with:
          name: ${{ inputs.report_title }}
          path: ${{ inputs.merged_junit_filename }}
          reporter: java-junit

      - name: 📊 Publish unittest results at CodeCov
        uses: codecov/test-results-action@v1
        id: codecov
        if: inputs.codecov == 'true'
        continue-on-error: true
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          disable_search: true
          files: ${{ inputs.merged_junit_filename }}
          flags: ${{ inputs.codecov_flags }}
          fail_ci_if_error: true

      - name: 📤 Upload merged 'JUnit Test Summary' artifact
        uses: pyTooling/upload-artifact@v6
        if: inputs.merged_junit_artifact != ''
        with:
          name: ${{ inputs.merged_junit_artifact }}
          path: ${{ inputs.merged_junit_filename }}
          if-no-files-found: error
          retention-days: 1
          investigate: true

      - name: Generate error messages
        run: |
          exitCode=0
          if [[ "${{ steps.test-reporter.outcome }}" == "failure" ]]; then
            printf "❌ Dorney/Test-Reporter: %s\n" "Failed to publish unittest results."
            printf "::error title=%s::%s\n" "Dorney/Test-Reporter" "Failed to publish unittest results."
            exitCode=1
          else
            printf "✅ Dorney/Test-Reporter: No errors to report.\n"
          fi

          if [[ "${{ steps.codecov.outcome }}" == "failure" ]]; then
            printf "❌ CodeCov: %s\n" "Failed to publish unittest and code coverage results."
            printf "::error title=%s::%s\n" "CodeCov" "Failed to publish unittest and code coverage results."
            exitCode=1
          else
            printf "✅ CodeCov: No errors to report.\n"
          fi

          exit $exitCode
