下面的自动提取数据方法需要Jenkins项目名称与Sonar项目的projectKey属性一致,因为Sonar的Web Service API可以通过projectKey属性指定项目,这样我们用${PROJECT_NAME}标记在email-ext的Pre-send Script中指定Sonar项目,获取项目数据,具体实现过程如下:
-
新建BVT项目USB-TEST,此项目的BVT脚本build.xml中定义对应的Sonar项目的projectKey:
<property name="sonar.projectKey" value="USB-TEST" />
-
Jenkins -> Manage Jenkins -> Configure System -> Extended E-mail Notification -> Default Pre-send Script
import groovy.json.JsonSlurper
sonarUrl = 'http://10.0.2.74:9000/api/resources?resource=${PROJECT_NAME}' +
'&metrics=ncloc,classes,violations,coverage,tests,' +
'test_success_density,comment_lines_density,duplications_data,' +
'function_complexity'
def conn = new URL(sonarUrl).getText()
def project = new JsonSlurper().parseText(conn)
String report = '' // 一定要声明为String,否则Jenkins执行脚本时报错
def result = project.msr[0]
result.each { item -> report = report + nameMapping(item.key) + ': ' + item.frmt_val + '<br />' }
String detail = 'See project <a href="http://10.0.2.74:9000">${PROJECT_NAME} on Sonar</a> for detail information.'
msg.setContent(report+detail, 'text/html')
def nameMapping (input) {
switch (input) {
case "ncloc":
result = "Total Lines of Code"
break
case "classes":
result = "Total Classes"
break
case "violations":
result = "Total Violations"
break
case "tests":
result = "Total Test Cases"
break
case "test_success_density":
result = "Test Success Rate"
break
case "coverage":
result = "Average Test Coverage"
break
case "comment_lines_density":
result = "Average Comment Lines Rate"
break
case "function_complexity":
result = "Average Function Complexity"
break
default:
reuslt = input
}
}
Jenkins中新建一个名为"USB-TEST"的项目,Configure -> Post-build Actions -> Advanced -> Pre-send Script: ${DEFAULT_PRESEND_SCRIPT}. Note that this token is case sensitive; This template is stored in the file $JENKINS_HOME/hudson.plugins.emailext.ExtendedEmailPublisher.xml;
上面脚本中的msg变量是JDK的javax.mail.internet.MimeMessage对象,用setText()方法设置邮件正文,详细介绍见email-ext官网;
当修改默认Pre-send Script后,各项目的Pre-send Scrpit不会自动更新,需要手工改为${DEFAULT_PRESEND_SCRIPT};
构建项目后Jenkins会自动发送邮件。
如果邮件正文中没有超链接,将文本格式设为text/plain更简洁,相应地上面的代码改为:
result.each { item -> report = report + nameMapping(item.key) + ': ' + item.frmt_val + '\n' }
msg.setText(report)
调试Groovy脚本的方法
利用Jenkins的Groovy引擎
在"http://10.0.2.74:8088/script"中用Web API调试代码,例如:
import groovy.json.JsonSlurper
sonarUrl = 'http://10.0.2.74:9000/api/resources?resource=ESB' +
'&metrics=ncloc,classes,violations,coverage,tests,' +
'test_success_density,comment_lines_density,duplications_data,' +
'function_complexity'
def conn = new URL(sonarUrl).getText()
def project = new JsonSlurper().parseText(conn)
println project
println project.id
命令行中调试
在命令行中执行groovy myscript.groovy
.