From 7052db8b59db7dd6883ecbaacb302f29f160df07 Mon Sep 17 00:00:00 2001
From: Pierre Smeyers <pierre.smeyers@gmail.com>
Date: Wed, 6 Jul 2022 19:34:01 +0200
Subject: [PATCH] chore: improve auto detect MR

---
 README.md                     | 12 ++++++++----
 templates/gitlab-ci-sonar.yml | 35 +++++++++++++++++++++--------------
 2 files changed, 29 insertions(+), 18 deletions(-)

diff --git a/README.md b/README.md
index 52b094f..9598700 100644
--- a/README.md
+++ b/README.md
@@ -45,10 +45,14 @@ Those is a great SonarQube features but it assumes one of the following conditio
 
 If you're not in one of those cases, then you shall disable this feature by setting `SONAR_BRANCH_ANALYSIS_DISABLED`.
 
-If you leave the feature enabled, if `SONAR_GITLAB_TOKEN` is provided, the template will try to autodetect (using GitLab APIs) an opened merge request matching the current branch:
-
-* If one is found, a SonarQube [Pull Request Analysis](https://docs.sonarqube.org/latest/analysis/pull-request/) will be made.
-* Otherwise, a simple [Branch Analysis](https://docs.sonarqube.org/latest/branches/overview/) is performed on the current branch.
+If you leave the feature enabled, the template will try to auto-detect whether the current branch is associated to an open Merge Request or not:
+
+1. if you're running [Merge Request pipelines](https://docs.gitlab.com/ee/ci/yaml/workflow.html#switch-between-branch-pipelines-and-merge-request-pipelines), 
+   then the template will automatically detect the MR,
+2. if you're running [branch pipelines](https://docs.gitlab.com/ee/ci/yaml/workflow.html#switch-between-branch-pipelines-and-merge-request-pipelines)
+   instead, the template will have to call GitLab APIs to determine whether the current branch is associated to an open Merge Request.
+   This will only be possible if you provided `SONAR_GITLAB_TOKEN`. 
+   Otherwise, a simple [Branch Analysis](https://docs.sonarqube.org/latest/branches/overview/) is performed on the current branch.
 
 ### About Sonar GitLab plugin
 
diff --git a/templates/gitlab-ci-sonar.yml b/templates/gitlab-ci-sonar.yml
index f810e6b..fdcf668 100644
--- a/templates/gitlab-ci-sonar.yml
+++ b/templates/gitlab-ci-sonar.yml
@@ -159,27 +159,34 @@ stages:
       log_info "Merge Request pipeline detected: let SonarScanner handle..."
       return
     fi
-    if [[ -n "$SONAR_GITLAB_TOKEN" ]]
-    then 
-      wget -q "$CI_API_V4_URL/projects/${CI_PROJECT_ID}/merge_requests?state=opened&source_branch=${CI_COMMIT_REF_NAME}&private_token=$SONAR_GITLAB_TOKEN" -O mr.json || log_warn "Failed requesting GitLab API: check \$SONAR_GITLAB_TOKEN"
-      if [[ -f mr.json ]] && [[ "$(cat mr.json)" != "[]" ]]
+    if [[ "$CI_OPEN_MERGE_REQUESTS" ]]
+    then
+      # we are in a branch pipeline associated with at least one MR: try to use GitLab APIs to get details
+      if [[ "$SONAR_GITLAB_TOKEN" ]]
       then
-        mr_title=$(sed -E 's/\[\{[^{]*"title":"([^"]*)".*/\1/g' < mr.json)
-        mr_target=$(sed -E 's/\[\{[^{]*"target_branch":"([^"]*)".*/\1/g' < mr.json)
-        mr_id=$(sed -E 's/\[\{[^{]*"iid":([0-9]+).*/\1/g' < mr.json)
-        log_info "Merge Request \\e[33;1m$mr_title\\e[0m detected associated to this branch: trigger MR analysis..."
-        export sonar_mr_args="-Dsonar.pullrequest.key=$mr_id -Dsonar.pullrequest.branch=${CI_COMMIT_REF_NAME} -Dsonar.pullrequest.base=$mr_target"
-      else 
-        log_info "No Merge Request associated to this branch: trigger branch analysis..."
+        wget -q "$CI_API_V4_URL/projects/${CI_PROJECT_ID}/merge_requests?state=opened&source_branch=${CI_COMMIT_REF_NAME}&private_token=$SONAR_GITLAB_TOKEN" -O mr.json || log_warn "Failed requesting GitLab API: check \$SONAR_GITLAB_TOKEN"
+        if [[ -f mr.json ]] && [[ "$(cat mr.json)" != "[]" ]]
+        then
+          mr_title=$(sed -E 's/\[\{[^{]*"title":"([^"]*)".*/\1/g' < mr.json)
+          mr_target=$(sed -E 's/\[\{[^{]*"target_branch":"([^"]*)".*/\1/g' < mr.json)
+          mr_id=$(sed -E 's/\[\{[^{]*"iid":([0-9]+).*/\1/g' < mr.json)
+          log_info "Merge Request \\e[33;1m$mr_title\\e[0m detected associated to this branch: trigger MR analysis..."
+          export sonar_mr_args="-Dsonar.pullrequest.key=$mr_id -Dsonar.pullrequest.branch=${CI_COMMIT_REF_NAME} -Dsonar.pullrequest.base=$mr_target"
+        else 
+          log_info "No Merge Request associated to this branch: trigger branch analysis..."
+          export sonar_mr_args="-Dsonar.branch.name=${CI_COMMIT_REF_NAME}"
+        fi
+      else
+        log_warn "Current branch $CI_COMMIT_REF_NAME associated to a MR but can't retrieve details..."
+        log_warn "Consider changing to merge request pipelines or set \$SONAR_GITLAB_TOKEN to allow the template to retrieve MR details (see doc)"
         export sonar_mr_args="-Dsonar.branch.name=${CI_COMMIT_REF_NAME}"
       fi
-    else 
-      log_info "\$SONAR_GITLAB_TOKEN unset: trigger branch analysis..."
+    else
+      log_info "Current branch $CI_COMMIT_REF_NAME not associated to any MR: trigger branch analysis..."
       export sonar_mr_args="-Dsonar.branch.name=${CI_COMMIT_REF_NAME}"
     fi
   }
 
-  
   function unscope_variables() {
     _scoped_vars=$(env | awk -F '=' "/^scoped__[a-zA-Z0-9_]+=/ {print \$1}" | sort)
     if [[ -z "$_scoped_vars" ]]; then return; fi
-- 
GitLab