@SuppressWarnings("unchecked") static <T> T fromStream(Class<T> clazz, InputStream stream) { try (ObjectInputStream objectInput = new ObjectInputStream(stream)) { T object = (T) objectInput.readObject(); Preconditions.checkArgument(clazz.isInstance(object), "Requires class %s, was %s", clazz, object); return object; } catch (ClassNotFoundException | IOException e) { throw Errors.asRuntime(e); } } }
static void toStream(Serializable obj, OutputStream stream) { try (ObjectOutputStream objectOutput = new ObjectOutputStream(stream)) { objectOutput.writeObject(obj); } catch (IOException e) { throw Errors.asRuntime(e); } }
public Builder problemFiles(List<File> problemFiles) { this.problemFiles = Objects.requireNonNull(problemFiles); Preconditions.checkArgument(!problemFiles.isEmpty(), "cannot be empty"); return this; }
private void taskRanAgainst(String task, String... ranAgainst) throws IOException { pauseForFilesystem(); String console = StringPrinter.buildString(Errors.rethrow().wrap(printer -> { boolean expectFailure = task.equals("spotlessCheck") && !isClean(); if (expectFailure) { gradleRunner().withArguments(task).forwardStdOutput(printer.toWriter()).buildAndFail(); } else { gradleRunner().withArguments(task).forwardStdOutput(printer.toWriter()).build(); } })); SortedSet<String> added = new TreeSet<>(); for (String line : console.split("\n")) { String trimmed = line.trim(); if (trimmed.startsWith("<") && trimmed.endsWith(">")) { added.add(trimmed.substring(1, trimmed.length() - 1)); } } Assert.assertEquals(concat(Arrays.asList(ranAgainst)), concat(added)); }
private void assertResultAndMessages(BuildResult result, TaskOutcome outcome, String... messages) { String expectedToStartWith = StringPrinter.buildStringFromLines(messages).trim(); int numNewlines = CharMatcher.is('\n').countIn(expectedToStartWith); List<String> actualLines = Splitter.on('\n').splitToList(LineEnding.toUnix(result.getOutput())); String actualStart = String.join("\n", actualLines.subList(0, numNewlines + 1)); Assertions.assertThat(actualStart).isEqualTo(expectedToStartWith); Assertions.assertThat(result.tasks(outcome).size() + result.tasks(TaskOutcome.UP_TO_DATE).size()) .isEqualTo(result.getTasks().size()); } }
static String buildResultToString(BuildResult result) { return StringPrinter.buildString(printer -> { for (BuildTask task : result.getTasks()) { printer.println(task.getPath() + " " + task.getOutcome()); } }); } }
private void assertFailureMessage(Bundle bundle, String... expectedOutput) { String msg = bundle.checkFailureMsg(); String expected = StringPrinter.buildStringFromLines(expectedOutput).trim(); Assert.assertEquals(expected, msg); } }
/** Runs against the `spotlessSelfApply.gradle` file. */ static void runWithTestKit(Type type) throws Exception { GradleRunner.create() .withPluginClasspath() .withProjectDir(new File(StandardSystemProperty.USER_DIR.value()).getParentFile()) .withArguments( "--build-file", "spotlessSelf.gradle", "--project-cache-dir", ".gradle-selfapply", "spotless" + type.checkApply("Check", "Apply"), "--stacktrace") .forwardOutput() .build(); } }
public File locateFile(String path) { if (isNullOrEmpty(path)) { return null; } String outputFile = tmpOutputFileName(path); try { return resourceManager.getResourceAsFile(path, outputFile); } catch (ResourceNotFoundException e) { throw new RuntimeException("Unable to locate file with path: " + path, e); } catch (FileResourceCreationException e) { throw new RuntimeException("Unable to create temporaty file '" + outputFile + "' in the output directory", e); } }
@Override public void run() { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteStreams.copy(input, output); result = output.toString(Charset.defaultCharset().name()); } catch (Exception e) { result = Throwables.getStackTraceAsString(e); } }
private static byte[] toByteArray(InputStream in) { ByteArrayOutputStream to = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; try { while (true) { int r = in.read(buf); if (r == -1) { break; } to.write(buf, 0, r); } return to.toByteArray(); } catch (IOException e) { throw Errors.asRuntime(e); } }
@Override public void runAllTasks(Project project) { project.getTasks().stream() .filter(task -> task instanceof SpotlessTask) .map(task -> (SpotlessTask) task) .forEach(task -> Errors.rethrow().run(() -> { IncrementalTaskInputs inputs = Mocks.mockIncrementalTaskInputs(task.getTarget()); task.setCheck(); task.performAction(inputs); })); }
private void assertTaskFailure(SpotlessTask task, String... expectedLines) throws Exception { String msg = getTaskErrorMessage(task); String firstLine = "The following files had format violations:\n"; String lastLine = "\nRun 'gradlew spotlessApply' to fix these violations."; Assertions.assertThat(msg).startsWith(firstLine).endsWith(lastLine); String middle = msg.substring(firstLine.length(), msg.length() - lastLine.length()); String expectedMessage = StringPrinter.buildStringFromLines(expectedLines); Assertions.assertThat(middle).isEqualTo(expectedMessage.substring(0, expectedMessage.length() - 1)); }
private static String getSystemProperty(String name) { String value = System.getProperty(name); if (isNullOrEmpty(value)) { fail("System property '" + name + "' is not defined"); } return value; }
/** Returns the error message. */ public String getMessage() { try { Objects.requireNonNull(runToFix, "runToFix"); Objects.requireNonNull(formatter, "formatter"); Objects.requireNonNull(problemFiles, "problemFiles"); DiffMessageFormatter diffFormater = new DiffMessageFormatter(this); return "The following files had format violations:\n" + diffFormater.buffer + runToFix; } catch (IOException e) { throw Errors.asRuntime(e); } }
@Override public void runAllTasks(Project project) { project.getTasks().stream() .filter(task -> task instanceof SpotlessTask) .map(task -> (SpotlessTask) task) .forEach(task -> Errors.rethrow().run(() -> { IncrementalTaskInputs inputs = Mocks.mockIncrementalTaskInputs(task.getTarget()); task.setApply(); task.performAction(inputs); })); }
private void fixWindowsBugTestcase(String... lines) { String input = StringPrinter.buildStringFromLines(lines); Assert.assertEquals(input, GoogleJavaFormatStep.fixWindowsBug(input, "1.1")); } }
/** * Load class based on the given configuration of JAR provider and Maven coordinates. * Different class loader instances are provided in the following scenarios: * <ol> * <li>The JARs ({@link #jarState}) have changes (this should only occur during development)</li> * <li>Different configurations ({@link #settingsFiles}) are used for different sub-projects</li> * <li>The same Eclipse step implementation provides different formatter types ({@link #formatterStepExt})</li> * </ol> */ public Class<?> loadClass(String name) { try { return jarState.getClassLoader(this).loadClass(name); } catch (ClassNotFoundException e) { throw Errors.asRuntime(e); } } }
static <T extends Serializable> T fromFile(Class<T> clazz, File file) { try (InputStream input = Files.asByteSource(file).openBufferedStream()) { return fromStream(clazz, input); } catch (IOException e) { throw Errors.asRuntime(e); } }