What a Quality Gate is
A Quality Gate is a set of conditions on metrics. Each analysis ends Passed or Failed. The default Sonar way gate requires, on new code:
| Condition | Default threshold |
|---|---|
| New issues | 0 |
| New Security Hotspots reviewed | 100% |
| Coverage on new code | ≥ 80% |
| Duplication on new code | ≤ 3% |
Clean as You Code
A legacy project may carry thousands of issues. If the gate demanded all code be clean, it would fail forever and people would ignore it. Sonar's approach is Clean as You Code: only new code (code changed since the previous version or compared with the main branch) must meet the standard. Over time the code people touch gets cleaner, without the team being blocked by old technical debt.
The new code period is set as: the previous version, a number of days, or a reference branch (common for PRs).
Quality Profile versus Quality Gate
| Quality Profile | Quality Gate | |
|---|---|---|
| Answers | Which rules apply? | Does the result pass? |
| Scope | Per language | Per project |
| Example | Enable a rule banning eval() |
No new vulnerabilities |
Usually you keep Sonar way and extend it to add rules rather than editing the default profile directly.
Really blocking merges
flowchart LR
PR["Pull request"] --> CI["CI: tests + Sonar scan"]
CI --> G{"Quality Gate"}
G -- "Failed" --> BL["Red status check<br/>cannot merge"]
G -- "Passed" --> RV["Human review"] --> M["Merge"]
A gate only works when it is wired into the process:
- The pipeline fails when the gate fails (
waitForQualityGate abortPipeline: true, orsonar.qualitygate.wait=truewith the CLI scanner). - GitHub, GitLab or Azure Repos branch protection requires a green SonarQube status check before merging.
Checking the result through the API
curl -s -u "$SONAR_TOKEN:" \
"http://localhost:9000/api/qualitygates/project_status?projectKey=example-org_myapp"
Traps
- Setting thresholds on overall code for a legacy project: the gate fails forever and is ignored.
- Lowering thresholds whenever it fails instead of fixing the code.
- Bulk-marking issues Won't fix to get through the gate.
- A gate so loose, for example blocking only Blocker bugs, that it protects nothing.