static String buildResultToString(BuildResult result) { return StringPrinter.buildString(printer -> { for (BuildTask task : result.getTasks()) { printer.println(task.getPath() + " " + task.getOutcome()); } }); } }
static GradleException youShouldTurnOnPaddedCell(SpotlessTask task) { Path rootPath = task.getProject().getRootDir().toPath(); return new GradleException(StringPrinter.buildStringFromLines( "You have a misbehaving rule which can't make up its mind.", "This means that spotlessCheck will fail even after spotlessApply has run.", "", "This is a bug in a formatting rule, not Spotless itself, but Spotless can", "work around this bug and generate helpful bug reports for the broken rule", "if you add 'paddedCell()' to your build.gradle as such: ", "", " spotless {", " format 'someFormat', {", " ...", " paddedCell()", " }", " }", "", "The next time you run spotlessCheck, it will put helpful bug reports into", "'" + rootPath.relativize(diagnoseDir(task).toPath()) + "', and spotlessApply", "and spotlessCheck will be self-consistent from here on out.", "", "For details see " + URL)); }
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)); }
/** Converts a list of stack trace elements to a String similar to Throwable.printStackTrace(). */ private static String stackTraceToString(List<StackTraceElement> stack) { return StringPrinter.buildString(printer -> { for (StackTraceElement element : stack) { printer.print("at "); printer.print(element.getClassName()); printer.print("."); printer.print(element.getMethodName()); printer.print("("); printer.print(element.getFileName()); printer.print(":"); printer.print(Integer.toString(element.getLineNumber())); printer.println(")"); } }); }
/** Dumps the given message and exception stack to the system error console */ public static void dump(String message, Throwable exception) { printEmphasized(StringPrinter.buildString(printer -> { printer.println(message); exception.printStackTrace(printer.toPrintWriter()); })); }
private static String getManifestContent(Jar jarTask, BndManifestExtension extension) throws Throwable { // if we don't want to merge, then delete the existing manifest so that bnd doesn't merge with it if (!extension.mergeWithExisting) { Files.deleteIfExists(outputManifest(jarTask)); } // take the bnd action return BndManifestPlugin.takeBndAction(jarTask.getProject(), jarTask, jar -> { return StringPrinter.buildString(printer -> { try (OutputStream output = printer.toOutputStream(StandardCharsets.UTF_8)) { aQute.bnd.osgi.Jar.writeManifest(jar.getManifest(), printer.toOutputStream(StandardCharsets.UTF_8)); } catch (Exception e) { throw Errors.asRuntime(e); } }); }); }
/** * Returns a PrintStream which will redirect all of its output to the source PrintStream. If * the trigger string is passed through the wrapped PrintStream, then it will dump the * stack trace of the call that printed the trigger. * * @param source * the returned PrintStream will delegate to this stream * @param trigger * the string which triggers a stack dump * @return a PrintStream with the above properties */ public static PrintStream wrapAndDumpWhenContains(PrintStream source, String trigger) { StringPrinter wrapped = new StringPrinter(StringPrinter.stringsToLines(perLine -> { source.println(perLine); if (perLine.contains(trigger)) { dump("Triggered by " + trigger); } })); return wrapped.toPrintStream(); }
private void testCharset(Charset charset) { // get the bytes for this string byte[] bytes = TEST_UTF.getBytes(charset); // write the complicated UTF string one byte at a time to an OutputStream String byteByByteOutputStream = StringPrinter.buildString(printer -> { Errors.rethrow().run(() -> { OutputStream output = printer.toOutputStream(charset); for (byte b : bytes) { output.write(b); } }); }); Assert.assertEquals(TEST_UTF, byteByByteOutputStream); // write the complicated UTF string one byte at a time to a PrintStream String byteByBytePrintStream = StringPrinter.buildString(printer -> { Errors.rethrow().run(() -> { OutputStream output = printer.toPrintStream(charset); for (byte b : bytes) { output.write(b); } }); }); Assert.assertEquals(TEST_UTF, byteByBytePrintStream); }
/** * Prints the given string to the the given printer, wrapped in hierarchy-friendly * braces. Useful for emphasizing a specific event from a sea of logging statements. */ private static void printEmphasized(String toPrint) { // print the triggered header pristineSysErr.println("+----------\\"); for (String line : toPrint.split("\n")) { pristineSysErr.println("| " + line); } pristineSysErr.println("+----------/"); } }
/** Default behavior of {@link Errors#dialog} is @{code JOptionPane.showMessageDialog} without a parent. */ static void defaultDialog(Throwable error) { SwingUtilities.invokeLater(() -> { error.printStackTrace(); String title = error.getClass().getSimpleName(); JOptionPane.showMessageDialog(null, error.getMessage() + "\n\n" + StringPrinter.buildString(printer -> { PrintWriter writer = printer.toPrintWriter(); error.printStackTrace(writer); writer.close(); }), title, JOptionPane.ERROR_MESSAGE); }); }
/** Returns a StringPrinter for {@link System#err}. */ public static StringPrinter systemErr() { return new StringPrinter(System.err::print); } }
@Test public void testToPrintStream() { Assert.assertEquals(TEST_STR, StringPrinter.buildString(printer -> { Errors.rethrow().run(() -> { printer.toPrintStream().print(TEST_STR); }); })); }
@Before public void setupStreams() { testCaseOut.setLength(0); testCaseErr.setLength(0); cleanOut = System.out; cleanErr = System.err; System.setOut(new StringPrinter(str -> { testCaseOut.append(str.replace("\r", "")); }).toPrintStream()); System.setErr(new StringPrinter(str -> { testCaseErr.append(str.replace("\r", "")); }).toPrintStream()); StackDumper.pristineSysErr = new StringPrinter(System.err::print); }
@Test public void ensureOverrideWorks() throws IOException { write("build.gradle", "plugins {", " id 'com.diffplug.gradle.oomph.ide'", "}", "ext.goomph_override_p2bootstrapUrl='somewhere'", "com.diffplug.gradle.GoomphCacheLocations.initFromProject(project)", "System.out.println(com.diffplug.gradle.GoomphCacheLocations.p2bootstrapUrl())", // if we leave it, it will muck with future testkit tests "project.afterEvaluate { com.diffplug.gradle.GoomphCacheLocations.override_p2bootstrapUrl=null }"); StringBuilder buffer = new StringBuilder(); StringPrinter printer = new StringPrinter(buffer::append); try (Writer writer = printer.toPrintWriter()) { gradleRunner().forwardStdOutput(writer).build(); } String firstLine = buffer.toString().split(System.getProperty("line.separator"))[0]; Assert.assertEquals("Optional[somewhere]", firstLine); } }
/** Creates a PrintWriter which passes its content to this StringPrinter. */ public PrintWriter toPrintWriter() { boolean autoflush = true; return new PrintWriter(toWriter(), autoflush); }
/** * Calls {@link #toOutputStream(Charset)} with `charset=UTF-8`. */ public OutputStream toOutputStream() { return toOutputStream(StandardCharsets.UTF_8); }
void transformProductFile(File output, PluginCatalog catalog, String version) throws IOException { String result = StringPrinter.buildString(printer -> { for (String line : productFileLines) { ProductFileUtil.transformProductFile(printer, line, catalog, version); } }); Files.write(output.toPath(), result.getBytes(StandardCharsets.UTF_8)); } }
/** * Calls {@link #toPrintStream(Charset)} with `charset=UTF-8`. */ public PrintStream toPrintStream() { return toPrintStream(StandardCharsets.UTF_8); }
private void testCaseStringsToLines(String expected, String... inputs) { // assemble the result StringBuilder result = new StringBuilder(); // create a harness for converting strings to lines Consumer<String> underTest = StringPrinter.stringsToLines(perLine -> { // there should be no newline Assert.assertEquals(-1, perLine.indexOf('\n')); // we'll append the result to StringBuilder result.append(perLine); result.append('\n'); }); // feed the input to the test harness Arrays.asList(inputs).forEach(underTest::accept); Assert.assertEquals(expected, result.toString()); } }