天天看點

代碼品質管理平台之SonarQube

代碼品質管理平台之SonarQube

    • 一:基本介紹
    • 二:安裝教程
    • 三:安裝插件
    • 四:maven+sonar
    • 五:後記

一:基本介紹

在官方文檔中,是這麼介紹的:

SonarQube® is an automatic code review tool to detect bugs, vulnerabilities and code smells in your code. It can integrate with your existing workflow to enable continuous code inspection across your project branches and pull requests.

Below are a few key pointers, otherwise head over to the left pane for full documentation content and search capabilities.

翻譯過來就是:SonarQube是一種自動的代碼審查工具,用于檢查代碼中的錯誤以及漏洞。他可以與您現在的工作流程內建,一遍在項目分支和拉取請求之間進行連續的檢查。

也就是說,在你将代碼送出到SonarQube平台上時,SonarQube會根據目前的代碼規範來檢查你的代碼,使用者可根據界面來檢視自己代碼中可能存在的一些錯誤或者漏洞。以下圖檔為SonarQube的web界面展示。

代碼品質管理平台之SonarQube

二:安裝教程

  1. 環境:jdk

    SonarQube :https://www.sonarqube.org/downloads/

    mysql

  2. 安裝
    代碼品質管理平台之SonarQube
    使用者可根據自己需要在bin目錄中選擇符合自己作業系統,此處筆者使用64位window系統。
    代碼品質管理平台之SonarQube

運作InstallNTService.bat,然後運作StartSonar.bat啟動Sonar。

代碼品質管理平台之SonarQube
  1. 配置

    資料庫配置:

CREATE DATABASE sonar CHARACTER SET utf8 COLLATE 	   
     utf8_general_ci;
    CREATE USER 'sonar' IDENTIFIED BY 'sonar';
    GRANT ALL ON sonar.* TO 'sonar'@'%' IDENTIFIED BY 'sonar';
    GRANT ALL ON sonar.* TO 'sonar'@'localhost' IDENTIFIED BY 'sonar';
           

修改sonar配置:(conf包下的sonar.properties,增加資料源)

sonar.jdbc.username=sonar 
sonar.jdbc.password=sonar
sonar.jdbc.url=jdbc:mysql://127.0.0.1:3306/sonar?
	useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements
		=true&useConfigs=maxPerformance\
           

重新開機sonar,通路127.0.0.1:9000,看到如下界面,即安裝成功。

三:安裝插件

代碼品質管理平台之SonarQube

在配置中,選擇應用市場,下載下傳自己所需要的插件。如上圖,即為筆者安裝的中文插件包。使用者可根據自己需要選擇不同程式設計語言的插件。

四:maven+sonar

目前很多項目都會結合着maven進行編譯,當然sonar也支援在maven編譯的時候将項目上傳至sonar平台。當然,也可以搭配sonar自己的scanner,sonar-scanner進行上傳代碼進行審查。這裡主要介紹maven下的。

在maven的setting檔案下新增:

<profile>
   <id>sonar</id>
   <activation>
      <activeByDefault>true</activeByDefault>
   </activation>
   <properties>
<sonar.jdbc.url>jdbc:mysql://127.0.0.1:3306/sonar</sonar.jdbc.url>
      <sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver>
      <sonar.jdbc.username>sonar</sonar.jdbc.username>
      <sonar.jdbc.password>sonar</sonar.jdbc.password>
      <!-- SERVER ON A REMOTE HOST -->
      <sonar.host.url>http://ip:9000</sonar.host.url>
   </properties>
</profile>
           
然後在maven編譯時加上 sonar:sonar參數即可。
clean install -Dmaven.test.skip=true sonar:sonar
           

順便介紹筆者在netbean下執行該操作:

代碼品質管理平台之SonarQube

右擊項目,選擇屬性,然後選擇操作,添加定制。

代碼品質管理平台之SonarQube

配置完成後,使用者可根據maven的goal來上傳代碼審查。

五:後記

sonar是目前非常強大的代碼審查工具,支援多種語言的審查。也可結合jenkins來使用,打造一整套自動化的建構審查體系。讓國中級甚至進階程式員的代碼更加健壯。