diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/FormatFileCallable.java b/open-java-format/src/main/java/com/palantir/javaformat/java/FormatFileCallable.java index 1faeedf1a..f51ad6c59 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/FormatFileCallable.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/FormatFileCallable.java @@ -49,15 +49,30 @@ public String call() throws FormatterException { Formatter formatter = Formatter.createFormatter(options); if (parameters.outputReplacements()) { - RangeSet characterRanges = characterRanges(input); - return writeFormatReplacements( - parameters.reflowLongStrings() - ? formatter.getFormatAndReflowReplacements(input, characterRanges) - : formatter.getFormatReplacements(input, characterRanges.asRanges())); + return writeFormatReplacements(replacements(formatter)); + } + if (!wholeFile()) { + // A part of the file, as --output-replacements has it: the imports and the rest of the file stay as they + // are. + return Utils.applyReplacements(input, replacements(formatter)); } return formatFile(formatter); } + private List replacements(Formatter formatter) throws FormatterException { + RangeSet characterRanges = characterRanges(input); + return parameters.reflowLongStrings() + ? formatter.getFormatAndReflowReplacements(input, characterRanges) + : formatter.getFormatReplacements(input, characterRanges.asRanges()); + } + + /** No {@code --lines}, {@code --offset} or {@code --character-ranges}. */ + private boolean wholeFile() { + return parameters.characterRanges().isEmpty() + && parameters.lines().isEmpty() + && parameters.offsets().isEmpty(); + } + String writeFormatReplacements(List replacements) throws FormatterException { try { return MAPPER.writeValueAsString(replacements); @@ -88,9 +103,7 @@ private String fixImports(String input) throws FormatterException { private RangeSet characterRanges(String input) { final RangeSet characterRanges = TreeRangeSet.create(); - if (parameters.characterRanges().isEmpty() - && parameters.lines().isEmpty() - && parameters.offsets().isEmpty()) { + if (wholeFile()) { characterRanges.add(Range.closedOpen(0, input.length())); return characterRanges; } diff --git a/open-java-format/src/test/java/com/palantir/javaformat/java/CommandLineRangesTest.java b/open-java-format/src/test/java/com/palantir/javaformat/java/CommandLineRangesTest.java new file mode 100644 index 000000000..fb5c902d8 --- /dev/null +++ b/open-java-format/src/test/java/com/palantir/javaformat/java/CommandLineRangesTest.java @@ -0,0 +1,56 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.java; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +/** + * The command line with {@code --lines}, {@code --offset} or {@code --character-ranges} prints a part of the file + * formatted, the imports and the rest of the file as they are. {@link FormatterCasesTest} holds the text to what + * applying {@code --output-replacements} for the same ranges gives, for every case. + */ +@Execution(ExecutionMode.CONCURRENT) +final class CommandLineRangesTest { + @Test + void linesLeaveTheImportsAndTheStringsElsewhere() throws Exception { + String input = """ + import java.util.List; + import java.io.File; + + class S { + String outside = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat sed."; + + String changed = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna."; + } + """; + + assertThat(FormatterCasesTest.commandLine(input, "--lines", "7", "-")).isEqualTo(""" + import java.util.List; + import java.io.File; + + class S { + String outside = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat sed."; + + String changed = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et" + + " dolore magna."; + } + """); + } +} diff --git a/open-java-format/src/test/java/com/palantir/javaformat/java/FormatterCasesTest.java b/open-java-format/src/test/java/com/palantir/javaformat/java/FormatterCasesTest.java index 73a07ed03..272136162 100644 --- a/open-java-format/src/test/java/com/palantir/javaformat/java/FormatterCasesTest.java +++ b/open-java-format/src/test/java/com/palantir/javaformat/java/FormatterCasesTest.java @@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.google.common.collect.Range; +import com.palantir.javaformat.Utils; import com.palantir.javaformat.java.JavaFormatterOptions.Style; import java.io.ByteArrayInputStream; import java.io.PrintWriter; @@ -37,9 +38,9 @@ * One test for each {@link CaseFile} in the given folders on the test classpath: formatting the before block gives the * after block, and formatting that again changes nothing. For the lines that formatting changes, taken as a range, the * service that formats in this JVM, as {@code formatDiff} does without the native binary, gives the replacements that - * the command line prints, which the bootstrapping and native services run. Adding a case is adding a file. The cases - * are in a folder of the JDK they need, and each JDK has a class that runs the folders it can parse, such as - * {@link FormatterCasesJava21Test}. + * the command line prints, which the bootstrapping and native services run, and the command line printing text gives + * what applying them gives. Adding a case is adding a file. The cases are in a folder of the JDK they need, and each + * JDK has a class that runs the folders it can parse, such as {@link FormatterCasesJava21Test}. */ final class FormatterCasesTest { private static final Formatter FORMATTER = Formatter.createFormatter( @@ -80,18 +81,19 @@ static List casesIn(String... folders) throws Exception { .isEqualTo(once); var lines = changedLines(testCase); + var characters = lines.lowerEndpoint() + ":" + (lines.upperEndpoint() - 1); List replacements = MAPPER.readValue( commandLine( - testCase.before(), - "--character-ranges", - lines.lowerEndpoint() + ":" + (lines.upperEndpoint() - 1), - "--output-replacements", - "-"), + testCase.before(), "--character-ranges", characters, "--output-replacements", "-"), new TypeReference<>() {}); assertThat(SERVICE.getFormatReplacements(testCase.before(), List.of(lines))) .as(() -> folder + "/" + path + ", the in-process service on characters " + lines) .isEqualTo(replacements); + + assertThat(commandLine(testCase.before(), "--character-ranges", characters, "-")) + .as(() -> folder + "/" + path + ", the command line printing characters " + lines) + .isEqualTo(Utils.applyReplacements(testCase.before(), replacements)); })); } } diff --git a/open-java-format/src/test/java/com/palantir/javaformat/java/MainTest.java b/open-java-format/src/test/java/com/palantir/javaformat/java/MainTest.java index fe059ece9..9fedaca6a 100644 --- a/open-java-format/src/test/java/com/palantir/javaformat/java/MainTest.java +++ b/open-java-format/src/test/java/com/palantir/javaformat/java/MainTest.java @@ -264,9 +264,10 @@ void optimizeImportsDoesNotLeaveEmptyLines() throws Exception { assertThat(out.toString()).isEqualTo(joiner.join(expected)); } - // test that -lines handling works with import removal + // -lines formats those lines only, as --output-replacements does: an unused import stays, where it was removed with + // every other import of the file fixed (ADR-001). @Test - void importRemovalLines() throws Exception { + void linesLeaveTheImports() throws Exception { String[] input = { "import java.util.ArrayList;", "import java.util.List;", @@ -277,7 +278,7 @@ void importRemovalLines() throws Exception { }; String[] expected = { "import java.util.ArrayList;", - "", + "import java.util.List;", "class Test {", " ArrayList a = new ArrayList<>();", "ArrayList b = new ArrayList<>();", diff --git a/open-java-format/src/test/java/com/palantir/javaformat/java/PartialFormattingTest.java b/open-java-format/src/test/java/com/palantir/javaformat/java/PartialFormattingTest.java index 544ac3d61..d3bd9a7e5 100644 --- a/open-java-format/src/test/java/com/palantir/javaformat/java/PartialFormattingTest.java +++ b/open-java-format/src/test/java/com/palantir/javaformat/java/PartialFormattingTest.java @@ -1551,11 +1551,12 @@ public void importJavadocNewlines() throws Exception { " ArrayList xs = new ArrayList<>();", "}", ""); + // The line of the import is laid out, and the imports are not fixed: the blank line after it was the import + // orderer's, which -lines no longer runs (ADR-001). String expectedOutput = lines( "package p;", "", "import java.util.ArrayList;", - "", "/** */", "class Foo {", " ArrayList xs = new ArrayList<>();",