Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format code according to google java format

Current state:

I have a project which is build with: Java 1.8.161, Maven 3.3.9, SpringBoot 2.0.1, tools: Jenkins and GitLab. I would like to use google java format as a standard for whole team.

My investigation / solution:

During the investigation I found solution, which sounds really easy. Just update pom file with:

<build>
    <plugins>
        <plugin>
            <groupId>com.coveo</groupId>
            <artifactId>fmt-maven-plugin</artifactId>
            <version>2.5.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>format</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

And it works. If I run compile, package, verify, install or deploy Maven lifecycle the code is formatted.

Question:

How can I run this after i.e. each commit for all team members without any extra steps in their IDEA? Because right now, I need to run Maven before each commit. But during the run of an application it is not necessary, so the team can avoid it.. Which of course will lead to problems with history in git.

like image 605
Beginner Avatar asked Jun 14 '18 12:06

Beginner


People also ask

How do I format Java code?

Window -> Preferences -> Java -> Editor -> Save Action -> Format source code (Format all lines & Imports)

How do I enable google formatter in IntelliJ?

To enable it in the current project, go to File→Settings... →google-java-format Settings (or IntelliJ IDEA→Preferences... →Other Settings→google-java-format Settings on macOS) and check the Enable google-java-format checkbox.

How do I add google style to IntelliJ?

Next to the Scheme drop-down menu select the gear icon then Import Scheme > IntelliJ IDEA code style XML then select the intellij-java-google-style. xml file you downloaded from GitHub. Give the schema a name (or use the default GoogleStyle name from the import). Click OK or Apply for the settings to take effect.


2 Answers

You can let pre-commit hook trigger formatter for files staged for commit.

git-code-format-maven-plugin uses google-java-format formatter and can install client-side pre-commit git hook during compile phase. It requires Maven 3.5.x, which should be enforced.

<build>
  <plugins>
    <plugin>
      <groupId>com.cosium.code</groupId>
      <artifactId>git-code-format-maven-plugin</artifactId>
      <version>VERSION</version>
      <executions>
        <execution>
          <goals>
            <goal>install-hooks</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <artifactId>maven-enforcer-plugin</artifactId>
      <version>VERSION</version>
      <executions>
        <execution>
          <goals>
            <goal>enforce</goal>
          </goals>
          <configuration>
            <rules>
              <requireMavenVersion>
                <version>[3.5.4,)</version>
              </requireMavenVersion>
            </rules>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Point to standalone Maven in IDE as git-code-format-maven-plugin does not play along nicely with embedded Maven.

mvn compile to get hook installed. For IDEA, that's it.

As git-code-format-maven-plugin only formats changed files (which is good), it is probably good to format whole project upfront once (mvn git-code-format:format-code -Dgcf.globPattern=**/*).

Workaround for Eclipse

Because of a bug in EGit, which sometimes ignores Git hooks completely, developers using Eclipse on Windows should have Cygwin in PATH. An empty cygpath.exe will do. Run 'Command Prompt' as a administrator and execute C:\>echo "" > /"Program Files"/Git/bin/cygpath.exe (kudos to hook is not working eclipse egit client).

Reboot.

A note on java import statements ordering

Optimise imports or reformat in IDE or reformat with plugins, can lead to changes in imports ordering. A nasty surprise if an older version of git-code-format-maven-plugin is being used together with fmt-maven-plugin (to format or validate code later in CI, for example).

  • git-code-format-maven-plugin will sort imports (since version 1.20)
  • fmt-maven-plugin will always sort imports
  • googleformatter-maven-plugin can optionally sort imports (not per default)
like image 153
zziga Avatar answered Sep 26 '22 02:09

zziga


In order to run this formatter after each developer commit, you will have to first have a Jenkins commit hook in place, that will trigger a Jenkins build. One of the phases of the build, should execute the fmt-maven-plugin's (or any others) check functionality in order to ensure that the code is properly formatted.

Adding a webhook

First thing to do is add a webhook that will trigger a Jenkins build after every commit in your git repository. You can find how to do this here. For Gitlab specific instructions, this post from medium may be helpful.

Executing the check

This can be done by executing the check goal on the fmt-maven-plugin

Maven acceps either <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal> as a means of calling a plugin goal, so for your specific problem, you can run:

mvn fmt:check

That being said, you will have to add a Jenkins build step, that will run the mentioned command. Step 5 from this tutorial shows you how to add a build step.

Hope that this actually helps :D

like image 42
dragos.triteanu Avatar answered Sep 23 '22 02:09

dragos.triteanu