/*
 * Copyright (C) 2020 The Dagger Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package dagger.testing.compile;

import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.collect.Streams.stream;
import static com.google.testing.compile.Compiler.javac;

import com.google.common.collect.ImmutableList;
import com.google.common.io.Files;
import com.google.testing.compile.Compiler;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

/**
 * A helper class for working with java compiler tests.
 */
public final class CompilerTests {
  private CompilerTests() {}

  /** Returns the {@plainlink File jar file} containing the compiler deps. */
  public static File compilerDepsJar() {
    return stream(Files.fileTraverser().breadthFirst(getRunfilesDir()))
        .filter(file -> file.getName().endsWith("_compiler_deps_deploy.jar"))
        .collect(onlyElement());
  }

  /** Returns a {@link Compiler} with the compiler deps jar added to the class path. */
  public static Compiler compiler() {
    return javac().withClasspath(ImmutableList.of(compilerDepsJar()));
  }

  private static File getRunfilesDir() {
    return getRunfilesPath().toFile();
  }

  private static Path getRunfilesPath() {
    Path propPath = getRunfilesPath(System.getProperties());
    if (propPath != null) {
      return propPath;
    }

    Path envPath = getRunfilesPath(System.getenv());
    if (envPath != null) {
      return envPath;
    }

    Path cwd = Paths.get("").toAbsolutePath();
    return cwd.getParent();
  }

  private static Path getRunfilesPath(Map<?, ?> map) {
    String runfilesPath = (String) map.get("TEST_SRCDIR");
    return isNullOrEmpty(runfilesPath) ? null : Paths.get(runfilesPath);
  }
}

@@ -1096,16 +1096,57 @@
 til.Map;
+%0Aimport java.util.NoSuchElementException;
 %0A%0A/**%0A *
@@ -1383,24 +1383,36 @@
 DepsJar() %7B%0A
+    try %7B%0A  
     return s
@@ -1479,16 +1479,18 @@
         
+ 
+ 
 .filter(
@@ -1559,16 +1559,18 @@
         
+  
 .collect
@@ -1582,24 +1582,201 @@
 Element());%0A
+    %7D catch (NoSuchElementException e) %7B%0A      throw new IllegalStateException(%0A          %22No compiler deps jar found. Are you using the Dagger compiler_test macro?%22, e);%0A    %7D%0A
   %7D%0A%0A  /** R

Add better error message when the compiler deps jar isn't found.