-
Notifications
You must be signed in to change notification settings - Fork 510
/
Copy pathline.js
70 lines (61 loc) · 2.6 KB
/
line.js
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
import Diff from './base';
import {generateOptions} from '../util/params';
export const lineDiff = new Diff();
lineDiff.tokenize = function(value, options) {
if(options.stripTrailingCr) {
// remove one \r before \n to match GNU diff's --strip-trailing-cr behavior
value = value.replace(/\r\n/g, '\n');
}
let retLines = [],
linesAndNewlines = value.split(/(\n|\r\n)/);
// Ignore the final empty token that occurs if the string ends with a new line
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
// Merge the content and line separators into single tokens
for (let i = 0; i < linesAndNewlines.length; i++) {
let line = linesAndNewlines[i];
if (i % 2 && !options.newlineIsToken) {
retLines[retLines.length - 1] += line;
} else {
retLines.push(line);
}
}
return retLines;
};
lineDiff.equals = function(left, right, options) {
// If we're ignoring whitespace, we need to normalise lines by stripping
// whitespace before checking equality. (This has an annoying interaction
// with newlineIsToken that requires special handling: if newlines get their
// own token, then we DON'T want to trim the *newline* tokens down to empty
// strings, since this would cause us to treat whitespace-only line content
// as equal to a separator between lines, which would be weird and
// inconsistent with the documented behavior of the options.)
if (options.ignoreWhitespace) {
if (!options.newlineIsToken || !left.includes('\n')) {
left = left.trim();
}
if (!options.newlineIsToken || !right.includes('\n')) {
right = right.trim();
}
} else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
if (left.endsWith('\n')) {
left = left.slice(0, -1);
}
if (right.endsWith('\n')) {
right = right.slice(0, -1);
}
}
return Diff.prototype.equals.call(this, left, right, options);
};
export function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); }
// Kept for backwards compatibility. This is a rather arbitrary wrapper method
// that just calls `diffLines` with `ignoreWhitespace: true`. It's confusing to
// have two ways to do exactly the same thing in the API, so we no longer
// document this one (library users should explicitly use `diffLines` with
// `ignoreWhitespace: true` instead) but we keep it around to maintain
// compatibility with code that used old versions.
export function diffTrimmedLines(oldStr, newStr, callback) {
let options = generateOptions(callback, {ignoreWhitespace: true});
return lineDiff.diff(oldStr, newStr, options);
}