Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add maven plugin #2

Merged
merged 6 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions generator/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.github.runeflobakk</groupId>
<artifactId>record-matcher-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>

<artifactId>record-matcher-codegenerator</artifactId>

<name>Record Matcher Code Generator</name>
<description>Generates Hamcrest matchers for Java records</description>

<dependencies>
<dependency>
<groupId>com.squareup</groupId>
<artifactId>javapoet</artifactId>
<version>1.13.0</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>uk.co.probablyfine</groupId>
<artifactId>java-8-matchers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.testing.compile</groupId>
<artifactId>compile-testing</artifactId>
<version>0.21.0</version>
</dependency>
</dependencies>

</project>
75 changes: 75 additions & 0 deletions maven-plugin/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<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">

<parent>
<groupId>com.github.runeflobakk</groupId>
<artifactId>record-matcher-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>

<modelVersion>4.0.0</modelVersion>
<artifactId>record-matcher-maven-plugin</artifactId>
<packaging>maven-plugin</packaging>

<name>Record Matcher Generator Maven Plugin</name>
<description>Maven plugin for generating Hamcrest matchers for Java records</description>

<properties>
<maven.plugin-tools.version>3.10.2</maven.plugin-tools.version>
</properties>

<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>3.6.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>${maven.plugin-tools.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>3.6.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.runeflobakk</groupId>
<artifactId>record-matcher-codegenerator</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.9</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
<version>${maven.plugin-tools.version}</version>
<executions>
<execution>
<id>help-goal</id>
<goals>
<goal>helpmojo</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package no.rune.record;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

import static java.util.function.Predicate.not;
import static org.apache.maven.plugins.annotations.LifecyclePhase.GENERATE_TEST_SOURCES;
import static org.apache.maven.plugins.annotations.ResolutionScope.COMPILE;

@Mojo(name = "generate", defaultPhase = GENERATE_TEST_SOURCES, requiresDependencyResolution = COMPILE)
public class GenerateRecordMatcherMojo extends AbstractMojo {

private static final Logger LOG = LoggerFactory.getLogger(GenerateRecordMatcherMojo.class);
private static final String PLUGIN_CONF_PROP_PREFIX = "recordmatcher.";

/**
* Specifies the fully qualified class names of the records to
* generate Hamcrest matchers for.
*/
@Parameter
private Set<String> includes;


/**
* The directory where the generated Hamcrest matchers will be written to.
*/
@Parameter(required = true,
defaultValue = "${project.build.directory}/generated-test-sources/record-matchers",
property = PLUGIN_CONF_PROP_PREFIX + "outputDirectory")
private File outputDirectory;


/**
* Whether the {@link #outputDirectory} should be included as a test sources root.
*/
@Parameter(required = true,
defaultValue = "true",
property = PLUGIN_CONF_PROP_PREFIX + "includeGeneratedCodeAsTestSources")
private boolean includeGeneratedCodeAsTestSources;


@Parameter(required = true, readonly = true,
defaultValue = "${project}")
private MavenProject mavenProject;


@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (includes != null && !includes.isEmpty()) {
Path outputDirectory = resolveOutputDirectory();
if (includeGeneratedCodeAsTestSources) {
mavenProject.addTestCompileSourceRoot(outputDirectory.toString());
LOG.debug("{} has been added as a compiler test sources directory", outputDirectory);
}
try {
Files.createDirectories(outputDirectory);
LOG.info("Generating Hamcrest matchers in {}", outputDirectory);
} catch (IOException e) {
throw new UncheckedIOException(
"Unable to create output directory " + outputDirectory + ", " +
"because " + e.getClass().getSimpleName() + ": " + e.getMessage(), e);
}
var generator = new RecordMatcherGenerator();
resolveIncludedRecords().forEach(recordClass -> {
var recordMatcherSourceCode = generator.generateFromRecord(recordClass);
var matcherClassFileTargetDirectory = outputDirectory.resolve(Path.of(recordClass.getPackageName().replace('.', '/')));
var matcherTargetFile = matcherClassFileTargetDirectory.resolve(recordClass.getSimpleName() + "Matcher.java");
try {
Files.createDirectories(matcherClassFileTargetDirectory);
Files.writeString(matcherTargetFile, recordMatcherSourceCode);
} catch (IOException e) {
throw new UncheckedIOException("Unable to write to " + matcherTargetFile + ", " +
"because " + e.getClass().getSimpleName() + ": " + e.getMessage(), e);
}
LOG.info("Generated matcher {}", outputDirectory.relativize(matcherTargetFile));
});
} else {
LOG.warn("No records to generate Hamcrest matchers from!");
}
}

private Path resolveOutputDirectory() {
return outputDirectory.toPath();
}


private Stream<Class<? extends Record>> resolveIncludedRecords() {
ClassLoader classLoader = buildProjectClassLoader(mavenProject, this.getClass().getClassLoader());
return includes.stream()
.filter(not(String::isBlank))
.map(String::trim)
.map(recordClassName -> {
try {
return classLoader.loadClass(recordClassName);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(
"Unable to resolve Class from " + recordClassName +
", because " + e.getClass().getSimpleName() + ": " + e.getMessage(), e);
}
})
.map(c -> c.asSubclass(Record.class));
}


private static ClassLoader buildProjectClassLoader(MavenProject project, ClassLoader parent) {
try {
@SuppressWarnings("unchecked")
List<String> classpathElements = project.getCompileClasspathElements();
URL urls[] = new URL[classpathElements.size()];
for ( int i = 0; i < classpathElements.size(); ++i )
{
urls[i] = new File( classpathElements.get( i ) ).toURI().toURL();
}
return new URLClassLoader(urls, parent);
} catch (Exception e) {
throw new RuntimeException(
"Unable to build classloader for resolving record classes, " +
", because " + e.getClass().getSimpleName() + ": " + e.getMessage(), e);
}
}

}
64 changes: 25 additions & 39 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@
<modelVersion>4.0.0</modelVersion>

<groupId>com.github.runeflobakk</groupId>
<artifactId>record-matcher</artifactId>
<artifactId>record-matcher-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Record Matcher</name>
<description>Generates Hamcrest matchers for Java records</description>
<name>Record Matcher Parent POM</name>
<description>Parent POM for Record Matcher</description>
<url>https://github.com/runeflobakk/record-matcher</url>

<modules>
<module>generator</module>
<module>maven-plugin</module>
</modules>

<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
Expand All @@ -30,43 +36,23 @@
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.8.2</version>
<version>5.10.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>uk.co.probablyfine</groupId>
<artifactId>java-8-matchers</artifactId>
<version>1.9</version>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>com.squareup</groupId>
<artifactId>javapoet</artifactId>
<version>1.13.0</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>uk.co.probablyfine</groupId>
<artifactId>java-8-matchers</artifactId>
<version>1.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.testing.compile</groupId>
<artifactId>compile-testing</artifactId>
<version>0.19</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
Expand Down Expand Up @@ -120,11 +106,11 @@
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.3.1</version>
<version>3.3.2</version>
</plugin>
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.3.0</version>
<version>3.4.1</version>
<configuration>
<rules>
<requireMavenVersion>
Expand Down Expand Up @@ -157,7 +143,7 @@
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
Expand All @@ -180,7 +166,7 @@
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.5.0</version>
<version>3.6.3</version>
<configuration>
<doclint>all,-missing</doclint>
<quiet>true</quiet>
Expand All @@ -189,7 +175,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.16.0</version>
<version>2.16.2</version>
<configuration>
<generateBackupPoms>false</generateBackupPoms>
</configuration>
Expand Down
Loading