Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,30 @@ public String call() throws FormatterException {

Formatter formatter = Formatter.createFormatter(options);
if (parameters.outputReplacements()) {
RangeSet<Integer> 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<Replacement> replacements(Formatter formatter) throws FormatterException {
RangeSet<Integer> 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<Replacement> replacements) throws FormatterException {
try {
return MAPPER.writeValueAsString(replacements);
Expand Down Expand Up @@ -88,9 +103,7 @@ private String fixImports(String input) throws FormatterException {
private RangeSet<Integer> characterRanges(String input) {
final RangeSet<Integer> characterRanges = TreeRangeSet.create();

if (parameters.characterRanges().isEmpty()
&& parameters.lines().isEmpty()
&& parameters.offsets().isEmpty()) {
if (wholeFile()) {
characterRanges.add(Range.closedOpen(0, input.length()));
return characterRanges;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.";
}
""");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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(
Expand Down Expand Up @@ -80,18 +81,19 @@ static List<DynamicTest> casesIn(String... folders) throws Exception {
.isEqualTo(once);

var lines = changedLines(testCase);
var characters = lines.lowerEndpoint() + ":" + (lines.upperEndpoint() - 1);
List<Replacement> 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));
}));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;",
Expand All @@ -277,7 +278,7 @@ void importRemovalLines() throws Exception {
};
String[] expected = {
"import java.util.ArrayList;",
"",
"import java.util.List;",
"class Test {",
" ArrayList<String> a = new ArrayList<>();",
"ArrayList<String> b = new ArrayList<>();",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1551,11 +1551,12 @@ public void importJavadocNewlines() throws Exception {
" ArrayList<String> 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<String> xs = new ArrayList<>();",
Expand Down
Loading