forked from cel-expr/cel-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLineDiffer.java
More file actions
260 lines (227 loc) · 9.36 KB
/
Copy pathLineDiffer.java
File metadata and controls
260 lines (227 loc) · 9.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// Copyright 2022 Google LLC
//
// 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
//
// https://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 dev.cel.testing;
import static java.lang.Math.max;
import com.google.auto.value.AutoValue;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.errorprone.annotations.CheckReturnValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** Utility for generating a set of differences between two text files. */
@CheckReturnValue
public final class LineDiffer {
static final Diff EMPTY_DIFF = Diff.of(ImmutableList.of(), ImmutableList.of());
private static final Splitter LINE_SPLITTER = Splitter.on('\n');
public static Diff diffLines(String firstText, String secondText) {
if (firstText.equals(secondText)) {
return EMPTY_DIFF;
}
List<String> firstLines = LINE_SPLITTER.splitToList(firstText);
List<String> secondLines = LINE_SPLITTER.splitToList(secondText);
int firstLinesCount = firstLines.size();
int secondLinesCount = secondLines.size();
if (firstText.isEmpty()) {
return Diff.of(
ImmutableList.of(Snippet.of(1, secondLinesCount, secondLines)), ImmutableList.of());
}
if (secondText.isEmpty()) {
return Diff.of(
ImmutableList.of(), ImmutableList.of(Snippet.of(1, firstLinesCount, firstLines)));
}
// Compute a matrix of equivalent lines (ignoring spaces) into a matrix representing the longest
// common subsequences present in the input text. This method is O(n^2) and more efficient
// techniques exist, but the texts being compared are quite small so the performance should
// suffice.
int[][] longestCommonSubsequence = new int[firstLinesCount + 1][secondLinesCount + 1];
for (int firstLine = 1; firstLine < firstLinesCount + 1; firstLine++) {
for (int secondLine = 1; secondLine < secondLinesCount + 1; secondLine++) {
if (equalsHashIgnoreSpaces(
firstLines.get(firstLine - 1), secondLines.get(secondLine - 1))) {
// Increments the common subsequence length.
longestCommonSubsequence[firstLine][secondLine] =
1 + longestCommonSubsequence[firstLine - 1][secondLine - 1];
} else {
// Records the longest common subsequence from either the first or second text.
longestCommonSubsequence[firstLine][secondLine] =
max(
longestCommonSubsequence[firstLine - 1][secondLine],
longestCommonSubsequence[firstLine][secondLine - 1]);
}
}
}
int firstLine = firstLinesCount;
int secondLine = secondLinesCount;
ArrayList<Snippet> removals = new ArrayList<>();
ArrayList<Snippet> additions = new ArrayList<>();
while (firstLine != 0 || secondLine != 0) {
// This is an addition case where the second text contains more lines than the first.
if (firstLine == 0) {
if (!secondLines.isEmpty()) {
Snippet addition = Snippet.of(secondLine, secondLines.get(secondLine - 1));
appendOrJoin(additions, addition);
}
secondLine--;
continue;
}
// This is a removal case where the second text contains fewer lines than the first.
if (secondLine == 0) {
if (!firstLines.isEmpty()) {
Snippet removal = Snippet.of(firstLine, firstLines.get(firstLine - 1));
appendOrJoin(removals, removal);
}
firstLine--;
continue;
}
// The lines of text are equal and thus can be omitted from the results.
if (equalsIgnoreSpaces(firstLines.get(firstLine - 1), secondLines.get(secondLine - 1))) {
firstLine--;
secondLine--;
continue;
}
// Follow the direction of the longest common subsequence.
int cmp =
Integer.compare(
longestCommonSubsequence[firstLine - 1][secondLine],
longestCommonSubsequence[firstLine][secondLine - 1]);
if (cmp <= 0) {
Snippet addition = Snippet.of(secondLine, secondLines.get(secondLine - 1));
appendOrJoin(additions, addition);
secondLine--;
} else {
Snippet removal = Snippet.of(firstLine, firstLines.get(firstLine - 1));
appendOrJoin(removals, removal);
firstLine--;
}
}
return Diff.of(
ImmutableList.copyOf(additions).reverse(), ImmutableList.copyOf(removals).reverse());
}
private static void appendOrJoin(ArrayList<Snippet> snippets, Snippet snippet) {
if (snippets.isEmpty()) {
snippets.add(snippet);
return;
}
Snippet prev = Iterables.getLast(snippets);
if (snippet.isContiguous(prev)) {
snippets.set(snippets.size() - 1, snippet.join(prev));
} else {
snippets.add(snippet);
}
}
private static boolean equalsHashIgnoreSpaces(String first, String second) {
return first.trim().hashCode() == second.trim().hashCode();
}
private static boolean equalsIgnoreSpaces(String first, String second) {
return first.trim().equals(second.trim());
}
/**
* Snippet of text which includes the starting and ending lines where the snippet occurs in to the
* lines of text.
*/
@AutoValue
public abstract static class Snippet {
public abstract int startLine();
public abstract int endLine();
public abstract ImmutableList<String> textLines();
boolean isContiguous(Snippet snippet) {
return endLine() + 1 == snippet.startLine();
}
boolean intersects(Snippet snippet) {
return (startLine() <= snippet.startLine() && snippet.startLine() <= endLine())
|| (startLine() <= snippet.endLine() && snippet.endLine() <= endLine());
}
Snippet join(Snippet snippet) {
return Snippet.of(
startLine(),
snippet.endLine(),
ImmutableList.<String>builder().addAll(textLines()).addAll(snippet.textLines()).build());
}
String render(String direction) {
StringBuilder snippetString = new StringBuilder();
for (String line : textLines()) {
snippetString.append(String.format("%s %s%n", direction, line));
}
return snippetString.toString();
}
static Snippet of(int line, String text) {
return Snippet.of(line, line, ImmutableList.of(text));
}
static Snippet of(int startLine, int endLine, Collection<String> textLines) {
return Snippet.of(startLine, endLine, ImmutableList.copyOf(textLines));
}
static Snippet of(int startLine, int endLine, ImmutableList<String> textLines) {
return new AutoValue_LineDiffer_Snippet(startLine, endLine, textLines);
}
}
/**
* Diff holds a collection of additions and removals representing the differing lines between two
* strings.
*/
@AutoValue
public abstract static class Diff {
public abstract ImmutableList<Snippet> additions();
public abstract ImmutableList<Snippet> removals();
public boolean isEmpty() {
return additions().isEmpty() && removals().isEmpty();
}
static Diff of(ImmutableList<Snippet> additions, ImmutableList<Snippet> removals) {
return new AutoValue_LineDiffer_Diff(additions, removals);
}
@Override
public final String toString() {
int removeIndex = 0;
StringBuilder diffString = new StringBuilder();
for (int i = 0; i < additions().size(); i++) {
Snippet addition = additions().get(i);
Snippet removal = maybeNextSnippet(removals(), removeIndex);
if (removal == null) {
diffString.append(snippetHeader(addition)).append(addition.render(">"));
continue;
}
while (removal != null
&& removal.startLine() < addition.startLine()
&& !addition.intersects(removal)) {
diffString.append(snippetHeader(removal)).append(removal.render("<"));
removal = maybeNextSnippet(removals(), ++removeIndex);
}
if (removal != null && addition.intersects(removal)) {
diffString
.append(snippetHeader(addition))
.append(addition.render(">"))
.append(removal.render("<"));
removeIndex++;
} else {
diffString.append(snippetHeader(addition)).append(addition.render(">"));
}
}
for (int i = removeIndex; i < removals().size(); i++) {
Snippet removal = removals().get(i);
diffString.append(snippetHeader(removal)).append(removal.render("<"));
}
return diffString.toString();
}
private static String snippetHeader(Snippet snippet) {
return snippet.startLine() == snippet.endLine()
? String.format("===== Line %d =====\n", snippet.startLine())
: String.format("===== Lines %d-%d =====\n", snippet.startLine(), snippet.endLine());
}
private static Snippet maybeNextSnippet(ImmutableList<Snippet> snippets, int index) {
return index < snippets.size() ? snippets.get(index) : null;
}
}
private LineDiffer() {}
}