1 /* 2 * * Copyright 2022 Google LLC. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the License); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package kapt 18 19 import com.google.auto.service.AutoService 20 import java.io.IOException 21 import java.io.UncheckedIOException 22 import java.nio.charset.StandardCharsets.UTF_8 23 import java.nio.file.Files 24 import java.nio.file.Paths 25 import javax.annotation.processing.AbstractProcessor 26 import javax.annotation.processing.Processor 27 import javax.annotation.processing.RoundEnvironment 28 import javax.annotation.processing.SupportedAnnotationTypes 29 import javax.lang.model.SourceVersion 30 import javax.lang.model.element.TypeElement 31 32 /** Annotation processor to test `data` dependencies specified with [MakeHelper] annotations. */ 33 @AutoService(Processor::class) 34 @SupportedAnnotationTypes("*") 35 internal class ProcessorWithData : AbstractProcessor() { 36 37 private val template: String = 38 Files.readString( 39 Paths.get( 40 "tests/jvm/java/kapt/MakeHelperClass.java.template" 41 ), 42 UTF_8 43 ) 44 getSupportedSourceVersionnull45 override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latestSupported() 46 47 override fun process( 48 annotations: Set<TypeElement>, 49 roundEnv: RoundEnvironment, 50 ): Boolean { 51 for (element in roundEnv.getElementsAnnotatedWith(MakeHelper::class.java)) { 52 val c = element.getAnnotation(MakeHelper::class.java) 53 if (c.value.isNotEmpty()) { 54 try { 55 processingEnv.filer.createSourceFile(c.value, element).openWriter().use { 56 it.write(template.replace("|name|", c.value.substring(c.value.lastIndexOf(".") + 1))) 57 } 58 } catch (e: IOException) { 59 throw UncheckedIOException(e) 60 } 61 } 62 } 63 return false 64 } 65 } 66