checkstyle+ant配置

目的:

checkstyle是apache项目组提供的一款代码规范检测工具,使用checkstyle,可以帮助开发人员快速找到不符合规范要求的代码,本文将要介绍的是如何在ant中配置checkstyle,以生成代码质量检测报告。

版本:

      checkstyle5.3,ant1.7.1及以上

ant配置文件内容

<?xml version="1.0" encoding="UTF-8"?>
<project name="Checkstyle" default="xml2html" basedir=".">
	<property file="build.properties" />

	<!--前面省略项目中的其他target -->
	<!-- 定义lib存放目录 -->
	<property name="lib.dir" value="${basedir}/lib/checkstyle5.3" />

	<!-- 定义输出结果目录 -->
	<property name="result.dir" value="${basedir}/result" />

	<!-- 定义输出结果目录 -->
	<property name="result.html" value="${basedir}/result/html" />
	<!-- 定义源码目录 配置该文件时请确认此目录 -->
	<property name="src.dir" value="${basedir}/../src" />
	<!--  初始化输出结果目录 -->
	<target name="init">
		<delete dir="${result.dir}" />
		<mkdir dir="${result.dir}" />
		<!--<mkdir dir="${result.html}" />-->
	</target>
	<!-- 引入ant的<checkstyle>命令 checkstyletask.properties文件在jar包中 -->
	<taskdef resource="checkstyletask.properties" classpath="${basedir}/lib/checkstyle-5.3-all.jar" />
	<!-- 定义checkstyle执行计划 -->
	<target name="cs" description="Generates a report of code convention violations." depends="init">
		<!-- 指定检查规范为GS_java_check.xml  fileset指的要检查的文件;formatter type指结果返回格式 -->
		<checkstyle failonviolation="false" config="${lib.dir}/my_java_check.xml">
			<fileset dir="${basedir}/../src" includes="**/*.java" />
			<formatter type="plain" />
			<formatter type="xml" toFile="${result.dir}/checkstyle_report.xml" />
		</checkstyle>
	</target>
	<target name="xml2html" depends="cs">
		<!-- 将生产结果根据扩展样式表文件checkstyle-frames.xsl生成html页面,输出到html -->
		<xslt basedir="${result.dir}" destdir="${result.html}" extension=".html" style="${lib.dir}/checkstyle-frames.xsl">
			<param name="output.dir" expression="${result.html}" />
		</xslt>
	</target>
</project>

其中my_java_check.xm为checkstyle代码规范配置文件,可以在改文件中设置代码检测条件,

如:每个方法代码行数限制、java类的总长度、try/catch嵌套次数等等;

checkstyle-frames.xs是样式配置文件,l在xml转化htm时需要用到,该文件可以在checkstyle-5.3-all.jar包中找到;

ant文件包含了3个任务:

1)初始化输出目录,包含checkstyle生成文件目录,以及转换生成html格式文件目录

2)checkstyle检测代码,并见检测结果输出到checkstyle_report.xml文件

3)根据checkstyle-noframes.xs样式表,将checkstyle_report.xm转换为html格式文件

注意点:

在init target中,需要将<mkdir dir="${result.html}" />去掉,否则在执行xml转换时,会提示如下错误:

[xslt] : Error! The element type "META" must be terminated by the matching end-tag "</META>".

     [xslt] : Error! com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: The element type "META" must be terminated by the matching end-tag "</META>".

     [xslt] Failed to process null

BUILD FAILED

D:\workspace\workspace_study\test\bulid\build-cs.xml:40: javax.xml.transform.TransformerException: javax.xml.transform.TransformerException: com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: The element type "META" must be terminated by the matching end-tag "</META>".


猜你喜欢

转载自teared.iteye.com/blog/1079564