|
| 1 | +# Maven plugin |
| 2 | + |
| 3 | +The plugin formats the Java sources of a Maven build, or fails the build when they are not |
| 4 | +formatted. Maven has to run on Java 21 or later. |
| 5 | + |
| 6 | +## Add the plugin |
| 7 | + |
| 8 | +``` xml title="pom.xml" |
| 9 | +<build> |
| 10 | + <plugins> |
| 11 | + <plugin> |
| 12 | + <groupId>dev.openjavaformat</groupId> |
| 13 | + <artifactId>fmt-maven-plugin</artifactId> |
| 14 | + <version>{{ maven_plugin_version }}</version> |
| 15 | + <executions> |
| 16 | + <execution> |
| 17 | + <goals> |
| 18 | + <goal>format</goal> |
| 19 | + </goals> |
| 20 | + </execution> |
| 21 | + </executions> |
| 22 | + <dependencies> |
| 23 | + <dependency> |
| 24 | + <groupId>dev.openjavaformat</groupId> |
| 25 | + <artifactId>open-java-format</artifactId> |
| 26 | + <version>{{ ojf_version }}</version> |
| 27 | + </dependency> |
| 28 | + </dependencies> |
| 29 | + </plugin> |
| 30 | + </plugins> |
| 31 | +</build> |
| 32 | +``` |
| 33 | + |
| 34 | +The `format` goal runs in the `process-sources` phase, so `mvn compile`, `mvn test` and every later |
| 35 | +phase format `src/main/java` and `src/test/java` first. |
| 36 | + |
| 37 | +The dependency is not optional. The plugin does not bring a formatter of its own: it runs the |
| 38 | +open-java-format version named there, and without it the build stops with a message that says what |
| 39 | +to add. Name the same version as in your IDE and your other builds. |
| 40 | + |
| 41 | +## Check in CI |
| 42 | + |
| 43 | +Use the `check` goal instead of `format`. It changes no file, and in the `verify` phase it fails the |
| 44 | +build when a file is not formatted: |
| 45 | + |
| 46 | +``` text title="mvn verify" |
| 47 | +[ERROR] Found 1 non-complying files, failing build |
| 48 | +[ERROR] To fix formatting errors, run "mvn dev.openjavaformat:fmt-maven-plugin:format" |
| 49 | +``` |
| 50 | + |
| 51 | +## Run a goal from the command line |
| 52 | + |
| 53 | +``` sh |
| 54 | +mvn dev.openjavaformat:fmt-maven-plugin:format |
| 55 | +mvn dev.openjavaformat:fmt-maven-plugin:check |
| 56 | +``` |
| 57 | + |
| 58 | +The plugin still has to be in the `pom.xml` with its dependency: Maven reads the dependencies of a |
| 59 | +plugin from the POM, never from the command line. |
| 60 | + |
| 61 | +## Options |
| 62 | + |
| 63 | +The plugin is a fork of [spotify/fmt-maven-plugin](https://github.com/spotify/fmt-maven-plugin) with |
| 64 | +open-java-format in place of google-java-format. Its options, such as extra source directories, file |
| 65 | +name patterns and skipping a directory, are listed in |
| 66 | +[its README](https://github.com/openjavaformat/fmt-maven-plugin#options). There is nothing to set for |
| 67 | +the formatting itself: imports are always sorted and cleaned up, and long strings are always |
| 68 | +reflowed, as on every other route. |
0 commit comments