SonarQube-代码审查管理工具

Sonar家族框架

在这里插入图片描述

检测代码质量七个维度

  • 复杂度分布(complexity):代码复杂度过高将难以理解
  • 重复代码(duplications):程序中包含大量复制、粘贴的代码而导致代码臃肿,sonar可以展示源码中重复严重的地方
  • 单元测试统计(unit tests):统计并展示单元测试覆盖率,开发或测试可以清楚测试代码的覆盖情况
  • 代码规则检查(coding rules):通过Findbugs,PMD,CheckStyle等检查代码是否符合规
  • 注释率(comments):若代码注释过少,特别是人员变动后,其他人接手比较难接手;若过多,又不利于阅读
  • 潜在的Bug(potential bugs):通过Findbugs,PMD,CheckStyle等检测潜在的bug
  • 结构与设计(architecture & design):找出循环,展示包与包、类与类之间的依赖、检查程序之间耦合度

支持语言

ABAP、C/C++、C#、CSS、COBOL、Flex、Go、HTML、Java、JavaScript、Kotlin、Objective-C、PL/SQL、PL/I、PHP、Python、RPG、Ruby、Swift、T-SQL、TypeScript、VB.NET、VB6、XML

环境部署

SonarQube下载与安装

在SonarQube的下载页面:https://www.sonarqube.org/downloads/
JDK11下载:https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html

启动SONARQUBE服务

双击StartSonar.bat即可启动SonarQube服务
在这里插入图片描述
启动成功命令行如下图所示:
在这里插入图片描述
启动成功后,用浏览器打开http://localhost:9000
在这里插入图片描述
到此为止,SonarQube的服务端实际上已经部署成功,然而它还是只是个测试用的环境不足以用于生产环境,因为SonarQube是一个需要数据存储的Web系统,它需要数据库才能成为一个完整的有数据存储和展示功能的Web系统
在SonarQube的目录中有个conf文件夹,该文件夹内是SonarQube的配置文件,数据库的配置即是在sonar.properties中配置的,在该配置文件中我们也能看到当前版本的SonarQube支持哪些数据库

数据库配置

#--------------------------------------------------------------------------------------------------
# DATABASE
#
# IMPORTANT:
# - The embedded H2 database is used by default. It is recommended for tests but not for
#   production use. Supported databases are MySQL, Oracle, PostgreSQL and Microsoft SQLServer.
# - Changes to database connection URL (sonar.jdbc.url) can affect SonarSource licensed products.

# User credentials.
# Permissions to create tables, indices and triggers must be granted to JDBC user.
# The schema must be created first.
#sonar.jdbc.username=
#sonar.jdbc.password=

#----- Embedded Database (default)
# H2 embedded database server listening port, defaults to 9092
#sonar.embeddedDatabase.port=9092

#----- DEPRECATED 
#----- MySQL >=5.6 && <8.0
# Support of MySQL is dropped in Data Center Editions and deprecated in all other editions
# Only InnoDB storage engine is supported (not myISAM).
# Only the bundled driver is supported. It can not be changed.
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&&useSSL=false
sonar.jdbc.username=mysql
sonar.jdbc.password=alex005x
sonar.sorceEncoding=UTF-8
sonar.login=admin
sonar.password=admin

#----- Oracle 11g/12c
# The Oracle JDBC driver must be copied into the directory extensions/jdbc-driver/oracle/.
# Only the thin client is supported, and only the versions 11.2.x or 12.2.x must be used. See
# https://jira.sonarsource.com/browse/SONAR-9758 for more details.
# If you need to set the schema, please refer to http://jira.sonarsource.com/browse/SONAR-5000
#sonar.jdbc.url=jdbc:oracle:thin:@localhost:1521/XE


#----- PostgreSQL 9.3 or greater
# By default the schema named "public" is used. It can be overridden with the parameter "currentSchema".
#sonar.jdbc.url=jdbc:postgresql://localhost/sonarqube?currentSchema=my_schema


#----- Microsoft SQLServer 2014/2016 and SQL Azure
# A database named sonar must exist and its collation must be case-sensitive (CS) and accent-sensitive (AS)
# Use the following connection string if you want to use integrated security with Microsoft Sql Server
# Do not set sonar.jdbc.username or sonar.jdbc.password property if you are using Integrated Security
# For Integrated Security to work, you have to download the Microsoft SQL JDBC driver package from
# https://www.microsoft.com/en-us/download/details.aspx?id=55539
# and copy sqljdbc_auth.dll to your path. You have to copy the 32 bit or 64 bit version of the dll
# depending upon the architecture of your server machine.
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar;integratedSecurity=true

# Use the following connection string if you want to use SQL Auth while connecting to MS Sql Server.
# Set the sonar.jdbc.username and sonar.jdbc.password appropriately.
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar


#----- Connection pool settings
# The maximum number of active connections that can be allocated
# at the same time, or negative for no limit.
# The recommended value is 1.2 * max sizes of HTTP pools. For example if HTTP ports are
# enabled with default sizes (50, see property sonar.web.http.maxThreads)
# then sonar.jdbc.maxActive should be 1.2 * 50 = 60.
#sonar.jdbc.maxActive=60

# The maximum number of connections that can remain idle in the
# pool, without extra ones being released, or negative for no limit.
#sonar.jdbc.maxIdle=5

# The minimum number of connections that can remain idle in the pool,
# without extra ones being created, or zero to create none.
#sonar.jdbc.minIdle=2

# The maximum number of milliseconds that the pool will wait (when there
# are no available connections) for a connection to be returned before
# throwing an exception, or <= 0 to wait indefinitely.
#sonar.jdbc.maxWait=5000

#sonar.jdbc.minEvictableIdleTimeMillis=600000
#sonar.jdbc.timeBetweenEvictionRunsMillis=30000

Web Server配置


#--------------------------------------------------------------------------------------------------
# WEB SERVER
# Web server is executed in a dedicated Java process. By default heap size is 512Mb.
# Use the following property to customize JVM options.
#    Recommendations:
#
#    The HotSpot Server VM is recommended. The property -server should be added if server mode
#    is not enabled by default on your environment:
#    http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html
#
#    Startup can be long if entropy source is short of entropy. Adding
#    -Djava.security.egd=file:/dev/./urandom is an option to resolve the problem.
#    See https://wiki.apache.org/tomcat/HowTo/FasterStartUp#Entropy_Source
#
#sonar.web.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError

# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.web.javaAdditionalOpts=

# Binding IP address. For servers with more than one IP address, this property specifies which
# address will be used for listening on the specified ports.
# By default, ports will be used on all IP addresses associated with the server.
#sonar.web.host=0.0.0.0

# Web context. When set, it must start with forward slash (for example /sonarqube).
# The default value is root context (empty value).
#sonar.web.context=
# TCP port for incoming HTTP connections. Default value is 9000.
#sonar.web.port=9000


# The maximum number of connections that the server will accept and process at any given time.
# When this number has been reached, the server will not accept any more connections until
# the number of connections falls below this value. The operating system may still accept connections
# based on the sonar.web.connections.acceptCount property. The default value is 50.
#sonar.web.http.maxThreads=50

# The minimum number of threads always kept running. The default value is 5.
#sonar.web.http.minThreads=5

# The maximum queue length for incoming connection requests when all possible request processing
# threads are in use. Any requests received when the queue is full will be refused.
# The default value is 25.
#sonar.web.http.acceptCount=25

# By default users are logged out and sessions closed when server is restarted.
# If you prefer keeping user sessions open, a secret should be defined. Value is
# HS256 key encoded with base64. It must be unique for each installation of SonarQube.
# Example of command-line:
# echo -n "type_what_you_want" | openssl dgst -sha256 -hmac "key" -binary | base64
#sonar.auth.jwtBase64Hs256Secret=

# The inactivity timeout duration of user sessions, in minutes. After the configured
# period of time, the user is logged out.
# The default value is set to 3 days (4320 minutes)
# and cannot be greater than 3 months. Value must be strictly positive.
#sonar.web.sessionTimeoutInMinutes=4320

# A passcode can be defined to access some web services from monitoring
# tools without having to use the credentials of a system administrator.
# Check the Web API documentation to know which web services are supporting this authentication mode.
# The passcode should be provided in HTTP requests with the header "X-Sonar-Passcode".
# By default feature is disabled.
#sonar.web.systemPasscode=

除了以上两类重要配置外,还有单点登录、LDAP、Java虚拟机配置等相关参数可配

配置插件

在这里插入图片描述

配置SonarQube Scanner

下载地址:https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner
在这里插入图片描述

#Configure here general information about the environment, such as SonarQube server connection details for example
#No information about specific project should appear here

#----- Default SonarQube server
sonar.host.url=http://localhost:9000

#----- Default source code encoding
sonar.sourceEncoding=UTF-8
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&&useSSL=false
sonar.jdbc.username=mysql
sonar.jdbc.password=alex005x

新增系统环境变量

SONAR_SCANNER_HOME:D:\sonar-scanner-4.2.0.1873-windows
在这里插入图片描述
Path中新增%SONAR_SCANNER_HOME%\bin;
在这里插入图片描述
验证配置,在命令行输入sonar-scanner -help

D:\cuss-social-jscoco\target\classes\com\xhl\cuss\social>sonar-scanner -help
ERROR: Unrecognized option: -help
INFO:
INFO: usage: sonar-scanner [options]
INFO:
INFO: Options:
INFO:  -D,--define <arg>     Define property
INFO:  -h,--help             Display help information
INFO:  -v,--version          Display version information
INFO:  -X,--debug            Produce execution debug output

在工程目录下新建文件名为sonar-project.properties,在文件中写入如下项目信息,用于写入Sonar数据库

#项目的key
sonar.projectKey=my:baseInfo

#项目的名字
sonar.projectName=BASIC_INFORMATION

#项目的版本
sonar.projectVersion=1.0.0

#需要分析的源码的目录,多个目录用英文逗号隔开
sonar.sources=D:/cuss-social-jscoco/src/main/java/com/xhl

# Language
sonar.language=java

sonar.java.binaries=.
sonar.sourceEncoding=UTF-8

执行扫描

在工程目录下,执行命令sonar-scanner即可完成扫描,扫描结果会写入数据库,并可才Sonar平台上查看结果

D:\cuss-social-jscoco>sonar-scanner
INFO: Scanner configuration file: D:\sonar-scanner-4.2.0.1873-windows\bin\..\conf\sonar-scanner.properties
INFO: Project root configuration file: D:\cuss-social-jscoco\sonar-project.properties
INFO: SonarQube Scanner 4.2.0.1873
INFO: Java 11.0.3 AdoptOpenJDK (64-bit)
INFO: Windows 10 10.0 amd64
INFO: User cache: C:\Users\Administrator\.sonar\cache
INFO: SonarQube server 7.6.0
INFO: Default locale: "zh_CN", source code encoding: "UTF-8"
INFO: Load global settings
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.protobuf.UnsafeUtil (file:/C:/Users/Administrator/.sonar/cache/993f707e3af7ba4f46f121039128516b/sonar-scanner-engine-shaded-7.6-all.jar) to field java.nio.Buffer.address
WARNING: Please consider reporting this to the maintainers of com.google.protobuf.UnsafeUtil
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
INFO: Load global settings (done) | time=50ms
INFO: Server id: 49B321BC-AW5aoLlje3tu4A9kELXR
INFO: User cache: C:\Users\Administrator\.sonar\cache
INFO: Load/download plugins
INFO: Load plugins index
INFO: Load plugins index (done) | time=70ms
INFO: Plugin [l10nzh] defines 'l10nen' as base plugin. This metadata can be removed from manifest of l10n plugins since version 5.2.
INFO: Load/download plugins (done) | time=100ms
INFO: Process project properties
INFO: Execute project builders
INFO: Execute project builders (done) | time=10ms
INFO: Project key: my:baseInfo
INFO: Base dir: D:\cuss-social-jscoco
INFO: Working dir: D:\cuss-social-jscoco\.scannerwork
INFO: Load project settings
INFO: Load project settings (done) | time=20ms
INFO: Load project repositories
INFO: Load project repositories (done) | time=50ms
INFO: Load quality profiles
INFO: Load quality profiles (done) | time=40ms
INFO: Load active rules
INFO: Load active rules (done) | time=340ms
INFO: Load metrics repository
INFO: Load metrics repository (done) | time=21ms
WARN: SCM provider autodetection failed. Please use "sonar.scm.provider" to define SCM of your project, or disable the SCM Sensor in the project settings.
INFO: Language is forced to java
INFO: Indexing files...
INFO: Project configuration:
INFO: 132 files indexed
INFO: Quality profile for java: Sonar way
INFO: ------------- Run sensors on module BASIC_INFORMATION
INFO: Sensor JavaSquidSensor [java]
INFO: Configured Java source version (sonar.java.source): none
INFO: JavaClasspath initialization
WARN: Bytecode of dependencies was not provided for analysis of source files, you might end up with less precise results. Bytecode can be provided using sonar.java.libraries property.
INFO: JavaClasspath initialization (done) | time=20ms
INFO: JavaTestClasspath initialization
INFO: JavaTestClasspath initialization (done) | time=10ms
INFO: Java Main Files AST scan
INFO: 132 source files to be analyzed
INFO: 132/132 source files have been analyzed
INFO: Java Main Files AST scan (done) | time=9762ms
INFO: Java Test Files AST scan
INFO: 0 source files to be analyzed
INFO: Java Test Files AST scan (done) | time=0ms
INFO: 0/0 source files have been analyzed
INFO: Sensor JavaSquidSensor [java] (done) | time=10202ms
INFO: Sensor JaCoCo XML Report Importer [jacoco]
INFO: Sensor JaCoCo XML Report Importer [jacoco] (done) | time=10ms
INFO: Sensor SurefireSensor [java]
INFO: parsing [D:\cuss-social-jscoco\target\surefire-reports]
INFO: Sensor SurefireSensor [java] (done) | time=10ms
INFO: Sensor JaCoCoSensor [java]
INFO: Sensor JaCoCoSensor [java] (done) | time=0ms
INFO: Sensor JavaXmlSensor [java]
INFO: Sensor JavaXmlSensor [java] (done) | time=10ms
INFO: Sensor HTML [web]
INFO: Sensor HTML [web] (done) | time=10ms
INFO: Sensor Zero Coverage Sensor
INFO: Sensor Zero Coverage Sensor (done) | time=80ms
INFO: ------------- Run sensors on project
INFO: Sensor Java CPD Block Indexer
INFO: Sensor Java CPD Block Indexer (done) | time=271ms
INFO: No SCM system was detected. You can use the 'sonar.scm.provider' property to explicitly specify it.
INFO: 32 files had no CPD blocks
INFO: Calculating CPD for 100 files
INFO: CPD calculation finished
INFO: Analysis report generated in 270ms, dir size=1 MB
INFO: Analysis report compressed in 370ms, zip size=472 KB
INFO: Analysis report uploaded in 80ms
INFO: ANALYSIS SUCCESSFUL, you can browse http://localhost:9000/dashboard?id=my%3AbaseInfo
INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
INFO: More about the report processing at http://localhost:9000/api/ce/task?id=AW5eRz6r4XbRoxI2cCRW
INFO: Analysis total time: 13.842 s
INFO: ------------------------------------------------------------------------
INFO: EXECUTION SUCCESS
INFO: ------------------------------------------------------------------------
INFO: Total time: 14.893s
INFO: Final Memory: 8M/34M
INFO: ------------------------------------------------------------------------

在结果中能够看到链接

扫描二维码关注公众号,回复: 8876381 查看本文章
http://localhost:9000/dashboard?id=my%3AbaseInfo

用浏览器打开该链接,即可查看结果
在这里插入图片描述

扫描Maven项目

在这里插入图片描述
在这里插入图片描述
点击Setup,然后输入一个Name,并点击Generate按钮生成token
在这里插入图片描述
在这里插入图片描述
点击Continue,然后根据项目的语言选择要扫描什么类型的项目,例如Java语言的项目jiu选择Java然后,根据构建工具选择Maven还是Gradle,例如选择Maven
在这里插入图片描述

配置Maven

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

如果Maven环境配置成功,则只需要在命令行执行如下命令即可完成扫描

mvn sonar:sonar \
  -Dsonar.projectKey=java-c-leadscloud \
  -Dsonar.host.url=http://localhost:9000 \
  -Dsonar.login=c8e3f17a12f5ead7dac8a7a45460b7be958ef5e1

扫描Gradle项目

如果选择Gradle,则需要作如下配置
在这里插入图片描述

发布了162 篇原创文章 · 获赞 42 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/dawei_yang000000/article/details/103022124
今日推荐