SonarQube 已經內建 SonarC#,可以直接對 C# 進行檢查,本文將以 .NET Core 為例,並搭配 Jenkins 自動執行 SonarQube。
macOS High Sierra 10.13.4
SonarQube 7.1
Jenkins 2.107.1
.NET Core 2.0.7
將 .NET Core 專案放到 GitHub。
https://github.com/oomusou/Core2SonarQubeJenkins 當然也可以將 git repository 放在不同的 git server,如 Bitbucket
$ brew install sonarqube
使用 Homebrew 安裝 SonarQube。
brew services start sonarqube sonar console
$ sonar console
使用 sonar console 自行啟動 SonarQube。
輸入 localhost:9000 ,若看到 SonarQube 首頁,則表示安裝成功
右上角 Log in 可登入管理設定 SonarQube,預設為 admin/admin
SonarQube 雖然已經包含 SonarC#,但必須靠 SonarQube Scanner for MSBuild 才能執行,預設 SonarQube 並沒有包含 Scanner,必須自行安裝。
其實 SonarQube Scanner for MSBuild 包含 SonarQube Scanner,只是為了 C# 要編譯的特性再包了一層
Download for .NET core 2.0 下載。
下載後為一 zip 壓縮檔,解壓縮後可安裝在任何目錄。
將 zip 解開後,放到 home directory 下,並重新命名為 SonarScannerMsbuild 。
重新命名只為了縮短目錄名稱而已
<Property Name="sonar.host.url">http://localhost:9000</Property> <Property Name="sonar.login">admin</Property> <Property Name="sonar.password">admin</Property>
編輯 ~/SonarScannerMsbuild/SonarQube.Analysis.xml ,修改 sonar.host.url 、 sonar.login 與 sonar.password 三個 property。
SonarQube.Analysis.xml
$ dotnet ~/SonarScannerMsbuild/SonarScanner.MSBuild.dll begin /k:core2 /n:Core2 /v:1.0
使用 SonarQube Scanner for MSBuild 對 .NET Core 專案進行檢查。
由於 .NET Core 是跨平台, SonarScanner.MSBuild.dll 必須由 dotnet 執行。
SonarScanner.MSBuild.dll 需指定完整路徑,無法透過 $PATH 設定 begin , dotnet build 必須包在 scanner 內
SonarScanner.MSBuild.dll 檢查 C# $ dotnet build
使用 dotnet build 編譯專案。
Script 類不用編譯,可以直接使用 SonarQube Scanner 就可以檢查,但 C# 需要編譯,因此必須 dotnet build
dotnet build
$ dotnet ~/SonarScannerMsbuild/SonarScanner.MSBuild.dll end
end ,scanner 正式將 dotnet build 檢查出的結果寫入 SonarQube project
SonarScanner.MSBuild.dll 結束檢查
進入 SonarQube 網頁,就可看到 Core2 專案已經出現 SonarQube,也顯示剛剛 dotnet build 檢查出的 1 個 code smell 警告。
到目前為止,SonarQube 對 C# 的檢查已經完成,就算只將 SonarQube 裝在本機,也對 C# 程式碼品質的檢查有很大的幫助。
若能搭配 Jenkins 自動執行 SonarQube,那就更好了。
$ brew install jenkins
使用 Homebrew 安裝 Jenkins。
若想在每次 Mac 重開機就自動執行 Jenkins,輸入 brew services start jenkins
若想自行啟動 Jenkins,輸入 jenkins
$ jenkins
使用 jenkins 自行啟動 Jenkins。
localhost:8080 ~/jenkins/secrets/initialAdminPassword Continue
Install suggested plugins 即可
安裝 suggested plugin 中。
Save and Finish
Start using jenkins 開始使用 Jenkins
New Item 建立新 job
Freestyle project OK
Source Code Management 區段 Repository URL 設定到 https://github.com/oomusou/Core2SonarQubeJenkins
Build Environment Delete workspace before build starts
Build Add build step Execute shell
dotnet /Users/oomusou/SonarScannerMsbuild/SonarScanner.MSBuild.dll begin /k:core2 /n:Core2 /v:1.0 dotnet build dotnet /Users/oomusou/SonarScannerMsbuild/SonarScanner.MSBuild.dll end
Save 儲存設定
Build Now 執行 Job
藍燈
剛剛 Jenkins 執行的 Project 出現在 SonarQube 上。