SonarQube&Gitlab-CI 實現靜態代碼分析

一.背景介紹


SonarQube® is an automatic code review tool to detect bugs, vulnerabilities and code smells in your code.
Sonar 爲代碼的質量管理提供了一個平臺,對傳統的代碼靜態檢測如 PMD、FindBugs 等工具進行整合,可以說是目前最強大的代碼質量管理工具之一。SonarQube支持25+語言,可以跟CI/CD集成。
二.SonarQube平臺搭建
1.使用docker拉取鏡像
docker pull postgres //拉取數據庫
docker pull sonarqube //拉取sonarqube
2.啓動服務
docker run --name db -e POSTGRES_USER=sonar -e POSTGRES_PASSWORD=sonar -d postgres //啓動數據庫
docker run -d --name sonarqube
-p 9000:9000
-e sonar.jdbc.username=sonar
-e sonar.jdbc.password=sonar
-e sonar.jdbc.url=jdbc:postgresql://localhost/sonar
sonarqube //啓動sonarqube
如果需要特殊的配置可以選擇綁定掛載卷,命令如下
docker run -d --name sonarqube
-p 9000:9000
-v /path/to/conf:/opt/sonarqube/conf
-v /path/to/data:/opt/sonarqube/data
-v /path/to/logs:/opt/sonarqube/logs
-v /path/to/extensions:/opt/sonarqube/extensions
sonarqube
3.訪問sonarqube
本地搭建的訪問: https://localhost:9000 賬號:admin,密碼:admin


三.GitLab-CI&GitLab-Runner

在我們的項目中使用GitLab進行源碼控制,GitLab-CI就是一套配合GitLab使用的持續集成系統。GitLab-Runner是配合GitLab-CI進行使用的。在gitlab中每個project都會配置ci的腳本。也就是當有develop pull了代碼到repo,gitlab會通知gitlab-ci,gitlab-ci又會通知到相對應的Runner,這時候Runner會去執行相對應的script。
gitlab runner 可以配置多個,在不同的機器上也可以在同一個機器配置多個runner.

gitlab-runner安裝:https://docs.gitlab.com/runner/install/linux-repository.html

四.Gradle項目配置
build.gradle配置
plugins {
id "org.sonarqube" version "2.7"
}
subprojects {
apply plugin: "org.sonarqube"
sonarqube {
properties {
property "java-module.sonar.sources", "."
property "sonar.java.binaries", "/bin"
property "sonar.sourceEncoding", "UTF-8"
property "java-module.sonar.tests", "."
}
}
}
sonarqube {
properties {
property "sonar.host.url", "https://****"
property "sonar.verbose", "true"
property "sonar.login", ""
property "sonar.sourceEncoding", "UTF-8"
property "sonar.modules", "java-module"
property "sonar.projectKey", "int
"
property "sonar.projectName", "Int
*"
}
}
本地執行命令: gradle sonar
與CI集成,.gitlab-ci.yml配置
sonarqube:
stage: sonarqube
tags:
- shell
only:
- develop
- /^release.
/ script: - ./gradlew sonarqube -Dsonar.branch.name={CI_COMMIT_REF_NAME} -x test
五.結果展示

參考:
https://hub.docker.com/_/sonarqube/
https://docs.gitlab.com/ee/ci/yaml/README.html
https://plugins.gradle.org/plugin/org.sonarqube

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章