'How to format code according to google java format in my github workflow with maven
I have written this workflow below to verify the Java format in my project according to Google Java style guides. My intention is to use maven in the workflow.
# 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
With gradle I would have make it executable with chmod +x gradlew and run with ./gradlew verifyGoogleJavaFormat.
My question is how can I achieve this with maven. With above workflow I get the following error:
Unknown lifecycle phase "verifyGoogleJavaFormat".
Solution 1:[1]
You need to include a maven plugin that supports Googles Java format. It seems like your goal verifyGoogleJavaFormat is available for Gradle, but not for Maven. One option is to use https://github.com/Cosium/git-code-format-maven-plugin. It supports format verification and automatic formatting upon comitting.
The Github Repo documentation states that you can include it in your pom.xml like this:
<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>
Now, when I run mvn verify on my unformatted project I get an error:
[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]
When we make our next commit the formatter is automatically applied via a Git hook and the next mvn verify succeeds.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bastis Programming Corner |
