|
| 1 | +package io.avaje.inject.generator; |
| 2 | + |
| 3 | +import javax.lang.model.element.ModuleElement; |
| 4 | +import java.io.IOException; |
| 5 | +import java.nio.file.Files; |
| 6 | +import java.nio.file.StandardOpenOption; |
| 7 | + |
| 8 | +final class PomPluginWriter { |
| 9 | + |
| 10 | + private static final String plugin = |
| 11 | + " <!-- generated by avaje inject -->\n" |
| 12 | + + " <plugin>\n" |
| 13 | + + " <groupId>io.avaje</groupId>\n" |
| 14 | + + " <artifactId>avaje-inject-maven-plugin</artifactId>\n" |
| 15 | + + " <version>%s</version>\n" |
| 16 | + + " <executions>\n" |
| 17 | + + " <execution>\n" |
| 18 | + + " <phase>process-sources</phase>\n" |
| 19 | + + " <goals>\n" |
| 20 | + + " <goal>provides</goal>\n" |
| 21 | + + " </goals>\n" |
| 22 | + + " </execution>\n" |
| 23 | + + " </executions>\n" |
| 24 | + + " </plugin>\n" |
| 25 | + + " "; |
| 26 | + |
| 27 | + static void addPlugin2Pom() throws IOException { |
| 28 | + var module = APContext.getProjectModuleElement(); |
| 29 | + // don't need mvn plugin with JPMS |
| 30 | + if (disabledOrUsingModulePath(module)) { |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + var pomPath = APContext.getBuildResource("").getParent().resolve("pom.xml"); |
| 35 | + if (!pomPath.toFile().exists()) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + var pomContent = Files.readString(pomPath); |
| 40 | + // don't need mvn plugin if not using mvn compiler annotationProcessors |
| 41 | + if (pomContent.contains("avaje-inject-maven-plugin") |
| 42 | + || !pomContent.contains("<annotationProcessors>") |
| 43 | + && !pomContent.contains("<annotationProcessorPaths>")) { |
| 44 | + return; |
| 45 | + } |
| 46 | + APContext.logNote("Adding avaje-inject-maven-plugin Plugin to pom"); |
| 47 | + var pluginsIndex = pomContent.indexOf("</plugins>"); |
| 48 | + var builder = new StringBuilder(pomContent); |
| 49 | + if (pluginsIndex != -1) { |
| 50 | + builder.insert( |
| 51 | + pluginsIndex, |
| 52 | + String.format(plugin, PomPluginWriter.class.getPackage().getImplementationVersion())); |
| 53 | + |
| 54 | + Files.writeString( |
| 55 | + pomPath, builder.toString(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + private static boolean disabledOrUsingModulePath(ModuleElement module) { |
| 60 | + return !APContext.getOption("buildPlugin").map(Boolean::valueOf).orElse(true) |
| 61 | + || module != null && !module.isUnnamed(); |
| 62 | + } |
| 63 | +} |
0 commit comments