Jenkins系列——使用checkstyle进行代码规范检查

1.目标

  通过jenkins使用checkstyle对代码进行规范检查并生成html报告。

  构建采用shell。

2.环境

  checkstyle5.7(如果是Linux版本选用tar.gz格式

  apache-ant-1.9.9

①其他默认环境(如jdk)同前 。

②checkstyle没有选择最新版7.6.1是因为7.6.1版本没有将xml格式的报告转换为html报告的xsl文件。

③ant版本不宜选择太高,因为高版本可能需要JDK8+的支持。

④jenkins checkstyle插件主要是用于出版checkstyle报告,这里不涉及。

3.前置工作

  3.1 安装ant及checkstyle。

  3.2 编写ant脚本执行checkstyle构建。

<?xml version="1.0" encoding="UTF-8"?> 
<project name="checkstyle" default="checkstyle" basedir="D:\data\jenkins\workspace\CheckstyleDemo_CODE"> <!-- 检查源码的路径 ,每个作业不同-->
    <target name="init">
        <tstamp/>
        <!-- 设置作业工作目录,每个作业不同 -->
        <property name="project.dir" value="D:\data\jenkins\workspace\CheckstyleDemo_CODE"/>
        <!-- 输出报告的路径  -->
        <property name="project.checkstyle.report.dir" value="${project.dir}\checkstyle_report"/>    
        <property name="project.checkstyle.result.name" value="checkstyle-result.xml"/>
        <property name="project.checkstyle.report.name" value="checkstyle-report.html"/>
        <!-- 检测规则存放路径  -->
        <property name="checkstyle.config" value="D:\data\jenkins\myConf\checkstyle-5.7\sun_checks.xml"/>        
        <property name="checkstyle.report.style" value="D:\data\jenkins\myConf\checkstyle-5.7\contrib\checkstyle-author.xsl"/>    
        <property name="checkstyle.result" value="${project.checkstyle.report.dir}\${project.checkstyle.result.name}"/>    
        <property name="checkstyle.report" value="${project.checkstyle.report.dir}\${project.checkstyle.report.name}"/>    
        <mkdir dir="${project.checkstyle.report.dir}"/>
    </target>
    
    
    <taskdef resource="checkstyletask.properties" classpath="D:\data\jenkins\myConf\checkstyle-5.7\checkstyle-5.7-all.jar" />   
    <target name="checkstyle"  depends="init" description="check java code and report." >          
         <checkstyle config="${checkstyle.config}" failureProperty="checkstyle.failure"  failOnViolation="false">    
            <formatter type="xml"   tofile="${checkstyle.result}" />      
            <fileset dir="${project.dir}\src" includes="**/*.java" /> <!-- 检查源代码的存放路径 -->
        </checkstyle> 
        <!-- 通过指定的xsl模版文件生成一份html的报告,这里生成的文件用于邮件发送时附加上,另外Jenkins插件也会生成可视化的结果  --> 
        <style in="${checkstyle.result}" out="${checkstyle.report}" style="${checkstyle.report.style}" />    
    </target> 
</project>   
checkstyle作业构建脚本

每个checkstyle作业都应该新建一个类似的ant脚本,只需要更改作业源码路径(2处)。

4.jenkins配置

  新建一个自由风格的job,配置如下:

这里源码使用了码云的zheng项目,直接放到了该作业工作区的src目录之下。

5.构建结果

  在工作区中新建了一个checkstyle_report目录,目录中生成了checkstyle_report.xml和checkstyle_report.html文件。

   html格式的报告内容如下:

 

posted @ 2017-04-02 23:51  叶莜落  阅读(6018)  评论(0编辑  收藏  举报