自动修复非格式化但简单的 CheckStyle 问题

Automatically fix non formatting but simple CheckStyle issues

是否有一个命令行工具可以自动修复非格式化但仍然看似简单的 Java 源代码中的 CheckStyle 问题,例如:

我知道 fix formatting and some IDEs have fairly advanced quick fixers 有多种工具,但到目前为止我找不到任何可以递归 运行 在源代码文件夹中或集成到提交挂钩中的工具。

听起来是个不错的挑战,但我也找不到可以执行此操作的自动工具。正如您已经描述的那样,有很多选项可以更改代码格式。对于其他小问题,您也许可以从命令行 运行 Checkstyle 并过滤掉可修复的警告。用于解析和更改 Java 源代码的库可以帮助实际进行更改,例如 JavaParser。也许您可以使用 Java 源代码操作工具(例如 JavaParser.

在相对较少的时间内编写自定义工具

(还有其他工具如ANTLR that could be used; see for more ideas this question on Stack Overflow: Java: parse java source code, extract methods. Some libraries like Roaster and JavaPoet不解析方法体,这使得它们不太适合这种情况。)

作为一个非常简单的示例,假设我们有一个小的 Java class,Checkstyle 会为其生成两条消息(使用简约的 checkstyle-checks.xml Checkstyle 配置文件,仅检查 FinalParametersFinalLocalVariable):

// Example.java:

package q45326752;

public class Example {
    public static void main(String[] arguments) {
        System.out.println("Hello Checkstyle...");

        int perfectNumber = 1 + 2 + 3;

        System.out.println("Perfect number: " + perfectNumber);
    }
}


Checkstyle warnings:

java -jar checkstyle-8.0-all.jar -c checkstyle-checks.xml Example.java
[ERROR] Example.java:4:29: Parameter arguments should be final. [FinalParameters]
[ERROR] Example.java:7:13: Variable 'perfectNumber' should be declared final. [FinalLocalVariable]

使用Java解析器,这两个警告可以像这样自动修复(代码试图演示这个想法;现在忽略了一些部分):

// AutomaticCheckstyleFix.java:

package q45326752;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.body.*;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.stmt.*;

import java.io.File;
import java.io.FileNotFoundException;

public class AutomaticCheckstyleFix {
    private MethodDeclaration bestMatchMethod;
    private int bestMatchMethodLineNumber;
    private Statement statementByLineNumber;

    public static void main(final String[] arguments) {
        final String filePath = "q45326752\input\Example.java";

        try {
            new AutomaticCheckstyleFix().fixSimpleCheckstyleIssues(new File(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void fixSimpleCheckstyleIssues(File file) throws FileNotFoundException {
        CompilationUnit javaClass = JavaParser.parse(file);
        System.out.println("Original Java class:\n\n" + javaClass);
        System.out.println();
        System.out.println();

        // Example.java:4:29: Parameter arguments should be final. [FinalParameters]
        MethodDeclaration methodIssue1 = getMethodByLineNumber(javaClass, 4);
        if (methodIssue1 != null) {
            methodIssue1.getParameterByName("arguments")
                  .ifPresent(parameter -> parameter.setModifier(Modifier.FINAL, true));
        }

        // Example.java:7:13: Variable 'perfectNumber' should be declared final.
        // [FinalLocalVariable]
        Statement statementIssue2 = getStatementByLineNumber(javaClass, 7);
        if (statementIssue2 instanceof ExpressionStmt) {
            Expression expression = ((ExpressionStmt) statementIssue2).getExpression();
            if (expression instanceof VariableDeclarationExpr) {
                ((VariableDeclarationExpr) expression).addModifier(Modifier.FINAL);
            }
        }

        System.out.println("Modified Java class:\n\n" + javaClass);
    }

    private MethodDeclaration getMethodByLineNumber(CompilationUnit javaClass,
                                                    int issueLineNumber) {
        bestMatchMethod = null;

        javaClass.getTypes().forEach(type -> type.getMembers().stream()
                .filter(declaration -> declaration instanceof MethodDeclaration)
                .forEach(method -> {
                    if (method.getTokenRange().isPresent()) {
                        int methodLineNumber = method.getTokenRange().get()
                                .getBegin().getRange().begin.line;
                        if (bestMatchMethod == null
                                || (methodLineNumber < issueLineNumber
                                && methodLineNumber > bestMatchMethodLineNumber)) {
                            bestMatchMethod = (MethodDeclaration) method;
                            bestMatchMethodLineNumber = methodLineNumber;
                        }
                    }
                })
        );

        return bestMatchMethod;
    }

    private Statement getStatementByLineNumber(CompilationUnit javaClass,
                                               int issueLineNumber) {
        statementByLineNumber = null;

        MethodDeclaration method = getMethodByLineNumber(javaClass, issueLineNumber);
        if (method != null) {
            method.getBody().ifPresent(blockStmt
                    -> blockStmt.getStatements().forEach(statement
                    -> statement.getTokenRange().ifPresent(tokenRange -> {
                if (tokenRange.getBegin().getRange().begin.line == issueLineNumber) {
                    statementByLineNumber = statement;
                }
            })));
        }

        return statementByLineNumber;
    }
}

另一种方法是根据您尝试为其创建自动修复的插件创建新的 Checkstyle 插件。也许您有足够的可用信息,不仅可以发出警告,还可以生成修复了这些问题的修改版本。

就个人而言,我不愿意在提交时自动修复问题。当需要进行许多简单的修复时,自动化是受欢迎的,但我想在提交之前检查这些更改。 运行像这样的工具并检查更改可能是解决许多简单问题的非常快速的方法。

一些我认为可以自动修复的检查: