代码质量分析平台Sonarqube介绍

Owen Jia 2019年07月18日 1,794次浏览

问题:如何保证工程师提交的代码是符合标准的?

找个技术经理或架构师有事没事就Code Review或者不定期举行Review大会等等办法,它们有一个共同的特点:成本大,难持续,所以找一个自动化代码质量分析工具就势在必行了。

好用且开源的代码质量分析工具:Sonar Qube

官方很好几个版本:社区版、开发者版、企业版、数据中心版。

核心痛点

  • 代码高质量检测分析能力,Bug 检查
  • 支持定制化 review 检测
  • 可以与企业员工系统的账户体系打通
  • 与主流项目构建工具(Maven|Gradle)无缝融合
  • 部署配置简单,文档充足
  • 源码开源,大企业支撑(全球化)

Sonar与LDAP结合

结合windows统一账户管理,使用ldap帐号登陆和邮件发送服务体系。

参考技术文档: https://www.linuxhub.org/?p=4476

Sonar-scanner下载&文档地址:

https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/

简单的项目配置Sonar

在项目的根目录下添加sonar-project.properties文件,并修改sonar:projectName\projectVersion\sources\binaries为具体项目值。

# must be unique in a given SonarQube instance

sonar.projectKey=my:project:nc-link

# this is the name displayed in the SonarQube UI

sonar.projectName=nc-o-link

sonar.projectVersion=2.0.2-SNAPSHOT

# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.

# Since SonarQube 4.2, this property is optional if sonar.modules is set.

# If not set, SonarQube starts looking for source code from the directory containing

# the sonar-project.properties file.

sonar.sources=src

sonar.java.binaries=target

sonar.language=java

# Encoding of the source code. Default is default system encoding

sonar.sourceEncoding=UTF-8

Maven配置Sonar

直接配置Maven进行全局管理,Maven本身自带sonar插件,不需要在根目录单独添加配置sonar-project.properties文件,只需要在maven的config/setting.xml中添加sonar插件配置即可,如下:

<pluginGroups>
<pluginGroup>org.sonarsource.scanner.maven</pluginGroup>
</pluginGroups>
<profile>
<id>sonar</id>
<activation> 
<activeByDefault>true</activeByDefault> 
</activation> 
<properties>
<sonar.host.url>http://localhost:9000</sonar.host.url>
</properties>
</profile>

在Project的根目录直接运行命令:mvn sonar:sonar 或者 mvn clean verify -DskipTests sonar:sonar。第一次运行会下载相应的插件比较慢,可以根据项目具体情况进行使用,多项目结构官方推荐mvn clean install + mvn sonar:sonar

下载插件

success

官方参考文档:https://docs.sonarqube.org/display/sonarqube53/analyzing+with+sonarqube+scanner+for+maven

注意插件版本问题

<!-- sonar自动化代码分析 -->
<plugin>
	<groupId>org.sonarsource.scanner.maven</groupId>
	<artifactId>sonar-maven-plugin</artifactId>
	<version>3.6.0.1398</version>
</plugin>

Maven Sonar Plugins

查看支持的版本地址:http://maven-repository.com/artifact/org.sonarsource.scanner.maven/sonar-maven-plugin

20190709

Mysql 库表自动生成

mysql-config

Mysql配置好后,重新启动Sonar会自动生产表,并初始化数据。

mysql-database

Sonar 使用界面

login

index1

index2

项目分析案例

1、执行sonar scaner 脚本:mvn sonar:sonar

sonar\:sonar 1

sonar\:sonar 2

2、分析结果报表展示

result1

result2

result3

关注推荐

作者:Owen Jia,一个想法比较多的架构师。

他的博客网站:Owen Blog

推荐关注公众号:冬天就要吃胖点

不要随大流,做一个不一样的工程师