Skip to content

Commit

Permalink
More expressive return type from generator
Browse files Browse the repository at this point in the history
Instead of returning just a String with the Java source file
(compilation unit), instead include all information needed to correctly
write the source to a file.
  • Loading branch information
runeflobakk committed Mar 11, 2024
1 parent 5156e0b commit c80ae40
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package no.rune.record.matcher;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.util.Optional;

import static java.nio.file.Files.isDirectory;

public record JavaCompilationUnit(String content, String name, Optional<String> packageName) {

public JavaCompilationUnit(String content, String name, Package location) {
this(content, name, Optional.of(location).map(Package::getName));
}

Path writeToBaseDirectory(Path baseDirectory) throws NotDirectoryException, IOException {
if (!isDirectory(baseDirectory)) {
throw new NotDirectoryException(baseDirectory.toString());
}
var targetDirectory = packageName.map(p -> baseDirectory.resolve(p.replace('.', '/'))).orElse(baseDirectory);
var targetFile = targetDirectory.resolve(name + ".java");
try {
if (!baseDirectory.equals(targetDirectory)) {
Files.createDirectories(targetDirectory);
}
return Files.writeString(targetFile, content);
} catch (IOException e) {
throw new IOException("Unable to write to " + targetFile + ", " +
"because " + e.getClass().getSimpleName() + ": " + e.getMessage(), e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ public class RecordMatcherGenerator {

public static final RecordMatcherClassNameResolver DEFAULT_MATCHER_NAME_RESOLVER = new DefaultRecordMatcherClassNameResolver();

public String generateFromRecord(Class<? extends Record> record) {
public JavaCompilationUnit generateFromRecord(Class<? extends Record> record) {
return generateFromRecord(record, record.getPackage(), DEFAULT_MATCHER_NAME_RESOLVER.resolve(record));
}

public String generateFromRecord(Class<? extends Record> record, Package target, String matcherSimpleClassName) {
public JavaCompilationUnit generateFromRecord(Class<? extends Record> record, Package target, String matcherSimpleClassName) {

var codeFactory = new CodeFactory(record, ClassName.get(target.getName(), matcherSimpleClassName));

Expand Down Expand Up @@ -140,10 +140,11 @@ public String generateFromRecord(Class<? extends Record> record, Package target,
.addMethod(matchesSafelyMethodBuilder.build());


return JavaFile.builder(target.getName(), matcherClassBuilder.build())
String compilationUnitContent = JavaFile.builder(target.getName(), matcherClassBuilder.build())
.indent(" ")
.skipJavaLangImports(true)
.build().toString();
return new JavaCompilationUnit(compilationUnitContent, matcherSimpleClassName, target);
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package no.rune.record.matcher;

import no.rune.record.matcher.DefaultRecordMatcherClassNameResolver;
import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ public static ExpectedMatcher expectedMatcherFor(Class<? extends Record> record)

private static final RecordMatcherGenerator generator = new RecordMatcherGenerator();

public String generatedSourceCode() {
public JavaCompilationUnit generatedSourceCode() {
return generator.generateFromRecord(record());
}

public void assertEqualToGeneratedMatcherSourceCode() {
var generatedSourceCode = generatedSourceCode();
assertEquals(sourceCode(), generatedSourceCode);
assertEquals(sourceCode(), generatedSourceCode.content());

var compiledGeneratedMatcher = javac().compile(JavaFileObjects.forSourceString(fullyQualifiedClassName(), generatedSourceCode));
var compiledGeneratedMatcher = javac().compile(JavaFileObjects.forSourceString(fullyQualifiedClassName(), generatedSourceCode.content()));
assertAll(
() -> assertThat(compiledGeneratedMatcher, where(Compilation::status, is(SUCCESS))),
() -> assertThat(compiledGeneratedMatcher, where(Compilation::errors, empty())));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,15 @@ public void execute() throws MojoExecutionException, MojoFailureException {
}
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");
var recordMatcherCompilationUnit = generator.generateFromRecord(recordClass);
try {
Files.createDirectories(matcherClassFileTargetDirectory);
Files.writeString(matcherTargetFile, recordMatcherSourceCode);
var writtenFile = recordMatcherCompilationUnit.writeToBaseDirectory(outputDirectory);
LOG.info("Generated matcher {}", outputDirectory.relativize(writtenFile));
} catch (IOException e) {
throw new UncheckedIOException("Unable to write to " + matcherTargetFile + ", " +
throw new UncheckedIOException(
"Unable to write " + recordMatcherCompilationUnit + " to file, " +
"because " + e.getClass().getSimpleName() + ": " + e.getMessage(), e);
}
LOG.info("Generated matcher {}", outputDirectory.relativize(matcherTargetFile));
});
} else {
LOG.warn("No records to generate Hamcrest matchers from!");
Expand Down

0 comments on commit c80ae40

Please sign in to comment.