1 /* 2 * Copyright (C) 2020 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.testing.compile; 18 19 import static com.google.common.base.Strings.isNullOrEmpty; 20 import static com.google.common.collect.MoreCollectors.onlyElement; 21 import static com.google.common.collect.Streams.stream; 22 import static com.google.testing.compile.Compiler.javac; 23 24 import com.google.common.collect.ImmutableList; 25 import com.google.common.io.Files; 26 import com.google.testing.compile.Compiler; 27 import java.io.File; 28 import java.nio.file.Path; 29 import java.nio.file.Paths; 30 import java.util.Map; 31 import java.util.NoSuchElementException; 32 33 /** 34 * A helper class for working with java compiler tests. 35 */ 36 public final class CompilerTests { CompilerTests()37 private CompilerTests() {} 38 39 /** Returns the {@plainlink File jar file} containing the compiler deps. */ compilerDepsJar()40 public static File compilerDepsJar() { 41 try { 42 return stream(Files.fileTraverser().breadthFirst(getRunfilesDir())) 43 .filter(file -> file.getName().endsWith("_compiler_deps_deploy.jar")) 44 .collect(onlyElement()); 45 } catch (NoSuchElementException e) { 46 throw new IllegalStateException( 47 "No compiler deps jar found. Are you using the Dagger compiler_test macro?", e); 48 } 49 } 50 51 /** Returns a {@link Compiler} with the compiler deps jar added to the class path. */ compiler()52 public static Compiler compiler() { 53 return javac().withClasspath(ImmutableList.of(compilerDepsJar())); 54 } 55 getRunfilesDir()56 private static File getRunfilesDir() { 57 return getRunfilesPath().toFile(); 58 } 59 getRunfilesPath()60 private static Path getRunfilesPath() { 61 Path propPath = getRunfilesPath(System.getProperties()); 62 if (propPath != null) { 63 return propPath; 64 } 65 66 Path envPath = getRunfilesPath(System.getenv()); 67 if (envPath != null) { 68 return envPath; 69 } 70 71 Path cwd = Paths.get("").toAbsolutePath(); 72 return cwd.getParent(); 73 } 74 getRunfilesPath(Map<?, ?> map)75 private static Path getRunfilesPath(Map<?, ?> map) { 76 String runfilesPath = (String) map.get("TEST_SRCDIR"); 77 return isNullOrEmpty(runfilesPath) ? null : Paths.get(runfilesPath); 78 } 79 } 80