如何在我的github工作流中使用maven根据googlejava格式格式化代码



我在下面编写了这个工作流,以根据Google Java风格指南验证我的项目中的Java格式。我的意图是在工作流中使用maven。

# Checks that the code is formatted according to the
# Google Java style guide
name: Code Formatter Check
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
distribution: 'adopt'
cache: maven
- name: Build with maven
run: mvn --batch-mode --update-snapshots verify verifyGoogleJavaFormat

有了gradle,我就可以用chmod +x gradlew执行它,用./gradlew verifyGoogleJavaFormat运行它。

我的问题是如何与maven一起实现这一点。使用以上工作流程,我得到以下错误:

未知的生命周期阶段"verifyGoogleJavaFormat";。

您需要包含一个支持Google Java格式的maven插件。您的目标验证GoogleJavaFormat似乎适用于Gradle,但不适用于Maven。一种选择是使用https://github.com/Cosium/git-code-format-maven-plugin.它支持格式验证和调试时的自动格式化。

Github Repo文档指出,您可以将其包含在pom.xml中,如下所示:

<build>
<plugins>
<plugin>
<groupId>com.cosium.code</groupId>
<artifactId>git-code-format-maven-plugin</artifactId>
<version>3.3</version>
<executions>
<!-- On commit, format the modified java files -->
<execution>
<id>install-formatter-hook</id>
<goals>
<goal>install-hooks</goal>
</goals>
</execution>
<!-- On Maven verify phase, fail if any file
(including unmodified) is badly formatted -->
<execution>
<id>validate-code-format</id>
<goals>
<goal>validate-code-format</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

现在,当我在未格式化的项目上运行mvn verify时,我得到一个错误:

[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  6.090 s
[INFO] Finished at: 2022-03-12T17:56:13+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.cosium.code:git-code-format-maven-plugin:3.3:validate-code-format (validate-code-format) on project javatest: /home/bisensee/repos/javatest/src/main/java/Position.java is not correctly formatted ! -> [Help 1] 

当我们进行下一次提交时,格式化程序会通过Git挂钩自动应用,下一次mvn verify成功。

最新更新