Cra*_*lin 14 java whitespace tabs static-analysis
CheckStyle提供检查空间的一致使用,但遗憾的是缺乏相反的想法:强制源代码使用选项卡.有没有办法添加此功能?它不一定是CheckStyle,也欢迎其他工具.
与此问题相同,但对于Java.
编辑
我不需要代码美化,因为代码库的正常状态将是所有选项卡.我只需要一个可以报告备用缩进的工具.这样我就可以设置一个新的连续构建配置,当引入空格时它将失败.
首选使用空格而不是制表符缩进,因为它提供了所有编辑器/查看器的布局一致性.但是如果您仍然想要它,您可以随时自定义检查checkstyle或自定义maven插件/ ant任务.逻辑也不难实现 - 你必须检查任何行上的前导空格是否大于制表符长度.
编辑:包括一个蚂蚁的例子.自你发布以来已经过去两周,你仍然不开心,我有一些空闲时间:)所以我为你准备了一个小蚂蚁自定义任务解决方案.
Ant任务
public class SpaceDetectorTask extends Task {
public static final String REGEX = "^[ ]+";
public static final Pattern p = Pattern.compile(REGEX);
private FileSet fileSet;
private boolean failOnDetection;
// Usual getters/setters
public void addFileSet(FileSet fileSet) {
this.fileSet = fileSet;
}
public void execute() {
DirectoryScanner ds = fileSet.getDirectoryScanner();
String[] files = ds.getIncludedFiles();
for (int x = 0; x <= files.length -1; x++) {
process(ds.getBasedir(), files[x]);
}
}
public void process(File dir, String file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(new File(dir, file)));
String line;
int linecount = 0;
System.out.println("File: " + file);
boolean ignore = false;
while((line = reader.readLine()) != null) {
linecount++;
// exclude comment blocks
if (line.contains("/**") || line.contains("*/")) {
ignore = !ignore;
continue;
}
if (!ignore) {
if (p.matcher(line).find()) {
int spcCount = line.length() - (line.replaceAll(REGEX, "")).length();
if (spcCount >= 4) { // break whenever 4 leading spaces are detected. Configure as you need.
String msg = "File: "+ file + " is using spaces as indentation.";
if (failOnDetection) {
throw new BuildException(msg);
} else {
getProject().log(msg);
}
}
}
reader.close();
}
}
} catch (IOException e) {
if (failOnDetection) {
throw new BuildException(e);
} else {
getProject().log("File: " + file + "\n" + e.getMessage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
在ant build.xml中
宣布它
<taskdef name="detect-spaces"
classname="com.blah.blah.build.tools.SpaceDetectorTask">
<classpath>
<pathelement path="${dir.classes}"/>
<fileset dir="C:/apache-ant-1.7.1/lib">
<include name="**/*.jar"/>
</fileset>
</classpath>
</taskdef>
Run Code Online (Sandbox Code Playgroud)用它
<target name="rules.spaces">
<detect-spaces
failOnDetection="true">
<fileset dir="${dir.src.java}">
<include name="**/*.java"/>
</fileset>
</detect-spaces>
</target>
Run Code Online (Sandbox Code Playgroud)编写maven/checkstyle插件也很困难.
虽然Checkstyle没有内置检查,但您可以使用RegexpSinglelineJava检查强制执行仅限制表符缩进.请注意,这仅检查哪个字符用于缩进,而不是用于正确的缩进级别.
从Hibernate OGM源无耻地窃取:
<module name="RegexpSinglelineJava">
<property name="format" value="^\t* +\t*\S"/>
<property name="message" value="Line has leading space characters; indentation should be performed with tabs only."/>
<property name="ignoreComments" value="true"/>
</module>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4971 次 |
| 最近记录: |