一:生成build.gradle文件
gradle init --type pom
二:修改或者替换build.gradle文件内容如下
buildscript {
repositories {
jcenter()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath("io.spring.gradle:dependency-management-plugin:1.0.0.RELEASE")
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.5.RELEASE")
classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.7.1"
}
}
repositories {
jcenter()
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: "org.sonarqube"
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compileOnly('org.projectlombok:lombok:1.16.18')
annotationProcessor('org.projectlombok:lombok:1.16.18')
}
三:配置sonar认证权限信息(在该目录中创建 ~/.gradle/gradle.properties)
systemProp.sonar.host.url=http://10.100.10.22:9000
systemProp.sonar.login=admin
systemProp.sonar.password=admin
四:在项目根目录执行编译和扫描动作
stage("gradle and sonar"){
steps{
script {
def timeStamp=new Date().format("yyyy-MM-dd");
def targetDir="${WORKSPACE}/${params.targetDir}";
dir(targetDir){
withSonarQubeEnv('sonarqube-jenkins') {
print "repoBranch : ${params.repoBranch}"
sh "gradle clean build -x test sonarqube -Dsonar.projectKey=${params.projectKey} -Dsonar.projectName=${params.projectKey} -Dsonar.sourceEncoding=UTF-8 -Dsonar.analysis.buildNumber=${env.BUILD_NUMBER} -Dsonar.analysis.jobName=${env.JOB_NAME} -Dsonar.host.url=http://10.100.21.3:9000 -Dsonar.login=admin -Dsonar.password=admin -Dsonar.java.binaries=build/classes -Dsonar.java.sources=src/main/java -Dsonar.analysis.isFortify=true -Dsonar.projectDate="+timeStamp
}
}
timeout(1) {
sleep(5)
def qg = waitForQualityGate()
if (qg.status != 'OK') {
error "未通过Sonarqube的代码质量阈检查,请及时修改!failure: ${qg.status}"
}
}
}
}
}
五:接下来会生成code quality报告,在sonar的web页面查看