如何在SonarQube中获取指定两次Commit间的新增代码覆盖率?
Got it, let's walk through exactly how to target the code changes between two specific commits on your master branch and get their coverage in SonarQube. There are two straightforward ways to do this—via the command line with SonarScanner, or directly in the SonarQube UI.
Using SonarScanner (Command Line)
This is perfect if you're running analysis locally or setting this up in a CI pipeline. You'll need to pass two critical parameters to the scanner to define your commit range:
sonar.scm.compareRevision: Use this for the older commit ID (the baseline you want to compare against)sonar.scm.revision: Use this for the newer commit ID (the end of your comparison range)
Since you're focusing on the master branch, add the sonar.branch.name=master parameter to ensure the analysis is tied to the right branch context.
Here's a concrete example of what the command might look like:
sonar-scanner \ -Dsonar.projectKey=your-project-key-here \ -Dsonar.sources=. \ -Dsonar.host.url=http://your-sonarqube-server \ -Dsonar.login=your-auth-token \ -Dsonar.branch.name=master \ -Dsonar.scm.compareRevision=a1b2c3old-commit-id \ -Dsonar.scm.revision=x9y8z7new-commit-id
Once the analysis finishes, SonarQube will calculate coverage only for the code that changed between those two commits on master.
Using the SonarQube UI
If you prefer a visual workflow, the built-in comparison tool makes this easy:
- Go to your project in SonarQube and navigate to the Coverage tab.
- Look for the Compare button (usually in the top-right area of the page).
- In the pop-up modal, switch both the baseline and target options to Commit.
- Paste your older commit ID into the "Baseline" field and the newer one into the "Target" field.
- Hit Compare, and you'll get a detailed view showing the coverage stats for the code added or modified between those two commits.
Quick Tips
- Double-check that your project has SCM integration enabled (you can verify this in Project Settings > General Settings > SCM)—this is required for SonarQube to pull commit data.
- Ensure the commit IDs you use exist in the repository linked to your SonarQube project.
- For CI/CD pipelines, you can parameterize these commit IDs to automatically run comparisons between specific builds or merge requests without manual input.
内容的提问来源于stack exchange,提问作者Sherry

