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 @@ -76,10 +76,13 @@ private String reorderImports() throws FormatterException {
ImportsAndIndex imports = scanImports(firstImportStart);
int afterLastImport = imports.index;

// Make sure there are no more imports before the next class (etc) definition.
// Another import before the next class (etc) definition means something other than whitespace and comments
// separates the imports, such as a stray `;`, which javac rejects from Java 21 on. Leave the imports as they
// are rather than fail the whole file (google/google-java-format#1528): the formatter reports what is wrong
// with the file, or formats it if nothing is.
Optional<Integer> maybeLaterImport = findIdentifier(afterLastImport, IMPORT_OR_CLASS_START);
if (maybeLaterImport.isPresent() && tokenAt(maybeLaterImport.get()).equals("import")) {
throw new FormatterException("Imports not contiguous (perhaps a comment separates them?)");
return text;
}

StringBuilder result = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,25 @@ void throwsFormatterException() throws Exception {
.isInstanceOf(FormatterException.class);
}

// Fixing the imports leaves imports it cannot sort alone, so the error reported is what is wrong with the file,
// not "Imports not contiguous" (google/google-java-format#1528).
@Test
void straySemicolonBetweenImportsReportsTheParseError() {
String input = """
import b.B;
;
import a.A;

class T {
A a;
B b;
}
""";
assertThatThrownBy(() -> FORMATTER.formatSourceAndFixImports(input))
.isInstanceOf(FormatterException.class)
.hasMessage("2:1: error: extraneous semicolon");
}

@Test
void blankLinesImportComment() throws FormatterException {
String withBlank = """
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,16 @@ public static List<Object[]> parameters() {
"import com.foo.Third;",
}
},
// Anything else between two imports leaves them all where they are, rather than failing the file
// (google/google-java-format#1528).
{
{
"import com.foo.Second;", //
";",
"import com.foo.First;",
},
{}
},
{
{
"import com.foo.Second; /* A block comment after an import stays with it. */", //
Expand Down
Loading