How to block the merge of Pull Requests when SonarQube Quality Gate is failed, with GitHub

This feature is available with GitHub.com and GitHub Enterprise 2.17 and higher (maybe earlier versions too but this is to be verified)

With GitHub it’s possible to block the merge of a pull request if the SonarQube Quality Gate is failed on the PR (Pull Request).

This is called a Branch protection rule in GitHub, and can be defined per target branch, ie you can select which branches can accept pull request merges only if Quality Gate is passed. These branches are called protected branches

To do that:

  1. In the interested repository, browse to repository settingsBranchesBranch protection rules
  2. Click on Add Rule. Define branch name that should comply to this rule ("*" in the screenshot below
  3. Select Require status check to pass before merging
  4. Tick the SonarQube Code Analysis check.
    Note that there must have been at least one SonarQube analysis on the repository in the last week (on any branch) to have this check available in the list.

Once you’ve done that you should notice that the PR can’t be merged if the SonarQube Quality Gate failed on the PR… (Note: As per the screenshot below you can still merge but only if you are the repository Administrator. This is however probably a bad idea)

Note about monorepos

  • When analyzing pull request in a monorepo, each project composing the mono may decorate the pull request separately, and each project will generate a separate GitHub check, typically called [<projectName>] SonarQube Code Analysis. So you may have to configure each of the checks to pass (instead of the SonarQube Code Analysis check for a non monorepo).
  • If, for a given PR, only some projects are affected (ie have new code in the PR) and are analyzed, the PR will only be decorated for these projects and only the checks related to these projects will be emitted. So you can’t use ALL the checks of the monorepo as a condition to pass to allow merging the PR.
    In such case you have to revert to a solution where you fail the build when some QG are failed. In the GitHub workflow
    – Pass sonar.qualitygate.wait=true to the scanner properties of each separate project/scanner execution and
    – Set the scanner build step continue-on-error: false of each separate project/scanner execution step so that if the QG fails, the step fails, and the build fails, which will block the merge

See also

4 Likes

When I follow these steps users that are not admins on the repo are unable to commit and receive the following error when pushing code:

remote: error: XX: Protected branch update failed for refs/heads/XXXX remote: error: Required status check "SonarQube Code Analysis" is expected.

Is there any way around this?