Skip to content

Commit

Permalink
[MJAR-62] Set Build-Jdk according to used toolchain
Browse files Browse the repository at this point in the history
  • Loading branch information
slawekjaranowski committed Mar 24, 2024
1 parent adf1c76 commit fa4330f
Show file tree
Hide file tree
Showing 9 changed files with 392 additions and 21 deletions.
39 changes: 28 additions & 11 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,18 @@
<project.build.outputTimestamp>2022-09-12T15:53:21Z</project.build.outputTimestamp>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.10.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
Expand Down Expand Up @@ -123,33 +135,31 @@

<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-testing</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
<version>3.3.0</version>
<version>4.0.0-alpha-2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-compat</artifactId>
<version>${mavenVersion}</version>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.11.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.15.1</version>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>4.11.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-xml</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
Expand Down Expand Up @@ -178,6 +188,13 @@
</plugin>
</plugins>
</pluginManagement>

<plugins>
<plugin>
<groupId>org.eclipse.sisu</groupId>
<artifactId>sisu-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<profiles>
Expand Down
18 changes: 18 additions & 0 deletions src/it/MJAR-62-toolchain/invoker.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

invoker.toolchain.jdk.version = 17
68 changes: 68 additions & 0 deletions src/it/MJAR-62-toolchain/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>mjar-62</artifactId>
<name>MJAR-62</name>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<organization>
<name>jar plugin it</name>
</organization>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-toolchains-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<goals>
<goal>toolchain</goal>
</goals>
</execution>
</executions>
<configuration>
<toolchains>
<jdk>
<version>17</version>
</jdk>
</toolchains>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>@project.version@</version>
</plugin>
</plugins>
</build>
</project>
36 changes: 36 additions & 0 deletions src/it/MJAR-62-toolchain/src/main/java/myproject/HelloWorld.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package myproject;

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

/**
* The classic Hello World App.
*/
public class HelloWorld {

/**
* Main method.
*
* @param args Not used
*/
public static void main( String[] args )
{
System.out.println( "Hi!" );
}
}
26 changes: 26 additions & 0 deletions src/it/MJAR-62-toolchain/verify.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import java.util.jar.JarFile

def mrjar = new JarFile(new File(basedir, 'target/mjar-62-1.0-SNAPSHOT.jar'))
def manifest = mrjar.manifest.mainAttributes

assert manifest.getValue("Build-Jdk-Spec") == "17"
assert manifest.getValue("Build-Tool-Jdk-Spec") == System.getProperty("java.specification.version")
19 changes: 19 additions & 0 deletions src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.nio.file.FileSystems;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.archiver.MavenArchiver;
Expand All @@ -34,6 +35,7 @@
import org.apache.maven.project.MavenProjectHelper;
import org.apache.maven.shared.model.fileset.FileSet;
import org.apache.maven.shared.model.fileset.util.FileSetManager;
import org.apache.maven.toolchain.ToolchainManager;
import org.codehaus.plexus.archiver.Archiver;
import org.codehaus.plexus.archiver.jar.JarArchiver;

Expand All @@ -53,6 +55,12 @@ public abstract class AbstractJarMojo extends AbstractMojo {

private static final String SEPARATOR = FileSystems.getDefault().getSeparator();

@Component
private ToolchainsJdkSpecification toolchainsJdkSpecification;

@Component
private ToolchainManager toolchainManager;

/**
* List of files to include. Specified as fileset patterns which are relative to the input directory whose contents
* is being packaged into the JAR.
Expand Down Expand Up @@ -250,6 +258,17 @@ public File createArchive() throws MojoExecutionException {
archiver.setArchiver((JarArchiver) archivers.get(archiverName));
archiver.setOutputFile(jarFile);

Optional.ofNullable(toolchainManager.getToolchainFromBuildContext("jdk", session))
.ifPresent(toolchain -> toolchainsJdkSpecification
.getJDKSpecification(toolchain)
.ifPresent(jdkSpec -> {
archive.addManifestEntry("Build-Jdk-Spec", jdkSpec);
archive.addManifestEntry(
"Build-Tool-Jdk-Spec", System.getProperty("java.specification.version"));
archiver.setBuildJdkSpecDefaultEntry(false);
getLog().info("Set Build-Jdk-Spec based on toolchain in maven-jar-plugin " + toolchain);
}));

// configure for Reproducible Builds based on outputTimestamp value
archiver.configureReproducibleBuild(outputTimestamp);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.maven.plugins.jar;

import javax.inject.Named;
import javax.inject.Singleton;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.apache.maven.toolchain.Toolchain;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Component provided JDK specification based on toolchains.
*/
@Named
@Singleton
class ToolchainsJdkSpecification {

private final Logger logger = LoggerFactory.getLogger(ToolchainsJdkSpecification.class);

private final Map<Path, String> cache = new HashMap<>();

public synchronized Optional<String> getJDKSpecification(Toolchain toolchain) {
Optional<Path> javacPath = getJavacPath(toolchain);
return javacPath.map(path -> cache.computeIfAbsent(path, this::getSpecForPath));
}

private Optional<Path> getJavacPath(Toolchain toolchain) {
return Optional.ofNullable(toolchain.findTool("javac")).map(Paths::get).map(this::getCanonicalPath);
}

private Path getCanonicalPath(Path path) {
try {
return path.toRealPath();
} catch (IOException e) {
if (path.getParent() != null) {
return getCanonicalPath(path.getParent()).resolve(path.getFileName());
} else {
throw new UncheckedIOException(e);
}
}
}

private String getSpecForPath(Path path) {
try {
Commandline cl = new Commandline(path.toString());
cl.createArg().setValue("-version");
CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer();
CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();
CommandLineUtils.executeCommandLine(cl, out, err);
String version = out.getOutput().trim();
if (version.isEmpty()) {
version = err.getOutput().trim();
}
if (version.startsWith("javac ")) {
version = version.substring(6);
if (version.startsWith("1.")) {
version = version.substring(0, 3);
} else {
version = version.substring(0, 2);
}
return version;
} else {
logger.warn("Unrecognized output form " + path + " -version - " + version);
return null;
}
} catch (CommandLineException | IndexOutOfBoundsException e) {
logger.warn("Failed to execute: " + path + " - " + e.getMessage());
return null;
}
}
}
Loading

0 comments on commit fa4330f

Please sign in to comment.