1 /* 2 * Copyright (C) 2014 Google, Inc. 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 package dagger.internal.codegen.writer; 17 18 import com.google.common.base.Function; 19 import com.google.common.collect.FluentIterable; 20 import com.google.common.collect.Lists; 21 import java.io.IOException; 22 import java.util.List; 23 import java.util.Set; 24 25 public final class BlockWriter implements Writable, HasClassReferences { 26 private final List<Snippet> snippets; 27 BlockWriter()28 BlockWriter() { 29 this.snippets = Lists.newArrayList(); 30 } 31 addSnippet(String snippet, Object... args)32 public BlockWriter addSnippet(String snippet, Object... args) { 33 snippets.add(Snippet.format(snippet, args)); 34 return this; 35 } 36 addSnippet(Snippet snippet)37 public BlockWriter addSnippet(Snippet snippet) { 38 snippets.add(snippet); 39 return this; 40 } 41 isEmpty()42 boolean isEmpty() { 43 return snippets.isEmpty(); 44 } 45 46 @Override write(Appendable appendable, Context context)47 public Appendable write(Appendable appendable, Context context) throws IOException { 48 for (Snippet snippet : snippets) { 49 appendable.append('\n'); 50 snippet.write(appendable, context); 51 } 52 return appendable.append('\n'); 53 } 54 55 @Override referencedClasses()56 public Set<ClassName> referencedClasses() { 57 return FluentIterable.from(snippets) 58 .transformAndConcat(new Function<HasClassReferences, Set<ClassName>>() { 59 @Override 60 public Set<ClassName> apply(HasClassReferences input) { 61 return input.referencedClasses(); 62 } 63 }) 64 .toSet(); 65 } 66 } 67