Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use diff-match-patch for string diffing #3428

Closed
wants to merge 4 commits into from
Closed
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
1 change: 1 addition & 0 deletions packages/jest-diff/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"dependencies": {
"chalk": "^1.1.3",
"diff": "^3.2.0",
"diff-match-patch": "^1.0.0",
"jest-matcher-utils": "^19.0.0",
"pretty-format": "^19.0.0"
}
Expand Down
21 changes: 14 additions & 7 deletions packages/jest-diff/src/diffStrings.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

const chalk = require('chalk');
const diff = require('diff');
const DiffMatchPatch = require('diff-match-patch');

const {NO_DIFF_MESSAGE} = require('./constants.js');
const DIFF_CONTEXT = 5;
Expand Down Expand Up @@ -46,19 +47,25 @@ const getAnnotation = (options: ?DiffOptions): string =>
'\n' +
chalk.red('+ ' + ((options && options.bAnnotation) || 'Received')) +
'\n\n';

const diffMatchPatch = new DiffMatchPatch();
diffMatchPatch.Diff_Timeout = 0;
const diffLines = (a: string, b: string): Diff => {
let isDifferent = false;
const diffs = diffMatchPatch.diff_main(a, b);
// the following step likely needs changing
diffMatchPatch.diff_cleanupSemantic(diffs);
return {
diff: diff
.diffLines(a, b)
diff: diffs
.map(part => {
const {added, removed} = part;
if (part.added || part.removed) {
const added = part[0] === 1;
const removed = part[0] === -1;
const value = part[1];

if (added || removed) {
isDifferent = true;
}

const lines = part.value.split('\n');
const lines = value.split('\n');
const color = getColor(added, removed);
const bgColor = getBgColor(added, removed);

Expand All @@ -69,7 +76,7 @@ const diffLines = (a: string, b: string): Diff => {
return lines
.map(line => {
const highlightedLine = highlightTrailingWhitespace(line, bgColor);
const mark = color(part.added ? '+' : part.removed ? '-' : ' ');
const mark = color(added ? '+' : removed ? '-' : ' ');
return mark + ' ' + color(highlightedLine) + '\n';
})
.join('');
Expand Down