The Moment

阿宅的筆記

SonarQube Quick Setup

程式碼分析工具 SonarQube 初步設定與執行

SonarQube 分兩個部份,一個是Web管理平台,一個是執行程碼掃描的 Scanner,設定與執行都是分開的,以下也分開解說。

下載


  1. http://www.sonarqube.org/downloads/ 下載需要的版本 (eg, sonarqube-6.0.zip)
  2. http://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner 下載 LTS 版本

下載後解到 /opt 下

設定


原則上,SonarQube / SonarScanner 都需要利用 dababase 儲存資料,但它內建一個陽春版的讓你測試使用,如果是單機或是體驗用途,可以先不用設定 Database 的部份。

SonarQube

都不用改設定就可以跑了,但如果想跑得快一點,可以加大執行的Memory Heap size.

編輯 /opt/sonarqube-6.0/conf/sonar.properties

1
sonar.web.javaOpts=-Xmx2048m -Xms1024m -XX:+HeapDumpOnOutOfMemoryError

Sonar Scanner

編輯 /opt/sonar-scanner-2.7/conf/sonar-scanner.properties

1
2
3
4
#----- Default SonarQube server
sonar.host.url=http://localhost:9000
#----- Default source code encoding
sonar.sourceEncoding=UTF-8

執行


SonarQube

執行 /opt/sonarqube-6.0/bin/macosx-universal-64/sonar.sh 沒意外的話,打開 http://localhost:9000 就會看到它的 web portal , 預設以 admin / admin 登入

SonarScanner

在你需要掃描的專案目錄下新增一個檔案 sonar-project.properties

1
2
3
4
5
6
7
8
9
10
11
# Required metadata
sonar.projectKey=ThousandMilesEye
sonar.projectName=ThousandMilesEye
sonar.projectVersion=0.1
# Path to the parent source code directory.
# 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=SomeFolderPointTo/src

接著再執行 /opt/sonar-scanner-2.7/bin/sonar-scanner 就會開始分析你的程式碼

分析完成後,就會在 Web portal 裡的 Dashboard 中看到分析結果,有問題的部份,會有建議修正的方式,對於提昇程式碼品質相當不賴。 Screenshot