0%

[原创] 如何在 Android Studio 中使用 SonarQube

简述

本要主要讲解在 Mac 下(其它平台类似) Android Studio 如何使用 SonarQube 进行代码检查。
关于什么是 SonarQube,这里就不再赘述了,百度一下即可。它的目的就是持续分析及衡量代码质量 (continuously analyze and measure technical quality)

前提条件

关于 SonarQube,本文只讲解如何进行安装及配置。至于在安装 SonarQube 之前需要安装的软件,需要读者自行安装。
需要提前安装的软件有:

  • Java SDK
  • MySQL

以上软件请根据自己的平台进行安装。

系统环境说明

本人的开发环境如下:

  • Mac OS 10.13.3 (17D47)
  • SonarQube Version 7.0 (build 36138)
  • Java 1.8.0u152
  • MySQL 5.7.21

Android 环境如下:

  • Android Studio 3.0.1
  • Gradle Version 4.1
  • Android Plguin Version 3.0.1

SonarQube 安装及配置

安装

从官网下载最新版 SonarQube 7.0,并解压到指定的文件夹。例如:/Users/yhz61010/Downloads/sonarqube-7.0/

配置

SQL 配置

默认情况下, SonarQube 使用是的内嵌的 H2 数据库。生产环境下需要换成其它数据库,例如 MySQLPostgres 等。
这里以 MySQL 为例进行说明。

创建 DB 及 用户

登录 MySQL

1
2
3
4
5
$ mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.7.21 MySQL Community Server (GPL)

创建数据库

1
2
mysql> CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci;
Query OK, 1 row affected (0.00 sec)

创建名为 sonar 密码为 sonar 的用户
(因为下文中提到的 SonarQube 配置文件中默认的用户名及密码为 sonar)

1
2
mysql> CREATE USER 'sonar'@'localhost' IDENTIFIED BY 'sonar';
Query OK, 0 rows affected (0.00 sec)
设置并刷新权限
1
2
3
4
5
mysql> GRANT ALL PRIVILEGES ON * . * TO 'sonar'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES ;
Query OK, 0 rows affected (0.00 sec)

SonarQube 配置文件

修改如下配置文件:

1
vim <SonarQube 安装路径>/sonarqube-7.0/conf/sonar.properties

去掉必要行的注释,结果如下:

1
2
3
4
5
6
7
8
9
10
# 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
sonar.jdbc.password=sonar

#----- MySQL 5.6 or greater
# 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

运行 SonarQube

<SonarQube 安装路径>/sonarqube-7.0/bin/下面有各种平台的可执行文件(Windows, Linux, Mac),这里以 Mac 平台为例。
完成上面所有的配置之后,可以执行 SonarQube 如下常用命令:

启动 SonarQube

1
2
3
4
$ cd <SonarQube 安装路径>/sonarqube-7.0/bin/macosx-universal-64
$ ./sonar.sh start
Starting SonarQube...
Started SonarQube.

查看 SonarQube 启动状态

1
2
$ ./sonar.sh status
SonarQube is running (84846).

停止 SonarQube

1
2
3
$ ./sonar.sh stop
Stopping SonarQube...
SonarQube was not running.

重启 SonarQube

1
2
3
4
5
6
$ ./sonar.sh restart
Stopping SonarQube...
Waiting for SonarQube to exit...
Stopped SonarQube.
Starting SonarQube...
Started SonarQube.

查看其它命令

1
2
$ ./sonar.sh
Usage: ./sonar.sh { console | start | stop | restart | status | dump }

访问 SonarQube

SonarQube 默认的端口是 9000,因此在浏览器中打开如下地址:http://localhost:9000/

SonarQube Homepage

点击右上角的 Log in 登录,默认的用户名及密码均为 admin
登录后的页面如下:

SonarQube Login

获取 User Token

在 Android Studio 中设置 SonarQube 时,需要用到 SonarQube 的用户名及密码。显然,暴露这些重要信息是很不安全的。因此安全起见,我们不会在 Android Studio 直接使用 SonarQube 的用户名及密码,而是使用 Token。

获取 Token 的方法也很简单,不过请**注意**,
保存好 Token,
保存好 Token,
保存好 Token,
重要的事情说三遍,因为您以后没有第二次机会查看 Token 值:
SonarQube Get User Token

SonarQube Get User Token

SonarQube Get User Token

SonarQube Get User Token

在 Android Studio 中添加 SonarQube

在项目根目录下的 build.gradle 中添加如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
buildscript {

repositories {
mavenCentral()
google()
jcenter()
// Add this repository bellow for SonarQube
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
// Add this repository bellow for SonarQube
classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.6.1"
}
}

在 Module 目录下的 build.gradle 中添加如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
apply plugin: "org.sonarqube"

sonarqube {
// Check https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+Gradle
// for more information
properties {
// Chanage this to your project name.
property "sonar.projectName", "SonarQube Demo App"
// [${project.group}:]${project.name} for root module.
// <root module key>:<module path> for submodules.
property "sonar.projectKey", "com.ho1ho.sonarqube"
// You'd better specify your FQDN here(your ip or domain). Do not use localhost.
property "sonar.host.url", "http://192.168.21.181:9000"
property "sonar.language", "java"
property "sonar.sources", "src/main/"
// For security reason, you'd better set "sonar.forceAuthentication" to true
// if you do not want to expose your sonar user name and password here.
property "sonar.forceAuthentication", "true"
// When "sonar.forceAuthentication" is set to true, just use token as "sonar.login".
// You can get token by accessing your SonarQube site.
// See above metioned for more information.
property "sonar.login", "6975cc46bec31671b81cc64f33b3411db9d0a46d"
}
}

到这里 Android Studio 的 SonarQube 设置就全部完成了。

使用 SonarQube 检查代码

前提:需要安装 Gradle,或者使用 Android Studio 创建项目时下载的 Gradle。
进入你的 Android Studio 项目目录,并如何如下命令开始检查代码:

1
2
3
4
5
6
7
8
9
10
$ cd <Android Studio 项目根目录>/
$ gradle sonarqube
Starting a Gradle Daemon (subsequent builds will be faster)
Parallel execution with configuration on demand is an incubating feature.
<======-------> 50% CONFIGURING [7s]
> :app
......
......
BUILD SUCCESSFUL in 26s
34 actionable tasks: 3 executed, 31 up-to-date

看到 BUILD SUCCESSFUL,恭喜你,代码已经检查完成。

访问 SonarQube 查看检查结果

依然在浏览器中打开 SonarQube 的访问地址:http://localhost:9000/
SonarQube Report

SonarQube Report

SonarQube Report

SonarQube Report

总结

作为静态代码检查工具,SonarQube 确实能发现项目中潜在的问题,对于提高代码质量还是很有帮助的。而且它可以和 Jenkins 整合在一起极大的提高工作效率。

不过再智能的工具也有它不智能的一面。虽然它可以检查出很多问题,但是我发现其中也有很多问题其实并不是问题。例如很多被认为是 Bug 级别的问题,但在你查看代码后,你会发现这其实仅仅是一个在程序设计时特意为之的事情,而 SonarQube 并不知晓,只能作出一个善意的提醒。

坚持原创及高品质技术分享,您的支持将鼓励我继续创作!