|

Simplify Your Code Formatting with the Maven Plugins

Developers often struggle with maintaining a consistent code format throughout their projects. This can lead to messy and hard-to-read codebases. In this blog post, we’ll introduce the few Maven plugins, which simplifies code formatting, enforces your desired code style, and keeps your codebase neat and organized. We’ll guide you through the configuration process and demonstrate its use in a real-world scenario.

In this blog post I will cover following Maven formatting plugins.

In my previous blog post, I have covered about maven checkstyle plugin. The plugin only enforces coding format standards . To format the files either you need to do manually or take the help plugins developed for IDEs. The plugins covered here can check the formatting as well as format the code.

Maven Spotless Plugin

The Maven Spotless plugin is an open-source tool that allows you to automatically apply code formatting rules and styles to your project files. It supports various languages including Java, Kotlin, Scala, Groovy, JavaScript, and more. With this plugin, your team can maintain a consistent coding style throughout the project while minimizing manual effort.

Note

Spotless requires Maven to be running on JRE 11+. To use JRE 8, go back to 2.30.0 or older.

Setting up the Maven Spotless Plugin:

Add following configuration in your pom.xml. The configuration is for google java format.

<plugins>
....
	<plugin>
		<groupId>com.diffplug.spotless</groupId>
		<artifactId>spotless-maven-plugin</artifactId>
		<version>2.39.0</version>
		<configuration>
			<java>
				<googleJavaFormat>
					<version>1.17.0</version>
					<style>GOOGLE</style>
					<reflowLongStrings>true</reflowLongStrings>
				</googleJavaFormat>
			</java>
		</configuration>		
	</plugin>
</plugins>Code language: Java (java)

spotless plugin have 2 goals

  • spotless:check – checks that files adhering to configured formats
  • spotless:appy – applies the formatting rules to files

To find out the formatting violations run following command

mvn spotless:checkCode language: Java (java)
[INFO] --- spotless-maven-plugin:2.39.0:check (default-cli) @ springboot-resource-file ---
[INFO] Spotless.Java is keeping 3 files clean - 1 needs changes to be clean, 0 were already clean, 2 were skipped because caching determined they were already clean
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.227 s
[INFO] Finished at: 2023-09-04T00:31:06+12:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.diffplug.spotless:spotless-maven-plugin:2.39.0:check (default-cli) on project springboot-resource-file: The following files had format violations:
[ERROR]     src\main\java\dev\fullstackcode\resource\file\example\Application.java
[ERROR]         @@ -3,9 +3,7 @@
[ERROR]          import·org.springframework.boot.SpringApplication;
[ERROR]          import·org.springframework.boot.autoconfigure.SpringBootApplication;
[ERROR]          
[ERROR]         -/**
[ERROR]         -·*··Main·Class.
[ERROR]         -·*··*/
[ERROR]         +/**·Main·Class.·*/
[ERROR]          @SpringBootApplication
[ERROR]          public·class·Application·{
[ERROR]          
[ERROR] Run 'mvn spotless:apply' to fix these violations.
Code language: Java (java)

To fix the formatting violations run following command

mvn spotless:applyCode language: Java (java)
[INFO] --- spotless-maven-plugin:2.39.0:apply (default-cli) @ springboot-resource-file ---
[INFO] Writing clean file: D:\IdeaProjects\springboot-resource-file\src\main\java\dev\fullstackcode\resource\file\example\Application.java
[INFO] Spotless.Java is keeping 3 files clean - 1 were changed to be clean, 0 were already clean, 2 were skipped because caching determined they were already clean
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.161 s
[INFO] Finished at: 2023-09-04T00:33:25+12:00
[INFO] ------------------------------------------------------------------------
Code language: Java (java)

By default, spotless:check is bound to verify maven phase. To run the goals with mvn verify command add <executions> section as shown below.

<plugins>
....
	<plugin>
		<groupId>com.diffplug.spotless</groupId>
		<artifactId>spotless-maven-plugin</artifactId>
		<version>2.39.0</version>
		<configuration>
			<java>
				<googleJavaFormat>
					<version>1.17.0</version>
					<style>GOOGLE</style>
					<reflowLongStrings>true</reflowLongStrings>
				</googleJavaFormat>
			</java>
		</configuration>
		<executions>
			<execution>
				<goals>
					<goal>check</goal>
				</goals>
			</execution>
		</executions>
	</plugin>
</plugins>Code language: Java (java)

 If you require the check goal to be run with any other maven phase (i.e. compile) then it can be configured as below;

<executions>
  <execution>
    <goals>
      <goal>check</goal>
    </goals>
    <phase>compile</phase>
  </execution>
</executions>Code language: Java (java)

Specifying Source Directories

By default, spotless plugin apply the formatting rules to files in src/main/java and src/test/java

You can also configure source directories if you want include file from custom directory with <includes> tag

<plugins>
	<plugin>
		<groupId>com.diffplug.spotless</groupId>
		<artifactId>spotless-maven-plugin</artifactId>
		<version>2.39.0</version>
		<configuration>
			<includes>
				<include>src/main/java/**/*.java</include>
				<include>src/test/java/**/*.java</include>
			</includes>
			<java>
				<googleJavaFormat>
					<version>1.17.0</version>
					<style>GOOGLE</style>
					<reflowLongStrings>true</reflowLongStrings>
				</googleJavaFormat>
			</java>
		</configuration>
	</plugin>
</plugins>
Code language: Java (java)

Other formatting options

Other than google java format, you can configure spotless plugin to use other java formatting options.

palantir java format

<configuration>
	<palantirJavaFormat>
		<version>2.10.0</version>		
		<style>PALANTIR</style>		
	</palantirJavaFormat>
</configuration>		
Code language: Java (java)

eclipse jdt format

		
<configuration>
	<eclipse>
		<version>4.26</version>		
		<file>${project.basedir}/eclipse-formatter.xml</file>		
	</eclipse>
</configuration>		
Code language: Java (java)

fmt Maven Plugin

The fmt-maven-plugin is a Maven plugin that leverages the Google Java Format library to format your Java code according to Google’s style guidelines. It can be easily integrated into your existing Maven project and effortlessly formats your code without manual intervention. This means your entire codebase will be consistent following a single style guide, regardless of how many developers are working on it or their individual preferences.

The format cannot be configured by design.

Setting up the fmt-maven-plugin Plugin:

To have your sources automatically formatted on each build, add to following configuration in your pom.xml

    <build>
        <plugins>
            <plugin>
                <groupId>com.spotify.fmt</groupId>
                <artifactId>fmt-maven-plugin</artifactId>
                <version>2.20</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>format</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>Code language: Java (java)

If you want to check only formatting at build time using the check goal:

    <build>
        <plugins>
            <plugin>
                <groupId>com.spotify.fmt</groupId>
                <artifactId>fmt-maven-plugin</artifactId>
                <version>2.20</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>Code language: Java (java)

Overriding the Default Lifecycle Phase

format and check goals are configured to during maven life cycle phases as listed below.

GoalDefault Life Cycle Phase
formatprocess-sources
checkverify

If you run these goals in a different phase instead.
Maven allows you to override the default phase by specifying a <phase> for the <execution>.

For example, you may prefer that the check goal is performed in an earlier phase such as validate:

                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>Code language: Java (java)

Other Configurable Options

sourceDirectory represents the directory where your Java sources that need to be formatted are contained. It defaults to ${project.build.sourceDirectory}

testSourceDirectory represents the directory where your test’s Java sources that need to be formatted are contained. It defaults to ${project.build.testSourceDirectory}

additionalSourceDirectories represents a list of additional directories that contains Java sources that need to be formatted. It defaults to an empty list.

verbose is whether the plugin should print a line for every file that is being formatted. It defaults to false.

filesNamePattern represents the pattern that filters files to format. The defaults value is set to .*\.java.

skip is whether the plugin should skip the operation.

skipSortingImports is whether the plugin should skip sorting imports.

skipSourceDirectory is whether the plugin should skip formatting/checking the sourceDirectory. It defaults to false.

skipTestSourceDirectory is whether the plugin should skip formatting/checking the testSourceDirectory. It defaults to false.

style sets the formatter style to be google or aosp. By default this is google. Projects using Android conventions may prefer aosp.

forkMode lets you specify whether to run google-java-format in a fork or in-proces

<build>
    <plugins>
        <plugin>
            <groupId>com.spotify.fmt</groupId>
            <artifactId>fmt-maven-plugin</artifactId>
            <version>VERSION</version>
            <configuration>
                <sourceDirectory>some/source/directory</sourceDirectory>
                <testSourceDirectory>some/test/directory</testSourceDirectory>
                <verbose>true</verbose>
                <filesNamePattern>.*\.java</filesNamePattern>
                <additionalSourceDirectories>
                    <param>some/dir</param>
                    <param>some/other/dir</param>
                </additionalSourceDirectories>
                <skip>false</skip>
                <skipSourceDirectory>false</skipSourceDirectory>
                <skipTestSourceDirectory>false</skipTestSourceDirectory>
                <skipSortingImports>false</skipSortingImports>
                <style>google</style>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>format</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>Code language: Java (java)

Similar Posts