Skip to content

Commit 275270f

Browse files
committed
Format only the ranges on the command line, and leave the imports
With --lines, --offset or --character-ranges and no --output-replacements, Main formatted the ranges, then fixed the imports of the whole file and reflowed every long string in it. It now prints what applying its --output-replacements for the same ranges gives: the code of the ranges formatted, its long strings reflowed, the imports and the rest of the file as they are (ADR-001). Without ranges nothing changes. Two tests pinned the old way: MainTest.importRemovalLines, now linesLeaveTheImports, and PartialFormattingTest.importJavadocNewlines, whose import line is still laid out but no longer gets the import orderer's blank line after it. CommandLineRangesTest holds the text to the replacements for the lines each case changes, run by CommandLineRangesJava21Test, Java25Test and Java28Test on the case folders of their JDK; on the code before, 26 of its tests fail.
1 parent 6e28b71 commit 275270f

7 files changed

Lines changed: 240 additions & 12 deletions

File tree

‎open-java-format/src/main/java/com/palantir/javaformat/java/FormatFileCallable.java‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,30 @@ public String call() throws FormatterException {
4949

5050
Formatter formatter = Formatter.createFormatter(options);
5151
if (parameters.outputReplacements()) {
52-
RangeSet<Integer> characterRanges = characterRanges(input);
53-
return writeFormatReplacements(
54-
parameters.reflowLongStrings()
55-
? formatter.getFormatAndReflowReplacements(input, characterRanges)
56-
: formatter.getFormatReplacements(input, characterRanges.asRanges()));
52+
return writeFormatReplacements(replacements(formatter));
53+
}
54+
if (!wholeFile()) {
55+
// A part of the file, as --output-replacements has it: the imports and the rest of the file stay as they
56+
// are.
57+
return Utils.applyReplacements(input, replacements(formatter));
5758
}
5859
return formatFile(formatter);
5960
}
6061

62+
private List<Replacement> replacements(Formatter formatter) throws FormatterException {
63+
RangeSet<Integer> characterRanges = characterRanges(input);
64+
return parameters.reflowLongStrings()
65+
? formatter.getFormatAndReflowReplacements(input, characterRanges)
66+
: formatter.getFormatReplacements(input, characterRanges.asRanges());
67+
}
68+
69+
/** No {@code --lines}, {@code --offset} or {@code --character-ranges}. */
70+
private boolean wholeFile() {
71+
return parameters.characterRanges().isEmpty()
72+
&& parameters.lines().isEmpty()
73+
&& parameters.offsets().isEmpty();
74+
}
75+
6176
String writeFormatReplacements(List<Replacement> replacements) throws FormatterException {
6277
try {
6378
return MAPPER.writeValueAsString(replacements);
@@ -88,9 +103,7 @@ private String fixImports(String input) throws FormatterException {
88103
private RangeSet<Integer> characterRanges(String input) {
89104
final RangeSet<Integer> characterRanges = TreeRangeSet.create();
90105

91-
if (parameters.characterRanges().isEmpty()
92-
&& parameters.lines().isEmpty()
93-
&& parameters.offsets().isEmpty()) {
106+
if (wholeFile()) {
94107
characterRanges.add(Range.closedOpen(0, input.length()));
95108
return characterRanges;
96109
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.java;
16+
17+
import java.util.List;
18+
import org.junit.jupiter.api.DynamicTest;
19+
import org.junit.jupiter.api.TestFactory;
20+
import org.junit.jupiter.api.condition.EnabledForJreRange;
21+
import org.junit.jupiter.api.condition.JRE;
22+
import org.junit.jupiter.api.parallel.Execution;
23+
import org.junit.jupiter.api.parallel.ExecutionMode;
24+
25+
/** {@link CommandLineRangesTest} on JDK 21 and later, with the cases of JDK 21. */
26+
@EnabledForJreRange(min = JRE.JAVA_21)
27+
@Execution(ExecutionMode.CONCURRENT)
28+
final class CommandLineRangesJava21Test {
29+
@TestFactory
30+
List<DynamicTest> printsWhatItsReplacementsGive() throws Exception {
31+
return CommandLineRangesTest.changedLinesIn("test-cases-java21");
32+
}
33+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.java;
16+
17+
import java.util.List;
18+
import org.junit.jupiter.api.DynamicTest;
19+
import org.junit.jupiter.api.TestFactory;
20+
import org.junit.jupiter.api.condition.EnabledForJreRange;
21+
import org.junit.jupiter.api.condition.JRE;
22+
import org.junit.jupiter.api.parallel.Execution;
23+
import org.junit.jupiter.api.parallel.ExecutionMode;
24+
25+
/** {@link CommandLineRangesTest} on JDK 25 and later, with the cases of JDK 21 and 25. */
26+
@EnabledForJreRange(min = JRE.JAVA_25)
27+
@Execution(ExecutionMode.CONCURRENT)
28+
final class CommandLineRangesJava25Test {
29+
@TestFactory
30+
List<DynamicTest> printsWhatItsReplacementsGive() throws Exception {
31+
return CommandLineRangesTest.changedLinesIn("test-cases-java25", "test-cases-java21");
32+
}
33+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.java;
16+
17+
import java.util.List;
18+
import org.junit.jupiter.api.DynamicTest;
19+
import org.junit.jupiter.api.TestFactory;
20+
import org.junit.jupiter.api.condition.EnabledForJreRange;
21+
import org.junit.jupiter.api.condition.JRE;
22+
import org.junit.jupiter.api.parallel.Execution;
23+
import org.junit.jupiter.api.parallel.ExecutionMode;
24+
25+
/** {@link CommandLineRangesTest} on JDK 28 and later, with the cases of JDK 21, 25 and 28. */
26+
@EnabledForJreRange(min = JRE.JAVA_28)
27+
@Execution(ExecutionMode.CONCURRENT)
28+
final class CommandLineRangesJava28Test {
29+
@TestFactory
30+
List<DynamicTest> printsWhatItsReplacementsGive() throws Exception {
31+
return CommandLineRangesTest.changedLinesIn("test-cases-java28", "test-cases-java25", "test-cases-java21");
32+
}
33+
}
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.java;
16+
17+
import static java.nio.charset.StandardCharsets.UTF_8;
18+
import static org.assertj.core.api.Assertions.assertThat;
19+
20+
import com.fasterxml.jackson.core.type.TypeReference;
21+
import com.fasterxml.jackson.databind.ObjectMapper;
22+
import com.fasterxml.jackson.databind.json.JsonMapper;
23+
import com.fasterxml.jackson.datatype.guava.GuavaModule;
24+
import com.palantir.javaformat.Utils;
25+
import java.io.ByteArrayInputStream;
26+
import java.io.PrintWriter;
27+
import java.io.StringWriter;
28+
import java.nio.file.Files;
29+
import java.util.ArrayList;
30+
import java.util.List;
31+
import org.junit.jupiter.api.DynamicTest;
32+
import org.junit.jupiter.api.Test;
33+
import org.junit.jupiter.api.parallel.Execution;
34+
import org.junit.jupiter.api.parallel.ExecutionMode;
35+
36+
/**
37+
* The command line with {@code --lines}, {@code --offset} or {@code --character-ranges} prints what applying its
38+
* {@code --output-replacements} for the same ranges gives: a part of the file formatted, the imports and the rest of the
39+
* file as they are. Each JDK has a class that runs the case folders it can parse, such as
40+
* {@link CommandLineRangesJava21Test}.
41+
*/
42+
@Execution(ExecutionMode.CONCURRENT)
43+
final class CommandLineRangesTest {
44+
private static final ObjectMapper MAPPER =
45+
JsonMapper.builder().addModule(new GuavaModule()).build();
46+
47+
/** The tests of the case files under {@code folders} on the test classpath. */
48+
static List<DynamicTest> changedLinesIn(String... folders) throws Exception {
49+
var tests = new ArrayList<DynamicTest>();
50+
51+
for (var folder : folders) {
52+
var root = CaseFile.folder(folder);
53+
54+
for (var path : CaseFile.pathsIn(root)) {
55+
tests.add(DynamicTest.dynamicTest(path, () -> {
56+
var testCase = CaseFile.parse(path, Files.readString(root.resolve(path)));
57+
var source = testCase.before();
58+
var lines = testCase.changedLines();
59+
var ranges = lines.lowerEndpoint() + ":" + (lines.upperEndpoint() - 1);
60+
List<Replacement> replacements = MAPPER.readValue(
61+
commandLine(source, "--character-ranges", ranges, "--output-replacements", "-"),
62+
new TypeReference<>() {});
63+
64+
assertThat(commandLine(source, "--character-ranges", ranges, "-"))
65+
.as(() -> folder + "/" + path + ", characters " + lines)
66+
.isEqualTo(Utils.applyReplacements(source, replacements));
67+
}));
68+
}
69+
}
70+
71+
return tests;
72+
}
73+
74+
@Test
75+
void linesLeaveTheImportsAndTheStringsElsewhere() throws Exception {
76+
String input = """
77+
import java.util.List;
78+
import java.io.File;
79+
80+
class S {
81+
String outside = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat sed.";
82+
83+
String changed = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.";
84+
}
85+
""";
86+
87+
assertThat(commandLine(input, "--lines", "7", "-")).isEqualTo("""
88+
import java.util.List;
89+
import java.io.File;
90+
91+
class S {
92+
String outside = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat sed.";
93+
94+
String changed =
95+
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et"
96+
+ " dolore magna.";
97+
}
98+
""");
99+
}
100+
101+
/** What {@code open-java-format} prints for the source on standard input. */
102+
private static String commandLine(String source, String... args) throws UsageException {
103+
var out = new StringWriter();
104+
var err = new StringWriter();
105+
var main = new Main(
106+
new PrintWriter(out, true),
107+
new PrintWriter(err, true),
108+
new ByteArrayInputStream(source.getBytes(UTF_8)));
109+
110+
assertThat(main.format(args)).as(err::toString).isZero();
111+
112+
return out.toString();
113+
}
114+
}

‎open-java-format/src/test/java/com/palantir/javaformat/java/MainTest.java‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -264,9 +264,10 @@ void optimizeImportsDoesNotLeaveEmptyLines() throws Exception {
264264
assertThat(out.toString()).isEqualTo(joiner.join(expected));
265265
}
266266

267-
// test that -lines handling works with import removal
267+
// -lines formats those lines only, as --output-replacements does: an unused import stays, where it was removed with
268+
// every other import of the file fixed (ADR-001).
268269
@Test
269-
void importRemovalLines() throws Exception {
270+
void linesLeaveTheImports() throws Exception {
270271
String[] input = {
271272
"import java.util.ArrayList;",
272273
"import java.util.List;",
@@ -277,7 +278,7 @@ void importRemovalLines() throws Exception {
277278
};
278279
String[] expected = {
279280
"import java.util.ArrayList;",
280-
"",
281+
"import java.util.List;",
281282
"class Test {",
282283
" ArrayList<String> a = new ArrayList<>();",
283284
"ArrayList<String> b = new ArrayList<>();",

‎open-java-format/src/test/java/com/palantir/javaformat/java/PartialFormattingTest.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1551,11 +1551,12 @@ public void importJavadocNewlines() throws Exception {
15511551
" ArrayList<String> xs = new ArrayList<>();",
15521552
"}",
15531553
"");
1554+
// The line of the import is laid out, and the imports are not fixed: the blank line after it was the import
1555+
// orderer's, which -lines no longer runs (ADR-001).
15541556
String expectedOutput = lines(
15551557
"package p;",
15561558
"",
15571559
"import java.util.ArrayList;",
1558-
"",
15591560
"/** */",
15601561
"class Foo {",
15611562
" ArrayList<String> xs = new ArrayList<>();",

0 commit comments

Comments
 (0)