Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public String formatDiagnostics(String path, String input) {
sb.append(path).append(":").append(diagnostic).append(System.lineSeparator());
int line = diagnostic.line();
int column = diagnostic.column();
if (line != -1 && column != -1) {
if (line > 0 && column > 0 && line <= lines.size()) {
sb.append(CharMatcher.breakingWhitespace().trimTrailingFrom(lines.get(line - 1)))
.append(System.lineSeparator());
sb.append(" ".repeat(column - 1)).append('^').append(System.lineSeparator());
Expand Down
23 changes: 18 additions & 5 deletions core/src/main/java/com/google/googlejavaformat/java/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,24 @@ public int format(String... args) throws UsageException {
private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions options) {
int numThreads = min(MAX_THREADS, parameters.files().size());
ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
boolean allOk;
try {
allOk = formatFiles(parameters, options, executorService);
} finally {
// Shut down the executor even if formatting throws, otherwise its non-daemon threads keep the
// JVM alive.
if (!MoreExecutors.shutdownAndAwaitTermination(executorService, Duration.ofSeconds(5))) {
errWriter.println("Failed to shut down ExecutorService");
allOk = false;
}
}
return allOk ? 0 : 1;
}

private boolean formatFiles(
CommandLineOptions parameters,
JavaFormatterOptions options,
ExecutorService executorService) {
ExecutorCompletionService<FormatFileCallable.Result> cs =
new ExecutorCompletionService<>(executorService);
boolean allOk = true;
Expand Down Expand Up @@ -195,11 +212,7 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti
outWriter.write(formatted);
}
}
if (!MoreExecutors.shutdownAndAwaitTermination(executorService, Duration.ofSeconds(5))) {
errWriter.println("Failed to shut down ExecutorService");
allOk = false;
}
return allOk ? 0 : 1;
return allOk;
}

private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions options) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,22 +80,36 @@ static String wrap(final int columnLimit, String input, Formatter formatter)
// We really don't want bugs in this pass to change the behaviour of programs we're
// formatting, so check that the pretty-printed AST is the same before and after reformatting.
String expected = parse(input, /* allowStringFolding= */ true).toString();
String actual = parse(result, /* allowStringFolding= */ true).toString();
String actual;
try {
actual = parse(result, /* allowStringFolding= */ true).toString();
} catch (FormatterException e) {
// Diagnostics for the reflowed output don't correspond to positions in the original input,
// and the error is a bug in this pass rather than in the input, so report it as such.
throw somethingHasGoneTerriblyWrong(
"it would produce code that does not parse (" + e.getMessage() + ")", result, input);
}
if (!expected.equals(actual)) {
throw new FormatterException(
String.format(
"Something has gone terribly wrong. We planned to make the below formatting change,"
+ " but have aborted because it would unexpectedly change the AST.\n"
+ "Please file a bug: "
+ "https://github.com/google/google-java-format/issues/new"
+ "\n\n=== Actual: ===\n%s\n=== Expected: ===\n%s\n",
actual, expected));
throw somethingHasGoneTerriblyWrong(
"it would unexpectedly change the AST", actual, expected);
}
}

return result;
}

private static FormatterException somethingHasGoneTerriblyWrong(
String reason, String actual, String expected) {
return new FormatterException(
String.format(
"Something has gone terribly wrong. We planned to make the below formatting change,"
+ " but have aborted because %s.\n"
+ "Please file a bug: "
+ "https://github.com/google/google-java-format/issues/new"
+ "\n\n=== Actual: ===\n%s\n=== Expected: ===\n%s\n",
reason, actual, expected));
}

private static TreeRangeMap<Integer, String> getReflowReplacements(
int columnLimit, final String input, JavaFormatterOptions options) throws FormatterException {
return new Reflower(columnLimit, input, options).getReflowReplacements();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.googlejavaformat.FormatterDiagnostic;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -100,6 +101,51 @@ public void lexError() throws Exception {
assertThat(result).isEqualTo(1);
}

@Test
public void formatDiagnostics_positionOutOfRange() {
String input = "class T {}\n";
assertThat(
new FormatterException(new FormatterDiagnostic(5, 3, "oops"))
.formatDiagnostics("T.java", input))
.isEqualTo("T.java:5:3: error: oops" + System.lineSeparator());
assertThat(
new FormatterException(new FormatterDiagnostic(0, 3, "oops"))
.formatDiagnostics("T.java", input))
.isEqualTo("T.java:0:3: error: oops" + System.lineSeparator());
assertThat(
new FormatterException(new FormatterDiagnostic(1, 0, "oops"))
.formatDiagnostics("T.java", input))
.isEqualTo("T.java:1:0: error: oops" + System.lineSeparator());
}

@Test
public void stringWrappingProducesInvalidCode() throws Exception {
// Reflowing this string splits the escaped backslash in `\\t`, which produces an unterminated
// string literal several lines past the end of the original input.
String input =
"""
class T {
String s = "%s%s\\\\tend";
}
"""
.formatted("word ".repeat(100), "x".repeat(95));

StringWriter stdout = new StringWriter();
StringWriter stderr = new StringWriter();
Main main = new Main(new PrintWriter(stdout, true), new PrintWriter(stderr, true), System.in);

Path tmpdir = testFolder.newFolder().toPath();
Path path = tmpdir.resolve("T.java");
Files.writeString(path, input);

int result = main.format(path.toString());
assertThat(stdout.toString()).isEmpty();
assertThat(stderr.toString())
.contains(
"it would produce code that does not parse (9:13: error: unclosed string literal)");
assertThat(result).isEqualTo(1);
}

@Test
public void oneFileParseError() throws Exception {
String one = "class One {\n";
Expand Down
Loading