aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/java_tools/buildjar/java
diff options
context:
space:
mode:
authorGravatar Lukacs Berki <lberki@google.com>2016-01-19 12:31:46 +0000
committerGravatar Lukacs Berki <lberki@google.com>2016-01-19 13:28:53 +0000
commit1903d7048a86aa0ff10e72f27e578eec30276aa9 (patch)
treef42d4dda3e165c92777fad04bfe8aef783af842a /src/java_tools/buildjar/java
parent16fd9ab1036df378511876417e3f35f6ca19cf19 (diff)
Remove javac/testing from the public tree.
It is currently unused and messes up IDEs because it requires a few dependencies that are not in the source tree (most notably, jimfs) -- MOS_MIGRATED_REVID=112461226
Diffstat (limited to 'src/java_tools/buildjar/java')
-rw-r--r--src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/BlackHoleProcessor.java41
-rw-r--r--src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/DummyAnnotationProcessor.java91
-rw-r--r--src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/ErrorProneTestHelper.java413
-rw-r--r--src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/InMemoryJavaFileManager.java246
4 files changed, 0 insertions, 791 deletions
diff --git a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/BlackHoleProcessor.java b/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/BlackHoleProcessor.java
deleted file mode 100644
index 161610ca30..0000000000
--- a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/BlackHoleProcessor.java
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2015 The Bazel Authors. All rights reserved.
-//
-// 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 com.google.devtools.build.buildjar.javac.testing;
-
-import java.util.Set;
-
-import javax.annotation.processing.AbstractProcessor;
-import javax.annotation.processing.RoundEnvironment;
-import javax.annotation.processing.SupportedAnnotationTypes;
-import javax.lang.model.SourceVersion;
-import javax.lang.model.element.TypeElement;
-
-/**
- * Annotation processor used for testing JavaBuilder's annotation processing phase.
- *
- * It is a universal processor that claims all annotations, potentially preventing other processors
- * from ever seeing those annotations.
- */
-@SupportedAnnotationTypes("*")
-public class BlackHoleProcessor extends AbstractProcessor {
- @Override
- public SourceVersion getSupportedSourceVersion() {
- return SourceVersion.latest();
- }
- @Override
- public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
- return true;
- }
-}
diff --git a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/DummyAnnotationProcessor.java b/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/DummyAnnotationProcessor.java
deleted file mode 100644
index 93e19ca3e3..0000000000
--- a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/DummyAnnotationProcessor.java
+++ /dev/null
@@ -1,91 +0,0 @@
-// Copyright 2015 The Bazel Authors. All rights reserved.
-//
-// 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 com.google.devtools.build.buildjar.javac.testing;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Set;
-
-import javax.annotation.processing.AbstractProcessor;
-import javax.annotation.processing.Filer;
-import javax.annotation.processing.RoundEnvironment;
-import javax.annotation.processing.SupportedAnnotationTypes;
-import javax.lang.model.SourceVersion;
-import javax.lang.model.element.TypeElement;
-import javax.tools.JavaFileObject;
-
-/**
- * Annotation processor used for testing correct propagation of factories between Contexts.
- *
- * It generates new source files for a given number of times, each source referring to the
- * next (so that compilation will fail if the generated sources aren't all included in the
- * same compilation round).
- *
- * Being a universal processor, it does not claim any annotations and {@link #process} always
- * returns {@code false}, in order to interact correctly with other annotation processors.
- */
-@SupportedAnnotationTypes("*")
-public class DummyAnnotationProcessor extends AbstractProcessor {
-
- private final int maxRounds;
- private int round;
-
- /** By default, generates a new file for one round of annotation processing. */
- public DummyAnnotationProcessor() {
- this(1);
- }
-
- /** Generates new files for given number of annotation processing rounds. */
- public DummyAnnotationProcessor(int rounds) {
- round = 0;
- this.maxRounds = rounds;
- }
-
- @Override
- public SourceVersion getSupportedSourceVersion() {
- return SourceVersion.latest();
- }
-
- @Override
- public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
- round++;
- if (round <= maxRounds) {
- String curr = "p.Gen" + round;
- String next = "p.Gen" + (round + 1);
- StringBuilder text = new StringBuilder();
- text.append("package p;\n");
- text.append("public class Gen").append(round).append(" {\n");
- if (round < maxRounds) {
- text.append(" ").append(next).append(" x;\n");
- }
- text.append("}\n");
-
- try {
- Filer filer = processingEnv.getFiler();
- JavaFileObject fo = filer.createSourceFile(curr);
- Writer out = fo.openWriter();
- try {
- out.write(text.toString());
- } finally {
- out.close();
- }
- } catch (IOException e) {
- throw new Error(e);
- }
- }
-
- return false;
- }
-}
diff --git a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/ErrorProneTestHelper.java b/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/ErrorProneTestHelper.java
deleted file mode 100644
index eb3c77611d..0000000000
--- a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/ErrorProneTestHelper.java
+++ /dev/null
@@ -1,413 +0,0 @@
-// Copyright 2015 The Bazel Authors. All rights reserved.
-//
-// 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 com.google.devtools.build.buildjar.javac.testing;
-
-import static com.google.common.base.Preconditions.checkState;
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import com.google.devtools.build.buildjar.InvalidCommandLineException;
-import com.google.devtools.build.buildjar.javac.BlazeJavacMain;
-import com.google.devtools.build.buildjar.javac.plugins.BlazeJavaCompilerPlugin;
-import com.google.devtools.build.buildjar.javac.plugins.errorprone.ErrorPronePlugin;
-import com.google.devtools.build.java.bazel.BazelJavaCompiler;
-import com.google.errorprone.ErrorProneAnalyzer;
-import com.google.errorprone.ErrorProneOptions;
-import com.google.errorprone.scanner.Scanner;
-import com.google.errorprone.scanner.ScannerSupplier;
-
-import com.sun.source.util.TaskEvent;
-import com.sun.source.util.TaskEvent.Kind;
-import com.sun.tools.javac.comp.AttrContext;
-import com.sun.tools.javac.comp.Env;
-import com.sun.tools.javac.main.JavaCompiler;
-import com.sun.tools.javac.main.Main.Result;
-import com.sun.tools.javac.util.Context;
-import com.sun.tools.javac.util.Log;
-import com.sun.tools.javac.util.Options;
-
-import org.junit.After;
-import org.junit.Before;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.regex.Pattern;
-
-import javax.tools.Diagnostic;
-import javax.tools.DiagnosticCollector;
-import javax.tools.JavaFileObject;
-
-/**
- * Helper class for testing Error Prone plugins and scanners.
- *
- * <p>
- * This class takes care of the set up of the error-prone compiler, and provides methods to perform
- * compilation and assert success/failure results.
- *
- * <p>
- * Subclasses must invoke (typically from their {@link #setUp()} method) either
- * {@link #registerPlugin(BlazeJavaCompilerPlugin)} or {@link #registerScanner(Scanner)} to install
- * the plugin or scanner to be used during compilation.
- *
- * <p>
- * Java source files are kept in memory using {@link #fileManager}, a
- * {@link InMemoryJavaFileManager}. Test cases should use
- * {@link InMemoryJavaFileManager#addSource(String, String...)} to add Java sources under test.
- */
-public abstract class ErrorProneTestHelper {
-
- private BlazeJavaCompilerPlugin registeredPlugin;
-
- private Context context;
- private BlazeJavacMain compilerMain;
- private Writer out = new StringWriter();
-
- /**
- * The file manager to used to keep Java sources under test in memory.
- *
- * <p>
- * Tests cases should use {@link InMemoryJavaFileManager#addSource(String, String...)} to add Java
- * sources under test, and should use {@link InMemoryJavaFileManager#takeAvailableSources()} to
- * obtain the collection of {@link JavaFileObject} to pass to
- * {@link #assertCompileSucceeds(java.util.List)} and {@code ...CompileFails...}.
- * Note that {@link InMemoryJavaFileManager#takeAvailableSources()} clears the file manager, and
- * should only be invoked once per test case.
- *
- * <p>
- * The file manager is initialized by this class' {@link #setUp()} method.
- */
- protected InMemoryJavaFileManager fileManager;
-
- /**
- * The diagnostics collector in which compilation results are available.
- *
- * <p>
- * After invoking compilation, tests may inspect this collector for details of compilation errors.
- *
- * <p>
- * The diagnostics collector is initialized by this class' {@link #setUp()} method.
- */
- protected DiagnosticCollector<JavaFileObject> collector;
-
- @Before
- public void setUp() throws Exception {
- registeredPlugin = null;
-
- // Order is important here, since Context can raise exceptions if setting keys twice!
- context = new Context();
- // Disables faulty Zip implementation. In the compiler this is done in BlazeJavacMain, and
- // is replicated here to align the test environment with the actual compiler.
- Options options = Options.instance(context);
- options.put("useOptimizedZip", "false");
-
- collector = new DiagnosticCollector<>();
- fileManager = new InMemoryJavaFileManager();
- compilerMain = new BlazeJavacMain(new PrintWriter(out, true),
- ImmutableList.<BlazeJavaCompilerPlugin>of());
- }
-
- @After
- public void tearDown() throws Exception {
- fileManager.close();
- }
-
- protected void registerPlugin(BlazeJavaCompilerPlugin plugin) {
- registeredPlugin = plugin;
- compilerMain.preRegister(context, Arrays.asList(plugin));
- }
-
- protected void registerScanner(ScannerSupplier supplier) {
- registerScanner(supplier.get());
- }
-
- protected void registerScanner(Scanner scanner) {
- registerPlugin(new ScannerPlugin(scanner));
- }
-
- protected String getOutput() {
- return out.toString();
- }
-
- protected Result doCompile(List<JavaFileObject> sources) {
- return doCompile(new String[]{}, sources);
- }
-
- protected Result doCompile(String[] args, List<JavaFileObject> sources) {
- assertNotNull("Tests must register a plugin or scanner before compilation", registeredPlugin);
- List<String> argList = new ArrayList<>(BazelJavaCompiler.getDefaultJavacopts());
- argList.addAll(Arrays.asList(args));
-
- List<String> remainingArgs = null;
- try {
- remainingArgs = registeredPlugin.processArgs(argList);
- } catch (InvalidCommandLineException e) {
- fail("Invalid command line argument: " + e.getMessage());
- }
- fileManager.initializeClasspath(ImmutableList.<Path>of());
- return compilerMain.compile(remainingArgs.toArray(new String[remainingArgs.size()]), context,
- fileManager, collector, sources, null);
- }
-
- protected List<Diagnostic<? extends JavaFileObject>> assertCompileSucceeds(
- List<JavaFileObject> sources) {
- return assertCompileSucceeds(sources, new String[] {});
- }
-
- protected List<Diagnostic<? extends JavaFileObject>> assertCompileSucceeds(
- List<JavaFileObject> sources, String[] args) {
- Result compilerReturnCode = doCompile(args, sources);
- assertEquals(getOutput(), Result.OK, compilerReturnCode);
- return collector.getDiagnostics();
- }
-
- protected void assertCompileSucceedsWithoutWarnings(List<JavaFileObject> sources) {
- List<Diagnostic<? extends JavaFileObject>> diagnostics = assertCompileSucceeds(sources);
- assertThat(diagnostics).isEmpty();
- }
-
- /**
- * Compiles the given sources and asserts that the compile succeeds with exactly one warning,
- * with an error message that contains a substring that matches the given regex, and at the
- * specified exact source line and column.
- */
- protected void assertCompileSucceedsWithOnlyWarningContaining(
- List<JavaFileObject> sources, String expectedErrorRegex, int line, int col) {
- // TODO(bazel-team): remove column from this check
- List<Diagnostic<? extends JavaFileObject>> diagnostics = assertCompileSucceeds(sources);
-
- assertThat(diagnostics).named("diagnostics").hasSize(1);
- Diagnostic<? extends JavaFileObject> diagnostic = diagnostics.get(0);
- assertWithMessage("Wrong warning")
- .that(diagnostic.getMessage(null))
- .containsMatch(expectedErrorRegex);
- assertEquals("Wrong line number", line, diagnostic.getLineNumber());
- assertEquals("Wrong column number", col, diagnostic.getColumnNumber());
- }
-
- /**
- * Compiles the given sources and asserts that the compile succeeds and contains a warning
- * with an error message that contains a substring that matches the given regex, and at the
- * specified exact source line and column.
- */
- protected void assertCompileSucceedsWithWarningContaining(
- List<JavaFileObject> sources, String expectedErrorRegex, int line, int col) {
- // TODO(bazel-team): remove column from this check
- List<Diagnostic<? extends JavaFileObject>> diagnostics = assertCompileSucceeds(sources);
-
- assertThat(diagnostics).named("diagnostics").isNotEmpty();
- Diagnostic<? extends JavaFileObject> closeMatch =
- findClosestMatch(diagnostics, expectedErrorRegex, line, col);
-
- assertNotNull("Did not find expected warning", closeMatch);
- assertEquals("Wrong line number", line, closeMatch.getLineNumber());
- assertEquals("Wrong column number", col, closeMatch.getColumnNumber());
- }
-
- /**
- * Returns a diagnostic that matches the regex. If one with the matching line
- * and column is found, returns that one, otherwise anything that matches the
- * regex. If no regex match is found, returns null.
- */
- private Diagnostic<? extends JavaFileObject> findClosestMatch(
- List<Diagnostic<? extends JavaFileObject>> diagnostics,
- String regex, int line, int col) {
- // TODO(bazel-team): remove column from this check
- Diagnostic<? extends JavaFileObject> closeMatch = null;
- Pattern pattern = Pattern.compile(regex);
-
- for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
- if (pattern.matcher(diagnostic.getMessage(null)).matches()) {
- if (line == diagnostic.getLineNumber() && col == diagnostic.getColumnNumber()) {
- return diagnostic;
- } else {
- closeMatch = diagnostic;
- }
- }
- }
- return closeMatch;
- }
-
- /**
- * Compiles the given sources and asserts that the compile succeeds and contains no warnings
- * that match the expected regex.
- */
- protected void assertCompileSucceedsWithoutWarningContaining(
- List<JavaFileObject> sources, String expectedErrorRegex) {
- List<Diagnostic<? extends JavaFileObject>> diagnostics = assertCompileSucceeds(sources);
-
- for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
- assertWithMessage("Should not contain this warning")
- .that(diagnostic.getMessage(null))
- .doesNotContainMatch(expectedErrorRegex);
- }
- }
-
- /**
- * Compiles the given sources and asserts that the compile fails.
- *
- * @param sources the sources to compile
- * @return the resulting diagnostics, for further inspection
- */
- protected List<Diagnostic<? extends JavaFileObject>> assertCompileFails(
- List<JavaFileObject> sources) {
- return assertCompileFails(new String[]{}, sources);
- }
-
- protected List<Diagnostic<? extends JavaFileObject>> assertCompileFails(
- String[] args, List<JavaFileObject> sources) {
- Result compilerReturnCode = doCompile(args, sources);
- assertEquals(getOutput(), Result.ERROR, compilerReturnCode);
- return collector.getDiagnostics();
- }
-
- /**
- * Compiles the given sources and asserts that the compile fails with exactly one compile error.
- *
- * @param sources the sources to compile
- * @return the resulting diagnostics, for further inspection
- */
- protected List<Diagnostic<? extends JavaFileObject>> assertCompileFailsWithOneError(
- List<JavaFileObject> sources) {
- return assertCompileFailsWithOneError(new String[]{}, sources);
- }
-
- protected List<Diagnostic<? extends JavaFileObject>> assertCompileFailsWithOneError(
- String[] args, List<JavaFileObject> sources) {
- List<Diagnostic<? extends JavaFileObject>> diagnostics = assertCompileFails(args, sources);
- assertEquals("Expected 1 compiler message, found " + diagnostics.size() + ": " + diagnostics, 1,
- diagnostics.size());
- return diagnostics;
- }
-
- /**
- * Compiles the given sources and asserts that the compile fails with exactly one compile error,
- * which must contain the expected message as a substring.
- */
- protected void assertCompileFailsWithErrorContaining(
- List<JavaFileObject> sources, String errorMsg) {
- assertCompileFailsWithErrorContaining(new String[] {}, sources, errorMsg);
- }
-
- protected void assertCompileFailsWithErrorContaining(
- String[] args, List<JavaFileObject> sources, String errorMsg) {
- List<Diagnostic<? extends JavaFileObject>> diagnostics =
- assertCompileFailsWithOneError(args, sources);
-
- assertTrue("Error message should contain " + errorMsg + ", was: "
- + diagnostics.get(0).getMessage(null),
- diagnostics.get(0).getMessage(null).contains(errorMsg));
- }
-
- /**
- * Compiles the given sources and asserts that the compile fails with exactly one compile error,
- * with a specific, exact error message, and at the specified exact source line and column.
- */
- protected void assertCompileFailsWithError(List<JavaFileObject> sources,
- String expectedError, int line, int col) {
- List<Diagnostic<? extends JavaFileObject>> diagnostics =
- assertCompileFailsWithOneError(sources);
-
- Diagnostic<? extends JavaFileObject> diagnostic = diagnostics.get(0);
- assertEquals("Wrong error message", expectedError, diagnostic.getMessage(null));
- assertEquals("Wrong line number", line, diagnostic.getLineNumber());
- assertEquals("Wrong column number", col, diagnostic.getColumnNumber());
- }
-
- /**
- * Compiles the given sources and asserts that the compile fails with exactly one compile error,
- * with an error message that matches the given regex, and at the specified exact source line and
- * column.
- */
- protected void assertCompileFailsWithErrorMatching(
- List<JavaFileObject> sources, String expectedErrorRegex, int line, int col) {
- List<Diagnostic<? extends JavaFileObject>> diagnostics =
- assertCompileFailsWithOneError(sources);
-
- Diagnostic<? extends JavaFileObject> diagnostic = diagnostics.get(0);
- assertWithMessage("Wrong error message")
- .that(diagnostic.getMessage(null))
- .matches(expectedErrorRegex);
- assertEquals("Wrong line number", line, diagnostic.getLineNumber());
- assertEquals("Wrong column number", col, diagnostic.getColumnNumber());
- }
-
- /**
- * Compiles the given sources and asserts that the compile fails with exactly one compile error,
- * with an error message that contains a substring that matches the given regex, and at the
- * specified exact source line and column.
- */
- protected void assertCompileFailsWithErrorContaining(
- List<JavaFileObject> sources, String expectedErrorRegex, int line, int col) {
- List<Diagnostic<? extends JavaFileObject>> diagnostics =
- assertCompileFailsWithOneError(sources);
-
- Diagnostic<? extends JavaFileObject> diagnostic = diagnostics.get(0);
- assertWithMessage("Wrong error message")
- .that(diagnostic.getMessage(null))
- .containsMatch(expectedErrorRegex);
- assertEquals("Wrong line number", line, diagnostic.getLineNumber());
- assertEquals("Wrong column number", col, diagnostic.getColumnNumber());
- }
-
- /**
- * A slightly stripped down version of ErrorPronePlugin, hard-wired to use a specific
- * {@link Scanner}.
- *
- * <p>
- * This plugin is installed by {@link ErrorProneTestHelper#registerScanner(Scanner)}, and is
- * intended to be used by unit tests of a specific scanner (as opposed to ErrorProneScanner).
- */
- private final class ScannerPlugin extends BlazeJavaCompilerPlugin {
-
- private final Scanner scanner;
-
- private boolean isInitialized = false;
- private ErrorProneAnalyzer errorProneAnalyzer;
-
- ScannerPlugin(Scanner scanner) {
- this.scanner = scanner;
- }
-
- @Override
- public void init(Context context, Log log, JavaCompiler compiler) {
- Preconditions.checkState(!isInitialized);
- super.init(context, log, compiler);
- ErrorPronePlugin.setupMessageBundle(context);
- errorProneAnalyzer =
- ErrorProneAnalyzer.create(scanner).init(context, ErrorProneOptions.empty());
- isInitialized = true;
- }
-
- /**
- * Run Error Prone analysis after performing dataflow checks.
- */
- @Override
- public void postFlow(Env<AttrContext> env) {
- checkState(isInitialized);
- errorProneAnalyzer.finished(new TaskEvent(Kind.ANALYZE, env.toplevel, env.enclClass.sym));
- }
- }
-}
diff --git a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/InMemoryJavaFileManager.java b/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/InMemoryJavaFileManager.java
deleted file mode 100644
index 79fea3d555..0000000000
--- a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/testing/InMemoryJavaFileManager.java
+++ /dev/null
@@ -1,246 +0,0 @@
-// Copyright 2015 The Bazel Authors. All rights reserved.
-//
-// 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 com.google.devtools.build.buildjar.javac.testing;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static java.util.Locale.ENGLISH;
-
-import com.google.auto.value.AutoValue;
-import com.google.common.base.CharMatcher;
-import com.google.common.collect.ImmutableList;
-import com.google.common.jimfs.Configuration;
-import com.google.common.jimfs.Jimfs;
-
-import com.sun.tools.javac.nio.JavacPathFileManager;
-import com.sun.tools.javac.util.Context;
-import com.sun.tools.javac.util.Log;
-
-import java.io.IOError;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.nio.file.FileSystem;
-import java.nio.file.FileVisitResult;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.SimpleFileVisitor;
-import java.nio.file.attribute.BasicFileAttributes;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Locale;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import javax.tools.JavaFileObject;
-import javax.tools.StandardLocation;
-
-/**
- * An in memory file manager based on {@link JavacPathFileManager} and Jimfs, with utilities for
- * creating Java source files and manipulating compiled classes.
- */
-@com.sun.tools.javac.api.ClientCodeWrapper.Trusted
-public class InMemoryJavaFileManager extends JavacPathFileManager {
-
- protected static final CharMatcher SLASH_MATCHER = CharMatcher.is('/');
- protected static final CharMatcher DOT_MATCHER = CharMatcher.is('.');
-
- private FileSystem fileSystem;
- private final List<Path> sources = new ArrayList<>();
-
- // Upstream may eventually create a {@code JavaCompiler#getPathFileManager()} that we could
- // use instead. (See implementation comment on {@link PathFileManager}.))
- private static Context makeContext() {
- Context context = new Context();
- context.put(Locale.class, ENGLISH);
- context.put(Log.outKey, new PrintWriter(new OutputStreamWriter(System.err, UTF_8), true));
- return context;
- }
-
- public InMemoryJavaFileManager() {
- super(makeContext(), false, UTF_8);
- this.fileSystem = Jimfs.newFileSystem(Configuration.unix());
- setDefaultFileSystem(fileSystem);
- }
-
- /**
- * Creates an in-memory Jar from all compiled classes from package pkg.
- *
- * @param pkg name of package
- * @param compiled a list of classes and their compiled bytecode to include in the jar
- * @return the name of the constructed jar
- */
- public Path makeJarInClasspath(String pkg, List<CompiledClass> compiled) {
- try {
- String jarName = "lib" + pkg.replace(".", "") + ".jar";
- Path jarPath = fileSystem.getPath("/" + jarName);
- try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(jarPath))) {
- for (CompiledClass compiledClass : compiled) {
- if (pkg.equals(getPackageName(compiledClass.name()))) {
- String entry = DOT_MATCHER.replaceFrom(compiledClass.name(), '/') + ".class";
- out.putNextEntry(new ZipEntry(entry));
- out.write(compiledClass.data());
- }
- }
- }
- return jarPath;
- } catch (IOException e) {
- throw new IOError(e);
- }
- }
-
- /**
- * Creates an in-memory Java source file with the specified name and content.
- *
- * @param className the fully-qualified class name
- * @param lines Java source code
- */
- public void addSource(String className, String... lines) {
- Path path = fileSystem.getPath(
- "/", SLASH_MATCHER.trimLeadingFrom(DOT_MATCHER.replaceFrom(className, '/') + ".java"));
- try {
- Files.createDirectories(path.getParent());
- Files.write(path, Arrays.asList(lines), UTF_8);
- } catch (IOException e) {
- throw new IOError(e);
- }
- sources.add(path);
- }
-
- /**
- * Gets a list of available Java sources and clears the fileManager's cache.
- *
- * @return a list of the JavaFileObjects holding the source files
- */
- public List<JavaFileObject> takeAvailableSources() {
- try {
- return ImmutableList.copyOf(getJavaFileObjectsFromPaths(sources));
- } finally {
- sources.clear();
- }
- }
-
- /**
- * Copy the given JavaFileObjects into the current file manager's filesystem.
- *
- * <p>The previous implementation allowed {@link JavaFileObject}s to be passed between file
- * managers.
- */
- // TODO(cushon): consider making this class return a wrapper around the content of source files
- // other than JavaFileObjects, and then materialize them later.
- public List<JavaFileObject> naturalize(
- JavacPathFileManager external, Iterable<JavaFileObject> externalFileObjects) {
- ImmutableList.Builder<JavaFileObject> result = ImmutableList.builder();
- for (JavaFileObject externalFileObject : externalFileObjects) {
- try {
- Path externalPath = external.getPath(externalFileObject);
- Path dest = fileSystem.getPath(externalPath.toString());
- Files.createDirectories(dest.getParent());
- Files.copy(external.getPath(externalFileObject), dest);
- result.addAll(getJavaFileObjects(dest));
- } catch (IOException e) {
- throw new IOError(e);
- }
- }
- return result.build();
- }
-
- /**
- * The name and bytecode of a compiled class.
- */
- @AutoValue
- public abstract static class CompiledClass {
- public abstract String name();
- @SuppressWarnings("mutable")
- public abstract byte[] data();
-
- public static CompiledClass create(String name, byte[] data) {
- return new AutoValue_InMemoryJavaFileManager_CompiledClass(name, data);
- }
- }
-
- /**
- * Return the list of all compiled classes in the filesystem.
- */
- public List<CompiledClass> getCompiledClasses() {
- final ImmutableList.Builder<CompiledClass> result = ImmutableList.builder();
- try {
- Files.walkFileTree(fileSystem.getPath("/"), new SimpleFileVisitor<Path>() {
- @Override
- public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs)
- throws IOException {
- if (filePath.toString().endsWith(".class")) {
- String className = filePath.toString();
- className = className.substring(0, className.length() - ".class".length());
- className = DOT_MATCHER.trimLeadingFrom(SLASH_MATCHER.replaceFrom(className, '.'));
- result.add(CompiledClass.create(className, Files.readAllBytes(filePath)));
- }
- return FileVisitResult.CONTINUE;
- }
- });
- } catch (IOException e) {
- throw new IOError(e);
- }
- return result.build();
- }
-
- /**
- * Returns the package name for a fully-qualified classname, or the empty string.
- */
- // TODO(cushon): this doesn't work for nested classes.
- public static String getPackageName(String className) {
- int dot = className.lastIndexOf('.');
- return (dot > 0) ? className.substring(0, dot) : "";
- }
-
- /**
- * Create a plausible looking target name from a package name, for testing.
- */
- public static String getTargetName(String pkg) {
- return "//com/google/" + pkg.replace('.', '/');
- }
-
- /**
- * Set the filemanager's classpath for a compilation. Also explicitly sets the sourcepath and
- * processorpath to empty, since the default behaviour searches for processors and additional
- * sources to compile.
- *
- * <p>We don't rely on the command-line flags, since filemanager flag parsing doesn't work when
- * using javac through the API.
- */
- public void initializeClasspath(Iterable<Path> classpath) {
- try {
- setLocation(StandardLocation.CLASS_PATH, classpath);
- setLocation(StandardLocation.SOURCE_PATH, ImmutableList.<Path>of());
- setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH, ImmutableList.<Path>of());
- } catch (IOException e) {
- throw new IOError(e);
- }
- }
-
- /**
- * Set the filemanager's bootclasspath for a compilation.
- *
- * <p>We don't rely on the command-line flags, since filemanager flag parsing doesn't work when
- * using javac through the API.
- */
- public void initializeBootClasspath(Iterable<Path> bootClasspath) {
- try {
- setLocation(StandardLocation.PLATFORM_CLASS_PATH, bootClasspath);
- } catch (IOException e) {
- throw new IOError(e);
- }
- }
-}