sonar检测C#代码时必须按照必要的插件,而且C#代码必须用MSbuid进行编译,如果需要使用SonarQube对C#进行代码质量分析,需要下载sonar-scanner-msbuild和MSBuild,其中要求MSBuild在V14.0以上,sonar-scanner-msbuild下载地址:https://github.com/SonarSource/sonar-scanner-msbuild/releases/download/3.0.0.629/sonar-scanner-msbuild-3.0.0.629.zip
使用msbuild方式通过Sonar scanner扫描代码
参考:https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+MSBuild
1. CMD命令下运行:SonarQube.Scanner.MSBuild.exe begin /k:"project 1" /n:"Test WPF" /v:"1.0"
注 :SonarQube.Scanner.MSBuilder.exe找不到,运行的时候需要固定到Snoar\sonar-scanner-msbuild-2.2.0.24目录下进行运行
参数说明:
/K:Key -对应projectKey即项目的唯一代码,如两套源代码使用同一个projectKey那扫描的结果将混在一起,所以一个项目需要有一个单独的projectKey
/n:Name: 对应projectName即项目的名称
/v:Version -对应projectVersion即项目的版本
2.cmd命令下运行:MSBuild.exe /t:Rebuild(MSBuild需要设置到系统变量中)
3.cmd命令下运行:SonarScanner.MSBuild.exe end
Jenkins和Sonar+MSBuild集成
在jenkins中就要按照这个顺序设置build,jenkins项目设置--构建--SonarQube Scanner for MSBuild - Begin Analysis和SonarQube Scanner for MSBuild - Begin Analysis,然后再将build放在begin和end中间,build可以选择用Execute Windows batch commond 或者选择Build a Visual Studio project or solution using MSBuild ,目的都是一样的。
选择如图,
参考:https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+Jenkins
遇到问题:jenkins单独构建没问题,sonar静态检查代码问题,但是jenkins+sonar集成时出现未经授权问题。
03:11:04.31 Failed to request and parse 'http://localhost:9000/api/settings/values?component=CommOperation': 远程服务器返回错误: (401) 未经授权。 03:11:04.312 Could not authorize while connecting to the SonarQube server. Check your credentials and try again.
遇到问题:SonarScanner for MsBuild begin和MSBuild.exe /t:Rebuild都没有问题,但是在SonarScanner forMSBuild end时候报错:
The SonarQube MSBuild integration failed: SonarQube was unable to collect the required information about your projects.
解决问题:电脑--属性--服务--jenkins--登录用户改为此账号,输入用户名和密码,再次运行jenkins,问题解决。
参考:https://www.queryoverflow.gdn/query/sonarqube-scanner-for-jenkins-the-sonarqube-msbuild-integration-failed-sonarqube-was-unable-to-collect-the-required-information-about-your-projects-27_48680943.html