下面是Jenkins的presend script模板(用${DEFAULT_PRESEND_SCRIPT}引用)的内容:
content = /<table width="100%">
<tr>
<td bgcolor="silver" valign="top" width="25%">
<h3>代码总行数<\/h3>
<h2>${getVal('ncloc')}<\/h2>
<p>${getVal('lines')} 行<\/p>
<p>${getVal('statements')} 语句<\/p>
<p>${getVal('files')} 文件<\/p>
<\/td>
<td valign="top" width="25%"> <h3>类<\/h3> <h2>${getVal('classes')}<\/h2> <p>${getVal('packages')} 包<\/p> <p>${getVal('functions')} 方法<\/p> <p>${getVal('accessors')} 存取<\/p> <\/td> <td bgcolor="silver" valign="top" width="25%"> <h3>事务<\/h3> <h2>${getVal('violations')}<\/h2> <h3>遵守规则<\/h3> <h2>${getVal('violations_density')}<\/h2> <\/td>
<\/tr>
<tr><td valign="top"><p\/><hr\/><p\/><\/td><\/tr>
<tr>
<td bgcolor="silver" valign="top" width="25%">
<h3>注释<\/h3>
<h2>${getVal('comment_lines_density')}<\/h2>
<p>${getVal('comment_lines')} 行<\/p>
<p>${getVal('public_documented_api_density')} 注释了的API<\/p>
<p>${getVal('public_undocumented_api')} 未注释的API<\/p>
<\/td>
<td valign="top" width="25%">
<h3>重复<\/h3>
<h2>${getVal('duplicated_lines_density')}<\/h2>
<p>${getVal('duplicated_lines')} 行<\/p>
<p>${getVal('duplicated_blocks')} 块<\/p>
<p>${getVal('duplicated_files')} 文件<\/p>
<\/td>
<td bgcolor="silver" valign="top" width="25%">
<h3>代码覆盖率<\/h3>
<h2>${getVal('coverage')}<\/h2>
<p>${getVal('line_coverage')} 行覆盖率<\/p>
<p>${getVal('branch_coverage')} 分支覆盖率<\/p>
<\/td>
<td valign="top" width="25%">
<h3>单元测试成功<\/h3>
<h2>${getVal('test_success_density')}<\/h2>
<p>${getVal('test_failures')} 失败<\/p>
<p>${getVal('tests')} 测试<\/p>
<p>${getVal('test_execution_time')}<\/p>
<\/td>
<\/tr>
<tr><td valign="top"><p\/><hr\/><p\/><\/td><\/tr>
<tr>
<td valign="top" width="25%">
<h3>复杂度<\/h3>
<h2>${getVal('function_complexity')} \/方法<\/h2>
<h2>${getVal('class_complexity')} \/类<\/h2>
<h2>${getVal('file_complexity')} \/文件<\/h2>
<p>总数:${getVal('complexity')}<\/p>
<\/td>
<\/tr>
<\/table>
详细结果见SonarQube上的<a href="http:\/\/10.0.2.74:9000\/dashboard\/index\/\({getID()}">\)项目<\/a>。 /
import groovy.json.JsonSlurper
msg.setText(content.toString(), 'UTF-8', 'html')
def getVal(name) {
sonarUrl = 'http://10.0.2.74:9000/api/resources?resource=${PROJECT_DISPLAY_NAME}&metrics=' + name
data = new JsonSlurper().parseText(new URL(sonarUrl).getText())
data.msr[0].frmt_val[0]
}
def getID() {
sonarUrl = 'http://10.0.2.74:9000/api/resources?resource=${PROJECT_DISPLAY_NAME}'
data = new JsonSlurper().parseText(new URL(sonarUrl).getText())
data.id[0]
}
Note1:使用msg.setText(string, charset, 'html')
而不是setContent方法,后者无法设置charset,中文显示为乱码;
Note2:Groovy中使用/.../表示多行字符串,但内容中的"/"需要转义为"\/";
Note3:当使用\({PROJECT_NAME}不方便时,可以用\)代替,这个值在项目的 Configure -> Advanced Project Options -> Display Name中设置。