Skip to content

Commit 67bec58

Browse files
authored
[Enhancement] Only Send Updates When Formatting Changed (palantir#1188)
1 parent aeb6ae5 commit 67bec58

2 files changed

Lines changed: 50 additions & 13 deletions

File tree

‎idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
import java.util.List;
3737
import java.util.Optional;
3838
import java.util.Set;
39-
import java.util.stream.Collectors;
4039
import org.jetbrains.annotations.NotNull;
4140

4241
class PalantirJavaFormatFormattingService extends AsyncDocumentFormattingService {
@@ -91,28 +90,32 @@ public void run() {
9190
return;
9291
}
9392

93+
String preFormatText = request.getDocumentText();
94+
9495
try {
9596
if (logger.isDebugEnabled()) {
9697
logger.debug(String.format(
9798
"Received request to format file=%s, length=%s with ranges=%s",
9899
Optional.ofNullable(request.getIOFile())
99100
.map(file -> file.toPath().toString())
100101
.orElse("null"),
101-
request.getDocumentText().length(),
102+
preFormatText.length(),
102103
request.getFormattingRanges()));
103104
}
104-
List<Replacement> replacements =
105-
formatterService.get().getFormatReplacements(request.getDocumentText(), toRanges(request));
106-
if (logger.isDebugEnabled()) {
107-
logger.debug(String.format(
108-
"Applying %s replacements with ranges=%s",
109-
replacements.size(),
110-
replacements.stream()
111-
.map(Replacement::getReplaceRange)
112-
.collect(Collectors.toSet())));
105+
106+
// Note: I attempted to implement this using getFormatReplacements and elide an update when
107+
// there were no replacements. There is a bug in the underlying formatter where it _always_
108+
// returns a change. Thus we must perform a content aware diff / branching.
109+
String formattedText = applyReplacements(
110+
preFormatText, formatterService.get().getFormatReplacements(preFormatText, toRanges(request)));
111+
112+
// The Javadoc of this API says that you should set it to null when the document is unchanged
113+
// We should not be trying to format a document that is already formatted
114+
if (preFormatText.equals(formattedText)) {
115+
request.onTextReady(null);
116+
} else {
117+
request.onTextReady(formattedText);
113118
}
114-
String formattedText = applyReplacements(request.getDocumentText(), replacements);
115-
request.onTextReady(formattedText);
116119
} catch (FormatterException e) {
117120
logger.error(
118121
String.format(

‎palantir-java-format/src/test/java/com/palantir/javaformat/java/FormatterTest.java‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import static org.assertj.core.api.Assertions.assertThatThrownBy;
2222

2323
import com.google.common.base.Joiner;
24+
import com.google.common.collect.Range;
2425
import com.google.common.io.CharStreams;
2526
import java.io.ByteArrayInputStream;
2627
import java.io.IOException;
@@ -31,6 +32,7 @@
3132
import java.nio.charset.StandardCharsets;
3233
import java.nio.file.Files;
3334
import java.nio.file.Path;
35+
import java.util.List;
3436
import org.junit.jupiter.api.Test;
3537
import org.junit.jupiter.api.io.TempDir;
3638
import org.junit.jupiter.api.parallel.Execution;
@@ -452,4 +454,36 @@ void canParse_java9_private_interface_methods() {
452454
+ "}"))
453455
.doesNotThrowAnyException();
454456
}
457+
458+
@Test
459+
void producesFormattingChangesOnAlreadyFormattedFiles() throws FormatterException {
460+
Formatter formatter = Formatter.create();
461+
String simpleClass = "package com.palantir;\n"
462+
+ "\n"
463+
+ "public final class Formatted {\n"
464+
+ " public static int count(int number) {\n"
465+
+ " return number;\n"
466+
+ " }\n"
467+
+ "}";
468+
// This is kinda overkill but the point of the test is to show that it
469+
// is for sure formatted and still producing a replacement.
470+
String formattedClass = formatter.formatSourceAndFixImports(simpleClass);
471+
String reformattedClass = formatter.formatSourceAndFixImports(formattedClass);
472+
473+
// The formatSourceAndFixImports code path flows through getFormatReplacements and
474+
// this shows that despite the replacements happening they are superfluous
475+
assertThat(formattedClass).isEqualTo(reformattedClass);
476+
477+
assertWithMessage("""
478+
If this test is failing and you are reading this message it means that an underlying bug
479+
in the formatting service was fixed. Previously, this formatter always produced a "replacement"
480+
even when the document was fully formatted. You can see evidence of this in
481+
https://github.com/palantir/palantir-java-format/pull/1188. To fix this failing test, consider
482+
relying on the new behavior and instead checking that the 'replacements' is empty instead of
483+
full string comparison.
484+
""")
485+
.that(formatter.getFormatReplacements(
486+
formattedClass, List.of(Range.closedOpen(0, formattedClass.length()))))
487+
.isNotEmpty();
488+
}
455489
}

0 commit comments

Comments
 (0)