Skip to content

Commit bf770f1

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. Each case of FormatterCasesTest now also holds the text to the replacements for the lines it changes, and CommandLineRangesTest checks --lines on a file with imports and two long strings.
1 parent c799977 commit bf770f1

5 files changed

Lines changed: 93 additions & 20 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: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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 org.assertj.core.api.Assertions.assertThat;
18+
19+
import org.junit.jupiter.api.Test;
20+
import org.junit.jupiter.api.parallel.Execution;
21+
import org.junit.jupiter.api.parallel.ExecutionMode;
22+
23+
/**
24+
* The command line with {@code --lines}, {@code --offset} or {@code --character-ranges} prints a part of the file
25+
* formatted, the imports and the rest of the file as they are. {@link FormatterCasesTest} holds the text to what
26+
* applying {@code --output-replacements} for the same ranges gives, for every case.
27+
*/
28+
@Execution(ExecutionMode.CONCURRENT)
29+
final class CommandLineRangesTest {
30+
@Test
31+
void linesLeaveTheImportsAndTheStringsElsewhere() throws Exception {
32+
String input = """
33+
import java.util.List;
34+
import java.io.File;
35+
36+
class S {
37+
String outside = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat sed.";
38+
39+
String changed = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.";
40+
}
41+
""";
42+
43+
assertThat(FormatterCasesTest.commandLine(input, "--lines", "7", "-")).isEqualTo("""
44+
import java.util.List;
45+
import java.io.File;
46+
47+
class S {
48+
String outside = "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat sed.";
49+
50+
String changed =
51+
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et"
52+
+ " dolore magna.";
53+
}
54+
""");
55+
}
56+
}

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

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import com.fasterxml.jackson.databind.json.JsonMapper;
2424
import com.fasterxml.jackson.datatype.guava.GuavaModule;
2525
import com.google.common.collect.Range;
26+
import com.palantir.javaformat.Utils;
2627
import com.palantir.javaformat.java.JavaFormatterOptions.Style;
2728
import java.io.ByteArrayInputStream;
2829
import java.io.PrintWriter;
@@ -37,9 +38,9 @@
3738
* One test for each {@link CaseFile} in the given folders on the test classpath: formatting the before block gives the
3839
* after block, and formatting that again changes nothing. For the lines that formatting changes, taken as a range, the
3940
* service that formats in this JVM, as {@code formatDiff} does without the native binary, gives the replacements that
40-
* the command line prints, which the bootstrapping and native services run. Adding a case is adding a file. The cases
41-
* are in a folder of the JDK they need, and each JDK has a class that runs the folders it can parse, such as
42-
* {@link FormatterCasesJava21Test}.
41+
* the command line prints, which the bootstrapping and native services run, and the command line printing text gives
42+
* what applying them gives. Adding a case is adding a file. The cases are in a folder of the JDK they need, and each
43+
* JDK has a class that runs the folders it can parse, such as {@link FormatterCasesJava21Test}.
4344
*/
4445
final class FormatterCasesTest {
4546
private static final Formatter FORMATTER = Formatter.createFormatter(
@@ -80,18 +81,19 @@ static List<DynamicTest> casesIn(String... folders) throws Exception {
8081
.isEqualTo(once);
8182

8283
var lines = changedLines(testCase);
84+
var characters = lines.lowerEndpoint() + ":" + (lines.upperEndpoint() - 1);
8385
List<Replacement> replacements = MAPPER.readValue(
8486
commandLine(
85-
testCase.before(),
86-
"--character-ranges",
87-
lines.lowerEndpoint() + ":" + (lines.upperEndpoint() - 1),
88-
"--output-replacements",
89-
"-"),
87+
testCase.before(), "--character-ranges", characters, "--output-replacements", "-"),
9088
new TypeReference<>() {});
9189

9290
assertThat(SERVICE.getFormatReplacements(testCase.before(), List.of(lines)))
9391
.as(() -> folder + "/" + path + ", the in-process service on characters " + lines)
9492
.isEqualTo(replacements);
93+
94+
assertThat(commandLine(testCase.before(), "--character-ranges", characters, "-"))
95+
.as(() -> folder + "/" + path + ", the command line printing characters " + lines)
96+
.isEqualTo(Utils.applyReplacements(testCase.before(), replacements));
9597
}));
9698
}
9799
}

‎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)