|
| 1 | +package dev.arbjerg.lavalink.processor; |
| 2 | + |
| 3 | +import javax.annotation.processing.*; |
| 4 | +import javax.lang.model.SourceVersion; |
| 5 | +import javax.lang.model.element.ElementKind; |
| 6 | +import javax.lang.model.element.TypeElement; |
| 7 | +import javax.tools.Diagnostic.Kind; |
| 8 | +import javax.tools.StandardLocation; |
| 9 | +import java.io.BufferedWriter; |
| 10 | +import java.io.IOException; |
| 11 | +import java.util.ArrayList; |
| 12 | +import java.util.List; |
| 13 | +import java.util.Set; |
| 14 | + |
| 15 | +@SupportedSourceVersion(SourceVersion.RELEASE_17) |
| 16 | +@SupportedAnnotationTypes(LavalinkAnnotationProcessor.SPRING_CONFIGURATION) |
| 17 | +public class LavalinkAnnotationProcessor extends AbstractProcessor { |
| 18 | + |
| 19 | + public static final String SPRING_CONFIGURATION = "org.springframework.context.annotation.Configuration"; |
| 20 | + private TypeElement springConfigurationElement; |
| 21 | + private final List<CharSequence> configurationClasses = new ArrayList<>(); |
| 22 | + |
| 23 | + @Override |
| 24 | + public synchronized void init(final ProcessingEnvironment processingEnv) { |
| 25 | + springConfigurationElement = processingEnv.getElementUtils().getTypeElement(SPRING_CONFIGURATION); |
| 26 | + super.init(processingEnv); |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) { |
| 31 | + if (roundEnv.processingOver()) { |
| 32 | + writeStorage(); |
| 33 | + return false; |
| 34 | + } |
| 35 | + var newConfigurations = roundEnv.getElementsAnnotatedWith(springConfigurationElement) |
| 36 | + .stream() |
| 37 | + .filter(element -> element.getKind() == ElementKind.CLASS) |
| 38 | + .map(clazz -> processingEnv.getElementUtils().getBinaryName((TypeElement) clazz)) |
| 39 | + .toList(); |
| 40 | + processingEnv.getMessager().printMessage(Kind.NOTE, "Found the following new configurations: " + newConfigurations); |
| 41 | + configurationClasses.addAll(newConfigurations); |
| 42 | + return false; |
| 43 | + } |
| 44 | + |
| 45 | + private void writeStorage() { |
| 46 | + try (var resource = new BufferedWriter(processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/configurations.idx").openWriter())) { |
| 47 | + for (CharSequence className : configurationClasses) { |
| 48 | + resource.write(className.toString()); |
| 49 | + resource.newLine(); |
| 50 | + } |
| 51 | + } catch (IOException e) { |
| 52 | + processingEnv.getMessager().printMessage(Kind.ERROR, e.getMessage()); |
| 53 | + throw new RuntimeException(e); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments