commit db7183bf110016fb4a7b4fde7cdcff5a47b1ec1a Author: nyyu Date: Mon Jun 24 16:54:05 2024 +0200 Add sonar.sh diff --git a/sonar.sh b/sonar.sh new file mode 100755 index 0000000..b651ff1 --- /dev/null +++ b/sonar.sh @@ -0,0 +1,38 @@ +#!/bin/bash +set -e + +if ! command -v jq > /dev/null; then + mkdir -p /tmp/bin + wget -q https://nexus.nyyu.dev/repository/files/bin/jq-linux64 -O /tmp/bin/jq + chmod +x /tmp/bin/jq + export PATH="/tmp/bin:$PATH" +fi + +sonarOpts=(-Dsonar.branch.name="${CI_COMMIT_BRANCH}") +if [[ -n "${CI_COMMIT_PULL_REQUEST}" ]]; then + sonarOpts=(-Dsonar.pullrequest.key="${CI_COMMIT_PULL_REQUEST}" -Dsonar.pullrequest.branch="${CI_COMMIT_SOURCE_BRANCH}" -Dsonar.pullrequest.base="${CI_COMMIT_TARGET_BRANCH}") +fi + +sonar-scanner -Dsonar.working.directory=/tmp/.scannerwork -Dsonar.qualitygate.wait=true "${sonarOpts[@]}" || true + +projectKey=$(grep 'projectKey=' /tmp/.scannerwork/report-task.txt | cut -d'=' -f2) +taskId=$(grep 'ceTaskId=' /tmp/.scannerwork/report-task.txt | cut -d'=' -f2) +analysisId=$(wget -q -O- --header "Authorization: Bearer ${SONAR_TOKEN}" "${SONAR_HOST_URL}/api/ce/task?id=${taskId}" | jq -r '.task.analysisId') +report=$(wget -q -O- --header "Authorization: Bearer ${SONAR_TOKEN}" "${SONAR_HOST_URL}/api/qualitygates/project_status?analysisId=${analysisId}") + +status=$(echo "${report}" | jq -r '.projectStatus.status') +conditions=$(echo "${report}" | jq -r '.projectStatus.conditions[] | "\n* " + .metricKey + "\n - Status: " + .status + "\n - Value: " + .actualValue') +[[ -n "${CI_COMMIT_PULL_REQUEST}" ]] && link="pullRequest=${CI_COMMIT_PULL_REQUEST}" || link="branchName=${CI_COMMIT_BRANCH}" + +comment="## Quality Gate: **${status}** +${conditions} + +[See analysis details](${SONAR_HOST_URL}/dashboard?id=${projectKey}&${link})" + +echo "$comment" + +if [[ -n "${CI_COMMIT_PULL_REQUEST}" ]]; then + comment=$(echo "${comment}" | jq -R -s '.') + wget -q -O /dev/null --post-data "{\"body\": $comment}" --header 'Content-Type: application/json' --header "Authorization: Bearer ${GITEA_TOKEN}" \ + "${CI_FORGE_URL}/api/v1/repos/${CI_REPO}/issues/${CI_COMMIT_PULL_REQUEST}/comments" +fi