代码质量管理平台之SonarQube
一:基本介绍
在官方文档中,是这么介绍的:
SonarQube® is an automatic code review tool to detect bugs, vulnerabilities and code smells in your code. It can integrate with your existing workflow to enable continuous code inspection across your project branches and pull requests.
Below are a few key pointers, otherwise head over to the left pane for full documentation content and search capabilities.
翻译过来就是:SonarQube是一种自动的代码审查工具,用于检查代码中的错误以及漏洞。他可以与您现在的工作流程集成,一遍在项目分支和拉取请求之间进行连续的检查。
也就是说,在你将代码提交到SonarQube平台上时,SonarQube会根据当前的代码规范来检查你的代码,用户可根据界面来查看自己代码中可能存在的一些错误或者漏洞。以下图片为SonarQube的web界面展示。
二:安装教程
- 环境:jdk
SonarQube :https://www.sonarqube.org/downloads/
mysql - 安装
用户可根据自己需要在bin目录中选择符合自己操作系统,此处笔者使用64位window系统。
运行InstallNTService.bat,然后运行StartSonar.bat启动Sonar。
- 配置
数据库配置:
CREATE DATABASE sonar CHARACTER SET utf8 COLLATE
utf8_general_ci;
CREATE USER 'sonar' IDENTIFIED BY 'sonar';
GRANT ALL ON sonar.* TO 'sonar'@'%' IDENTIFIED BY 'sonar';
GRANT ALL ON sonar.* TO 'sonar'@'localhost' IDENTIFIED BY 'sonar';
修改sonar配置:(conf包下的sonar.properties,增加数据源)
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar
sonar.jdbc.url=jdbc:mysql://127.0.0.1:3306/sonar?
useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements
=true&useConfigs=maxPerformance\
重启sonar,访问127.0.0.1:9000,看到如下界面,即安装成功。
三:安装插件
在配置中,选择应用市场,下载自己所需要的插件。如上图,即为笔者安装的中文插件包。用户可根据自己需要选择不同编程语言的插件。
四:maven+sonar
当前很多项目都会结合着maven进行编译,当然sonar也支持在maven编译的时候将项目上传至sonar平台。当然,也可以搭配sonar自己的scanner,sonar-scanner进行上传代码进行审查。这里主要介绍maven下的。
在maven的setting文件下新增:
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<sonar.jdbc.url>jdbc:mysql://127.0.0.1:3306/sonar</sonar.jdbc.url>
<sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver>
<sonar.jdbc.username>sonar</sonar.jdbc.username>
<sonar.jdbc.password>sonar</sonar.jdbc.password>
<!-- SERVER ON A REMOTE HOST -->
<sonar.host.url>http://ip:9000</sonar.host.url>
</properties>
</profile>
然后在maven编译时加上 sonar:sonar参数即可。
clean install -Dmaven.test.skip=true sonar:sonar
顺便介绍笔者在netbean下执行该操作:
右击项目,选择属性,然后选择操作,添加定制。
配置完成后,用户可根据maven的goal来上传代码审查。
五:后记
sonar是当前非常强大的代码审查工具,支持多种语言的审查。也可结合jenkins来使用,打造一整套自动化的构建审查体系。让初中级甚至高级程序员的代码更加健壮。