Skip to content

Commit 19e6298

Browse files
committed
intellij runs wrapper
1 parent 8063b4d commit 19e6298

6 files changed

Lines changed: 78 additions & 44 deletions

File tree

debugger/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
React App that helps Debugging a javaInput's AST.
2+
3+
1. Run only one test from [FormatterIntegrationTest](https://github.com/palantir/palantir-java-format/blob/0ad916e4f27b5aab3870d633a16c50192b6e54cc/palantir-java-format/src/test/java/com/palantir/javaformat/java/FormatterIntegrationTest.java#L66) with ["debugOutput" = true](https://github.com/palantir/palantir-java-format/blob/0ad916e4f27b5aab3870d633a16c50192b6e54cc/palantir-java-format/src/test/java/com/palantir/javaformat/java/FormatterIntegrationTest.java#L66)
4+
2. Run `cd debugger && NODE_OPTIONS=--openssl-legacy-provider yarn start` that will open the app in the browser (<code>localhost:3000</code>)
5+
6+
7+
-----
8+
19
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
210

311
## Available Scripts

palantir-java-format-jdk-bootstrap/src/main/java/com/palantir/javaformat/bootstrap/NativeImageFormatterService.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ public NativeImageFormatterService(Path nativeImagePath) {
4545

4646
@Override
4747
public ImmutableList<Replacement> getFormatReplacements(String input, Collection<Range<Integer>> ranges) {
48+
Optional<String> output = Optional.empty();
4849
try {
4950
FormatterNativeImageArgs command = FormatterNativeImageArgs.builder()
5051
.nativeImagePath(nativeImagePath)
@@ -53,14 +54,14 @@ public ImmutableList<Replacement> getFormatReplacements(String input, Collection
5354
ranges.stream().map(RangeUtils::toStringRange).collect(Collectors.toList()))
5455
.build();
5556

56-
Optional<String> output = FormatterCommandRunner.runWithStdin(
57+
output = FormatterCommandRunner.runWithStdin(
5758
command.toArgs(), input, Optional.ofNullable(nativeImagePath.getParent()));
5859
if (output.isEmpty() || output.get().isEmpty()) {
5960
return ImmutableList.of();
6061
}
6162
return MAPPER.readValue(output.get(), new TypeReference<>() {});
6263
} catch (IOException e) {
63-
throw new UncheckedIOException("Error running the native image command", e);
64+
throw new UncheckedIOException(String.format("Error running the native image command %s", output), e);
6465
}
6566
}
6667

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

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,29 @@
1414

1515
package com.palantir.javaformat.java;
1616

17+
import static java.util.Comparator.comparing;
18+
1719
import com.fasterxml.jackson.core.JsonProcessingException;
1820
import com.fasterxml.jackson.databind.ObjectMapper;
1921
import com.fasterxml.jackson.databind.json.JsonMapper;
2022
import com.fasterxml.jackson.datatype.guava.GuavaModule;
21-
import com.google.common.collect.ImmutableList;
2223
import com.google.common.collect.Range;
2324
import com.google.common.collect.RangeSet;
2425
import com.google.common.collect.TreeRangeSet;
2526
import com.palantir.javaformat.Utils;
2627
import java.io.UncheckedIOException;
28+
import java.util.ArrayList;
29+
import java.util.Collection;
30+
import java.util.List;
31+
import java.util.Set;
2732
import java.util.concurrent.Callable;
33+
import java.util.logging.Logger;
2834

2935
/** Encapsulates information about a file to be formatted, including which parts of the file to format. */
3036
class FormatFileCallable implements Callable<String> {
31-
private final ObjectMapper MAPPER =
37+
private static final ObjectMapper MAPPER =
3238
JsonMapper.builder().addModule(new GuavaModule()).build();
33-
39+
private static final Logger log = Logger.getLogger("FormatFileCallable");
3440
private final String input;
3541
private final CommandLineOptions parameters;
3642
private final JavaFormatterOptions options;
@@ -49,14 +55,38 @@ public String call() throws FormatterException {
4955

5056
Formatter formatter = Formatter.createFormatter(options);
5157
if (parameters.outputReplacements()) {
52-
return formatReplacements(formatter);
58+
Set<Range<Integer>> rangesToChange = characterRanges(input).asRanges();
59+
List<Replacement> replacements = formatter.getFormatReplacements(input, rangesToChange);
60+
// log.severe("rangesToChange: " + rangesToChange);
61+
if (parameters.reflowLongStrings()) {
62+
String formattedText = applyReplacements(input, replacements);
63+
if (!StringWrapper.needWrapping(options.maxLineLength(), formattedText)) {
64+
return writeFormatReplacements(replacements);
65+
}
66+
String formattedSource = StringWrapper.wrap(options.maxLineLength(), formattedText, formatter);
67+
return writeFormatReplacements(List.of(Replacement.create(0, input.length(), formattedSource)));
68+
} else {
69+
return writeFormatReplacements(replacements);
70+
}
5371
}
5472
return formatFile(formatter);
5573
}
5674

57-
private String formatReplacements(Formatter formatter) throws FormatterException {
58-
ImmutableList<Replacement> replacements =
59-
formatter.getFormatReplacements(input, characterRanges(input).asRanges());
75+
static String applyReplacements(String input, Collection<Replacement> replacementsCollection) {
76+
List<Replacement> replacements = new ArrayList<>(replacementsCollection);
77+
replacements.sort(comparing((Replacement r) -> r.getReplaceRange().lowerEndpoint())
78+
.reversed());
79+
StringBuilder writer = new StringBuilder(input);
80+
for (Replacement replacement : replacements) {
81+
writer.replace(
82+
replacement.getReplaceRange().lowerEndpoint(),
83+
replacement.getReplaceRange().upperEndpoint(),
84+
replacement.getReplacementString());
85+
}
86+
return writer.toString();
87+
}
88+
89+
String writeFormatReplacements(List<Replacement> replacements) throws FormatterException {
6090
try {
6191
return MAPPER.writeValueAsString(replacements);
6292
} catch (JsonProcessingException e) {

palantir-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ private static ImmutableSet<Range<Integer>> rangesAfterAppliedReplacements(
116116
}
117117

118118
@SuppressWarnings("for-rollout:NullAway")
119-
private static TreeRangeMap<Integer, String> getReflowReplacements(int columnLimit, final String input)
119+
public static TreeRangeMap<Integer, String> getReflowReplacements(int columnLimit, final String input)
120120
throws FormatterException {
121121
return new Reflower(columnLimit, input).getReflowReplacements();
122122
}
@@ -289,6 +289,7 @@ private static boolean onSameLineAsParent(LineMap lineMap, TreePath path) {
289289
getStartPosition(path.getParentPath().getLeaf()));
290290
}
291291
}
292+
292293
/**
293294
* Returns the source text of the given string literal trees, excluding the leading and trailing double-quotes and
294295
* the `+` operator.
@@ -361,7 +362,7 @@ static int hasEscapedNewlineAt(String input, int idx) {
361362
* @param components the text to reflow
362363
* @param first0 true if the text includes the beginning of its enclosing concat chain, i.e. a
363364
* @param firstLineStartColumn the column where the very first line starts (can be less than textStartColumn if text
364-
* follows variable declaration)
365+
* follows variable declaration)
365366
*/
366367
private static String reflow(
367368
String separator,
@@ -420,17 +421,6 @@ private static String reflow(
420421
"\""));
421422
}
422423

423-
private static boolean totalLengthLessThanOrEqual(Iterable<String> input, int length) {
424-
int total = 0;
425-
for (String s : input) {
426-
total += s.length();
427-
if (total > length) {
428-
return false;
429-
}
430-
}
431-
return true;
432-
}
433-
434424
/**
435425
* Flattens the given binary expression tree, and extracts the subset that contains the given path and any adjacent
436426
* nodes that are also string literals.
@@ -491,7 +481,7 @@ private static int getStartPosition(Tree tree) {
491481
}
492482

493483
/** Returns true if any lines in the given Java source exceed the column limit. */
494-
private static boolean needWrapping(int columnLimit, String input) {
484+
public static boolean needWrapping(int columnLimit, String input) {
495485
// TODO(cushon): consider adding Newlines.lineIterable?
496486
Iterator<String> it = Newlines.lineIterator(input);
497487
while (it.hasNext()) {

palantir-java-format/src/test/resources/com/palantir/javaformat/java/testdata/RSL.input

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,7 @@ class RSLs {
5252
""", 42);
5353

5454
"""
55-
hello %s dsadasdsadad addkadkadakdakda hdsafdaf
56-
daskdabs
57-
adasd
55+
hello %s
5856
"""
5957
.formatted("world");
6058
f(
@@ -65,7 +63,7 @@ class RSLs {
6563
bar
6664
""");
6765
"""
68-
hello my dasdasdagdafkasfas fsdgaidahdahdafhalsdflas hasdsasadasdsadasdasdasds
66+
hello
6967
""".codePoints().forEach(System.err::println);
7068
String s =
7169
"""

palantir-java-format/src/test/resources/com/palantir/javaformat/java/testdata/RSL.output

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,11 @@ class RSLs {
3232

3333
ipsum
3434
""";
35-
String j =
36-
"""
37-
lorem
38-
one long incredibly unbroken sentence moving from topic to topic so that no one had a chance to interrupt
39-
ipsum
40-
""";
35+
String j = """
36+
lorem
37+
one long incredibly unbroken sentence moving from topic to topic so that no one had a chance to interrupt
38+
ipsum
39+
""";
4140
String k = """
4241
lorem
4342
ipsum
@@ -81,19 +80,27 @@ class RSLs {
8180
""" + """
8281
bar
8382
""";
84-
String u = stringVariableOne
85-
+ """
86-
...
87-
"""
88-
+ stringVariableTwo
89-
+ """
83+
String u = stringVariableOne + """
84+
...
85+
""" + stringVariableTwo + """
9086
...
9187
""";
9288
}
9389

94-
String x = String.format(
95-
"""
96-
this very long string that does something using arguments %s %s %s
97-
""",
98-
"@", "@", "something");
90+
String x = String.format("""
91+
this very long string that does something using arguments %s %s %s
92+
""", "@", "@", "something");
93+
94+
{
95+
"""
96+
No tools or answer found in the message. Please try again, following the instructions:\s
97+
98+
%s
99+
""".someOtherValue(e -> e.getValue().print())
100+
.myValue(System.err::println)
101+
.formatted(toolFormatter.usage())
102+
.myOtherValue()
103+
.someOtherValue()
104+
.somethingElse();
105+
}
99106
}

0 commit comments

Comments
 (0)