1 /* 2 * Copyright (C) 2018 The Dagger Authors. 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 dagger.internal.codegen; 18 19 import com.google.common.base.Joiner; 20 import com.google.common.collect.ImmutableSet; 21 import java.io.IOException; 22 import java.io.Writer; 23 import java.util.Set; 24 import javax.annotation.processing.AbstractProcessor; 25 import javax.annotation.processing.Processor; 26 import javax.annotation.processing.RoundEnvironment; 27 import javax.lang.model.SourceVersion; 28 import javax.lang.model.element.TypeElement; 29 30 /** A simple {@link Processor} that generates one source file. */ 31 final class GeneratingProcessor extends AbstractProcessor { 32 private final String generatedClassName; 33 private final String generatedSource; 34 private boolean processed; 35 GeneratingProcessor(String generatedClassName, String... source)36 GeneratingProcessor(String generatedClassName, String... source) { 37 this.generatedClassName = generatedClassName; 38 this.generatedSource = Joiner.on("\n").join(source); 39 } 40 41 @Override getSupportedSourceVersion()42 public SourceVersion getSupportedSourceVersion() { 43 return SourceVersion.latestSupported(); 44 } 45 46 @Override getSupportedAnnotationTypes()47 public Set<String> getSupportedAnnotationTypes() { 48 return ImmutableSet.of("*"); 49 } 50 51 @Override process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv)52 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { 53 if (!processed) { 54 processed = true; 55 try (Writer writer = 56 processingEnv.getFiler().createSourceFile(generatedClassName).openWriter()) { 57 writer.append(generatedSource); 58 } catch (IOException e) { 59 throw new RuntimeException(e); 60 } 61 } 62 return false; 63 } 64 } 65