Skip to content

Commit f7eeb77

Browse files
cushongoogle-java-format Team
authored andcommitted
Remove extra blank lines left by cleanup deletions and at EOF in partial formatting.
When partial formatting removed an unused import, the reformat range for the deletion covered only one character on each side, so the blank lines that had surrounded the import were left behind as a double blank line. Deletions at the start or end of the file were not reformatted at all. Separately, a range ending in the file's trailing blank lines did not reach the EOF token, so the trailing blank lines were never removed. Reformat the whitespace around a deletion plus the adjacent token on each side, including at the start and end of the file. Treat a character range that is followed only by whitespace as extending to EOF. PiperOrigin-RevId: 1007193676
1 parent cad4e9a commit f7eeb77

3 files changed

Lines changed: 74 additions & 8 deletions

File tree

‎core/src/main/java/com/google/googlejavaformat/java/Cleanups.java‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import static java.lang.Math.max;
1919
import static java.lang.Math.min;
2020

21+
import com.google.common.base.CharMatcher;
2122
import com.google.common.collect.ImmutableList;
2223
import com.google.common.collect.ImmutableRangeSet;
2324
import com.google.common.collect.ImmutableSet;
@@ -228,12 +229,26 @@ private void applyReplacements(List<Replacement> replacements) {
228229

229230
/// Returns the range to reformat for the given span.
230231
private static Range<Integer> reformatRange(Span span, String contents) {
231-
int start = span.outStart();
232-
int end = span.outEnd();
233-
if (start == end && !contents.isEmpty()) {
234-
start = max(0, start - 1);
235-
end = min(contents.length(), end + 1);
232+
if (span.outStart() == span.outEnd()) {
233+
return deletionReformatRange(contents, span.outStart());
236234
}
237-
return start < end ? Range.closedOpen(start, end) : Range.closedOpen(0, 0);
235+
return Range.closedOpen(span.outStart(), span.outEnd());
236+
}
237+
238+
/// Returns the range to reformat around a deletion at `pos`: the surrounding whitespace plus one
239+
/// character of each adjacent token, or empty if there is no surrounding whitespace.
240+
private static Range<Integer> deletionReformatRange(String contents, int pos) {
241+
int start = pos;
242+
while (start > 0 && CharMatcher.whitespace().matches(contents.charAt(start - 1))) {
243+
start--;
244+
}
245+
int end = pos;
246+
while (end < contents.length() && CharMatcher.whitespace().matches(contents.charAt(end))) {
247+
end++;
248+
}
249+
if (start == end) {
250+
return Range.closedOpen(0, 0);
251+
}
252+
return Range.closedOpen(max(0, start - 1), min(contents.length(), end + 1));
238253
}
239254
}

‎core/src/main/java/com/google/googlejavaformat/java/JavaInput.java‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import static com.google.common.collect.Iterables.getLast;
1919
import static java.nio.charset.StandardCharsets.UTF_8;
2020

21+
import com.google.common.base.CharMatcher;
2122
import com.google.common.base.MoreObjects;
2223
import com.google.common.base.Verify;
2324
import com.google.common.collect.DiscreteDomain;
@@ -608,6 +609,8 @@ static void validateRanges(Collection<Range<Integer>> characterRanges, int textL
608609
}
609610
}
610611

612+
private static final CharMatcher NOT_WHITESPACE = CharMatcher.whitespace().negate();
613+
611614
/// Convert from a character range to a token range.
612615
///
613616
/// @param characterRange the `0`-based [Range] of characters
@@ -624,11 +627,15 @@ private Range<Integer> characterRangeToTokenRange(Range<Integer> characterRange)
624627
: characterRange;
625628
ImmutableCollection<Token> enclosed =
626629
getPositionTokenMap().subRangeMap(nonEmptyRange).asMapOfRanges().values();
630+
boolean touchesEof = NOT_WHITESPACE.indexIn(text, characterRange.upperEndpoint()) == -1;
627631
if (enclosed.isEmpty()) {
632+
if (touchesEof) {
633+
return Range.closedOpen(getkN(), getkN() + 1);
634+
}
628635
return EMPTY_RANGE;
629636
}
630-
return Range.closedOpen(
631-
enclosed.iterator().next().getTok().getIndex(), getLast(enclosed).getTok().getIndex() + 1);
637+
int hi = touchesEof ? getkN() + 1 : getLast(enclosed).getTok().getIndex() + 1;
638+
return Range.closedOpen(enclosed.iterator().next().getTok().getIndex(), hi);
632639
}
633640

634641
/// Get the number of toks.

‎core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1799,4 +1799,48 @@ public void b117602702() throws Exception {
17991799
String output = runFormatter(input, new String[] {"-offset", "13", "-length", "1"});
18001800
assertThat(output).isEqualTo(expectedOutput);
18011801
}
1802+
1803+
// b/30464184: remove unused imports in partial formatting leaves at most one blank line
1804+
@Test
1805+
public void unusedImportDeletionNoDoubleBlankLine() throws Exception {
1806+
String input =
1807+
lines("package com.example;", "", "import java.util.List;", "", "class Test {}", "");
1808+
String expectedOutput = lines("package com.example;", "", "class Test {}", "");
1809+
assertThat(
1810+
new Formatter()
1811+
.formatSource(
1812+
input,
1813+
ImmutableList.of(rangeOf(input, "import java.util.List;")),
1814+
/* removeUnusedImports= */ true,
1815+
/* sortImports= */ true,
1816+
/* reflowLongStrings= */ false))
1817+
.isEqualTo(expectedOutput);
1818+
1819+
String noPackageInput = lines("import java.util.List;", "", "class Test {}", "");
1820+
String noPackageExpected = lines("class Test {}", "");
1821+
assertThat(
1822+
new Formatter()
1823+
.formatSource(
1824+
noPackageInput,
1825+
ImmutableList.of(rangeOf(noPackageInput, "import java.util.List;")),
1826+
/* removeUnusedImports= */ true,
1827+
/* sortImports= */ true,
1828+
/* reflowLongStrings= */ false))
1829+
.isEqualTo(noPackageExpected);
1830+
}
1831+
1832+
// b/150227347: trailing blank lines at EOF removed when range touches EOF
1833+
@Test
1834+
public void trailingBlankLinesAtEofRemoved() throws Exception {
1835+
String input = lines("class Test {", " void f() {}", "}", "", "", "");
1836+
String expectedOutput = lines("class Test {", " void f() {}", "}", "");
1837+
assertThat(runFormatter(input, new String[] {"-lines", "3:5"})).isEqualTo(expectedOutput);
1838+
assertThat(runFormatter(input, new String[] {"-lines", "4:5"})).isEqualTo(expectedOutput);
1839+
assertThat(runFormatter(input, new String[] {"-lines", "4:6"})).isEqualTo(expectedOutput);
1840+
1841+
String commentInput = lines("class Test {} // comment", "", "", "");
1842+
String commentExpected = lines("class Test {} // comment", "");
1843+
assertThat(runFormatter(commentInput, new String[] {"-lines", "2:3"}))
1844+
.isEqualTo(commentExpected);
1845+
}
18021846
}

0 commit comments

Comments
 (0)