介绍如何使用SonarQube对dotnetcore项目进行代码检查
创建项目
创建一个.dotnet core项目

推荐安装vs扩展SonarLint for Visual Studio 2019,在开发阶段就可以发现代码中可能存在的问题
分析代码
安装MSBuild .NET Core Global Tool全局工具
- 开始分析,这里使用了指定的
SonarScanner.MSBuild版本
dotnet D:\SonarScannerMsbuild\SonarScanner.MSBuild.dll begin /k:项目唯一编码 /n:显示的项目名称 /v:当前执行活动号(可以动态递增或使用时间戳)
- 编译
dotnet build ${xx.csproj or xx.sln}
- 将分析结果推送到
SonarQube站点
dotnet sonarscanner end /d:sonar.login="账号" /d:sonar.password="密码"
问题记录
MSBuild版本问题
C:\Users\WangPengLiang\Desktop\TestApplication\.sonarqube\bin\targets\SonarQube.Integration.targets(145,5): error : SonarQube analysis is only supported with MSBuild 14 or MSBuild 15 [C:\Users\WangPengLiang\Desktop\TestApplication\TestApplication\TestApplication.csproj]
解决方法
安装MSBuild14以上版本,运行时使用指定的MSBuild版本进行build

示例:
dotnet D:\SonarScannerMsbuild\SonarScanner.MSBuild.dll begin /k:testApplication /n:TestApplication /v:1.0 /d:sonar.host.url="http://localhost:9000" /d:sonar.login="admin" /d:sonar.password="admin"dotnet build TestApplication.slndotnet sonarscanner end /d:sonar.login="admin" /d:sonar.password="admin"





单元测试覆盖率
SonarQube只能通过已经生成的测试结果文件和代码覆盖率结果文件来展示覆盖率,如何生成测试结果文件参考测试相关笔记,SonarQube只需要在对应项目配置找到对应开发语言下设置测试结果文件和覆盖率文件存储位置即可
多分支扫描
SonarQube Community版本不支持多分支扫描SonarQube Developer Edition: 及以上版本支持多分支扫描
想实现社区版多分支扫描可以使用两种方式来做
- 开源插件:
sonarqube-community-branch-plugin - 替换
sonar.projectKey,porjectKey相等于Sonar中每个项目的主键ID,替换后就会以新项目创建
这里要注意sonarqube-community-branch-plugin对SonarQube版本支持有限制,先看好自己SonarQube是什么版本

我的是8.4,下载对应版本的开源插件
下载插件放到${SONAR_HOME}/extensions/plugins和${SONAR_HOME}/lib/common目录下,重启SonarQube
扫描时,增加-d sonar.branch.name=${GIT_BRANCH}即可
dotnet D:\SonarScannerMsbuild\SonarScanner.MSBuild.dll begin /k:test /n:test /v:2.0 /d:sonar.host.url="http://localhost:9000" /d:sonar.login="admin" /d:sonar.password="admin" /d:sonar.branch.name='$(Build.SourceBranchName)'

