1.目標
通過jenkins使用checkstyle對代碼進行規范檢查並生成html報告。
構建采用shell。
2.環境
checkstyle5.7(如果是Linux版本選用tar.gz格式)
①其他默認環境(如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作業都應該新建一個類似的ant腳本,只需要更改作業源碼路徑(2處)。
4.jenkins配置
新建一個自由風格的job,配置如下:
這里源碼使用了碼雲的zheng項目,直接放到了該作業工作區的src目錄之下。
5.構建結果
在工作區中新建了一個checkstyle_report目錄,目錄中生成了checkstyle_report.xml和checkstyle_report.html文件。
html格式的報告內容如下: