rewrite icon indicating copy to clipboard operation
rewrite copied to clipboard

Java toolchains for Maven

Open DPUkyle opened this issue 9 months ago • 0 comments

What problem are you trying to solve?

Maven has the little-known ability to allow a project to specify which version of the JDK to be used for compilation and test execution, called toolchains.

The primary benefit for a Maven project is a proscriptive declaration of exactly which version of Maven should be used, removing reliance on JAVA_HOME. This can greatly reduce flakiness and errors caused by JDK fragmentation. Unfortunately, I don't believe there is a way for Maven to auto-provision (e.g. download) the JDK if a matching candidate is not located on the build host.

A secondary benefit is the decoupling the version of Java used to run Maven, vs. the JDK used to build the project. This distinction is really nice when combined with the Maven daemon, for example.

NB Gradle later implemented a similar feature.

What precondition(s) should be checked before applying this recipe?

  1. Maven version is 3.3.1+
  2. If any of the listed plugins here are present, do they meet the required minimum versions?
  3. For MVP, does toolchains.xml file already exist?

Describe the situation before applying the recipe

Root pom.xml

maven-toolchains-plugin plugin not present

Describe the situation after applying the recipe

Something similar to below is added to root pom.xml

<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-toolchains-plugin</artifactId>
        <version>3.2.0</version>
        <configuration>
          <!-- Configure your toolchain requirements here -->
          <toolchain-type>
            <param>expected value</param>
            ...
          </toolchain-type>
          ...
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>toolchain</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Have you considered any alternatives or workarounds?

Can the toolchains.xml file be centrally located, such as in ${user.home}/.m2/? A large organization might prefer this to adding the file to every project.

Any additional context

Should the recipe use the Foojay Disco API (docs) to also download the JDK?

If yes, should this step happen first, then allow the maven-toolchains-plugin to discover and auto-generate its toolchain.xml file? (notes on discovery and generation)

Are you interested in contributing this recipe to OpenRewrite?

Yes.

DPUkyle avatar May 10 '24 16:05 DPUkyle