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 @@ -69,11 +69,7 @@ void parsing_git_diff_output_works() throws IOException {
@MethodSource("getFormatters")
void reformat_a_subpath_of_a_git_directory_for_only_changed_lines(FormatterService formatterService)
throws IOException, InterruptedException {
runCommandInRepo("git", "init");
runCommandInRepo("git", "config", "user.name", "Test User");
runCommandInRepo("git", "config", "user.email", "test-user@palantir.com");
runCommandInRepo("git", "config", "commit.gpgsign", "false");
runCommandInRepo("git", "commit", "--allow-empty", "-m", "Init");
initRepo();

Path subdir = repo.resolve("subdir");
Files.createDirectories(subdir);
Expand All @@ -92,6 +88,44 @@ void reformat_a_subpath_of_a_git_directory_for_only_changed_lines(FormatterServi
assertThat(dontTouchMe).hasContent(" class DontTouchMe {}");
}

@ParameterizedTest
@MethodSource("getFormatters")
void reflows_the_long_string_of_a_changed_line(FormatterService formatterService)
throws IOException, InterruptedException {
initRepo();
Path longString = repo.resolve("LongString.java");
Files.writeString(longString, """
class LongString {
}
""");
runCommandInRepo("git", "add", ".");
runCommandInRepo("git", "commit", "-m", "A class");

Files.writeString(longString, """
class LongString {
String changed = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.";
}
""");

FormatDiff.formatDiff(repo, formatterService);

assertThat(longString).hasContent("""
class LongString {
String changed =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et"
+ " dolore magna.";
}
""");
}

private void initRepo() throws IOException, InterruptedException {
runCommandInRepo("git", "init");
runCommandInRepo("git", "config", "user.name", "Test User");
runCommandInRepo("git", "config", "user.email", "test-user@palantir.com");
runCommandInRepo("git", "config", "commit.gpgsign", "false");
runCommandInRepo("git", "commit", "--allow-empty", "-m", "Init");
}

private void runCommandInRepo(String... args) throws IOException, InterruptedException {
Process process =
new ProcessBuilder().command(args).directory(repo.toFile()).start();
Expand All @@ -107,6 +141,9 @@ private void runCommandInRepo(String... args) throws IOException, InterruptedExc

private static Stream<FormatterService> getFormatters() throws IOException {
return Stream.of(
// In this JVM, as formatDiff runs it without the native binary.
FormatterServiceLoader.load(
getClasspath().stream().map(Path::toFile).toList()),
new BootstrappingFormatterService(
javaBinPath(), Runtime.version().feature(), getClasspath()),
new NativeImageFormatterService(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.palantir.javaformat.Utils;
import com.palantir.javaformat.java.FormatterException;
import com.palantir.javaformat.java.FormatterService;
import com.palantir.javaformat.java.FormatterServiceImpl;
import com.palantir.javaformat.java.Replacement;
import java.io.File;
import java.net.URI;
Expand Down Expand Up @@ -96,13 +97,43 @@ public void main( String aaaa ) {
.isEmpty();
}

@ParameterizedTest
@MethodSource("getFormattersAndTheInProcessOne")
void reflows_the_long_string_of_the_range(FormatterService formatterService) throws FormatterException {
String input = """
class S {
String changed = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.";
}
""";
String expectedOutput = """
class S {
String changed =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et"
+ " dolore magna.";
}
""";
int start = input.indexOf(" String changed");
int end = input.indexOf('\n', start);

List<Replacement> replacements =
formatterService.getFormatReplacements(input, List.of(Range.closedOpen(start, end)));

assertThat(Utils.applyReplacements(input, replacements)).isEqualTo(expectedOutput);
}

private static Stream<FormatterService> getFormatters() {
return Stream.of(
new BootstrappingFormatterService(
javaBinPath(), Runtime.version().feature(), getClasspath()),
new NativeImageFormatterService(Path.of(System.getenv("NATIVE_IMAGE_CLASSPATH"))));
}

// With the one that formats in this JVM, as formatDiff does without the native binary. On input that does not parse
// it throws, where the other two return no replacements, so it is not among getFormatters.
private static Stream<FormatterService> getFormattersAndTheInProcessOne() {
return Stream.concat(Stream.of(new FormatterServiceImpl()), getFormatters());
}

private String getTestResourceContent(String resourceName) {
try {
URI resource = getClass().getClassLoader().getResource(resourceName).toURI();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import com.palantir.javaformat.Utils;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;

/** Encapsulates information about a file to be formatted, including which parts of the file to format. */
Expand All @@ -51,23 +50,10 @@ public String call() throws FormatterException {
Formatter formatter = Formatter.createFormatter(options);
if (parameters.outputReplacements()) {
RangeSet<Integer> characterRanges = characterRanges(input);
Set<Range<Integer>> rangesToChange = characterRanges.asRanges();
List<Replacement> replacements = formatter.getFormatReplacements(input, rangesToChange);
if (parameters.reflowLongStrings()) {
String formattedText = Utils.applyReplacements(input, replacements);
// avoid trying to wrap the input unless the lines needing wrapping are part of the "characterRanges"
if (!StringWrapper.linesNeedWrapping(options.maxLineLength(), formattedText, characterRanges)) {
return writeFormatReplacements(replacements);
}
String wrappedFormattedText = StringWrapper.wrap(options.maxLineLength(), formattedText, formatter);
// if no wrapping change happened, return the initial replacements
if (wrappedFormattedText.equals(formattedText)) {
return writeFormatReplacements(replacements);
}
return writeFormatReplacements(List.of(Replacement.create(0, input.length(), wrappedFormattedText)));
} else {
return writeFormatReplacements(replacements);
}
return writeFormatReplacements(
parameters.reflowLongStrings()
? formatter.getFormatAndReflowReplacements(input, characterRanges)
: formatter.getFormatReplacements(input, characterRanges.asRanges()));
}
return formatFile(formatter);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,4 +364,25 @@ public List<Replacement> getFormatReplacements(String input, Collection<Range<In
RangeSet<Integer> tokenRangeSet = javaInput.characterRangesToTokenRanges(characterRanges);
return javaOutput.getFormatReplacements(tokenRangeSet);
}

/**
* Emit the {@link Replacement}s that format the given character ranges and reflow long strings, as the command line
* prints them for {@code --output-replacements} and {@link FormatterServiceImpl#getFormatReplacements} returns
* them: in the build's JVM, out of process and with the native binary alike.
*/
List<Replacement> getFormatAndReflowReplacements(String input, RangeSet<Integer> characterRanges)
throws FormatterException {
List<Replacement> replacements = getFormatReplacements(input, characterRanges.asRanges());
String formatted = Utils.applyReplacements(input, replacements);
// avoid trying to wrap the input unless the lines needing wrapping are part of the "characterRanges"
if (!StringWrapper.linesNeedWrapping(options.maxLineLength(), formatted, characterRanges)) {
return replacements;
}
String wrapped = StringWrapper.wrap(options.maxLineLength(), formatted, this);
// if no wrapping change happened, return the initial replacements
if (wrapped.equals(formatted)) {
return replacements;
}
return List.of(Replacement.create(0, input.length(), wrapped));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Range;
import com.google.common.collect.TreeRangeSet;
import com.palantir.javaformat.java.JavaFormatterOptions.Style;
import java.util.Collection;

Expand All @@ -36,7 +37,8 @@ public FormatterServiceImpl() {
@SuppressForbidden(reason = "FormatterService, kept in the SPI for compatibility, returns ImmutableList")
public ImmutableList<Replacement> getFormatReplacements(String text, Collection<Range<Integer>> toRanges)
throws FormatterException {
return ImmutableList.copyOf(formatter.getFormatReplacements(text, toRanges));
// What the command line prints for --output-replacements, which the bootstrapping and native services run.
return ImmutableList.copyOf(formatter.getFormatAndReflowReplacements(text, TreeRangeSet.create(toRanges)));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,19 @@

package com.palantir.javaformat.java;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static org.assertj.core.api.Assertions.assertThat;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.google.common.collect.Range;
import com.palantir.javaformat.java.JavaFormatterOptions.Style;
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
Expand All @@ -26,13 +35,18 @@

/**
* 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. 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
* 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}.
*/
final class FormatterCasesTest {
private static final Formatter FORMATTER = Formatter.createFormatter(
JavaFormatterOptions.builder().style(Style.OJF).build());
private static final FormatterService SERVICE = new FormatterServiceImpl();
private static final ObjectMapper MAPPER =
JsonMapper.builder().addModule(new GuavaModule()).build();

/** The tests of the case files under {@code folders} on the test classpath. */
static List<DynamicTest> casesIn(String... folders) throws Exception {
Expand Down Expand Up @@ -64,10 +78,74 @@ static List<DynamicTest> casesIn(String... folders) throws Exception {
assertThat(twice)
.as(() -> folder + "/" + path + ", second run, " + testCase.firstDifference(twice))
.isEqualTo(once);

var lines = changedLines(testCase);
List<Replacement> replacements = MAPPER.readValue(
commandLine(
testCase.before(),
"--character-ranges",
lines.lowerEndpoint() + ":" + (lines.upperEndpoint() - 1),
"--output-replacements",
"-"),
new TypeReference<>() {});

assertThat(SERVICE.getFormatReplacements(testCase.before(), List.of(lines)))
.as(() -> folder + "/" + path + ", the in-process service on characters " + lines)
.isEqualTo(replacements);
}));
}
}

return tests;
}

/**
* The lines of the before block that formatting changes, from the first that differs from the after block to the
* last, as one range of characters without the last line break; the whole block when no line differs.
*/
private static Range<Integer> changedLines(CaseFile testCase) {
var before = testCase.before();
var beforeLines = List.of(before.split("(?<=\n)"));
var afterLines = List.of(testCase.after().split("(?<=\n)"));
var first = 0;
while (first < beforeLines.size()
&& first < afterLines.size()
&& beforeLines.get(first).equals(afterLines.get(first))) {
first++;
}
var last = 0;
while (last < beforeLines.size() - first
&& last < afterLines.size() - first
&& beforeLines
.get(beforeLines.size() - 1 - last)
.equals(afterLines.get(afterLines.size() - 1 - last))) {
last++;
}
var start = 0;
for (var i = 0; i < first; i++) {
start += beforeLines.get(i).length();
}
var end = start;
for (var i = first; i < beforeLines.size() - last; i++) {
end += beforeLines.get(i).length();
}
while (end > start && (before.charAt(end - 1) == '\n' || before.charAt(end - 1) == '\r')) {
end--;
}
return end > start ? Range.closedOpen(start, end) : Range.closedOpen(0, before.length());
}

/** What {@code open-java-format} prints for the source on standard input. */
static String commandLine(String source, String... args) throws UsageException {
var out = new StringWriter();
var err = new StringWriter();
var main = new Main(
new PrintWriter(out, true),
new PrintWriter(err, true),
new ByteArrayInputStream(source.getBytes(UTF_8)));

assertThat(main.format(args)).as(err::toString).isZero();

return out.toString();
}
}
Loading