forked from kpdecker/jsdiff
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdiff.js
More file actions
Latest commit
557 lines (486 loc) · 19.4 KB
/
Copy pathdiff.js
File metadata and controls
557 lines (486 loc) · 19.4 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
(function(global,undefined){
varJsDiff=(function(){
/*jshint maxparams: 5*/
/*istanbul ignore next*/
functionmap(arr,mapper,that){
if(Array.prototype.map){
returnArray.prototype.map.call(arr,mapper,that);
}
varother=newArray(arr.length);
for(vari=0,n=arr.length;i<n;i++){
other[i]=mapper.call(that,arr[i],i,arr);
}
returnother;
}
functionclonePath(path){
return{newPos: path.newPos,components: path.components.slice(0)};
}
functionremoveEmpty(array){
varret=[];
for(vari=0;i<array.length;i++){
if(array[i]){
ret.push(array[i]);
}
}
returnret;
}
functionescapeHTML(s){
varn=s;
n=n.replace(/&/g,'&');
n=n.replace(/</g,'<');
n=n.replace(/>/g,'>');
n=n.replace(/"/g,'"');
returnn;
}
functionbuildValues(components,newString,oldString,useLongestToken){
varcomponentPos=0,
componentLen=components.length,
newPos=0,
oldPos=0;
for(;componentPos<componentLen;componentPos++){
varcomponent=components[componentPos];
if(!component.removed){
if(!component.added&&useLongestToken){
varvalue=newString.slice(newPos,newPos+component.count);
value=map(value,function(value,i){
varoldValue=oldString[oldPos+i];
returnoldValue.length>value.length ? oldValue : value;
});
component.value=value.join('');
}else{
component.value=newString.slice(newPos,newPos+component.count).join('');
}
newPos+=component.count;
// Common case
if(!component.added){
oldPos+=component.count;
}
}else{
component.value=oldString.slice(oldPos,oldPos+component.count).join('');
oldPos+=component.count;
}
}
returncomponents;
}
varDiff=function(ignoreWhitespace){
this.ignoreWhitespace=ignoreWhitespace;
};
Diff.prototype={
diff: function(oldString,newString,callback){
varself=this;
functiondone(value){
if(callback){
setTimeout(function(){callback(undefined,value);},0);
returntrue;
}else{
returnvalue;
}
}
// Handle the identity case (this is due to unrolling editLength == 0
if(newString===oldString){
returndone([{value: newString}]);
}
if(!newString){
returndone([{value: oldString,removed: true}]);
}
if(!oldString){
returndone([{value: newString,added: true}]);
}
newString=this.tokenize(newString);
oldString=this.tokenize(oldString);
varnewLen=newString.length,oldLen=oldString.length;
varmaxEditLength=newLen+oldLen;
varbestPath=[{newPos: -1,components: []}];
// Seed editLength = 0, i.e. the content starts with the same values
varoldPos=this.extractCommon(bestPath[0],newString,oldString,0);
if(bestPath[0].newPos+1>=newLen&&oldPos+1>=oldLen){
// Identity per the equality and tokenizer
returndone([{value: newString.join('')}]);
}
// Main worker method. checks all permutations of a given edit length for acceptance.
functionexecEditLength(){
for(vardiagonalPath=-1*editLength;diagonalPath<=editLength;diagonalPath+=2){
varbasePath;
varaddPath=bestPath[diagonalPath-1],
removePath=bestPath[diagonalPath+1];
oldPos=(removePath ? removePath.newPos : 0)-diagonalPath;
if(addPath){
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1]=undefined;
}
varcanAdd=addPath&&addPath.newPos+1<newLen;
varcanRemove=removePath&&0<=oldPos&&oldPos<oldLen;
if(!canAdd&&!canRemove){
// If this path is a terminal then prune
bestPath[diagonalPath]=undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if(!canAdd||(canRemove&&addPath.newPos<removePath.newPos)){
basePath=clonePath(removePath);
self.pushComponent(basePath.components,undefined,true);
}else{
basePath=addPath;// No need to clone, we've pulled it from the list
basePath.newPos++;
self.pushComponent(basePath.components,true,undefined);
}
varoldPos=self.extractCommon(basePath,newString,oldString,diagonalPath);
// If we have hit the end of both strings, then we are done
if(basePath.newPos+1>=newLen&&oldPos+1>=oldLen){
returndone(buildValues(basePath.components,newString,oldString,self.useLongestToken));
}else{
// Otherwise track this path as a potential candidate and continue.
bestPath[diagonalPath]=basePath;
}
}
editLength++;
}
// Performs the length of edit iteration. Is a bit fugly as this has to support the
// sync and async mode which is never fun. Loops over execEditLength until a value
// is produced.
vareditLength=1;
if(callback){
(functionexec(){
setTimeout(function(){
// This should not happen, but we want to be safe.
/*istanbul ignore next */
if(editLength>maxEditLength){
returncallback();
}
if(!execEditLength()){
exec();
}
},0);
})();
}else{
while(editLength<=maxEditLength){
varret=execEditLength();
if(ret){
returnret;
}
}
}
},
pushComponent: function(components,added,removed){
varlast=components[components.length-1];
if(last&&last.added===added&&last.removed===removed){
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length-1]={count: last.count+1,added: added,removed: removed};
}else{
components.push({count: 1,added: added,removed: removed});
}
},
extractCommon: function(basePath,newString,oldString,diagonalPath){
varnewLen=newString.length,
oldLen=oldString.length,
newPos=basePath.newPos,
oldPos=newPos-diagonalPath,
commonCount=0;
while(newPos+1<newLen&&oldPos+1<oldLen&&this.equals(newString[newPos+1],oldString[oldPos+1])){
newPos++;
oldPos++;
commonCount++;
}
if(commonCount){
basePath.components.push({count: commonCount});
}
basePath.newPos=newPos;
returnoldPos;
},
equals: function(left,right){
varreWhitespace=/\S/;
returnleft===right||(this.ignoreWhitespace&&!reWhitespace.test(left)&&!reWhitespace.test(right));
},
tokenize: function(value){
returnvalue.split('');
}
};
varCharDiff=newDiff();
varWordDiff=newDiff(true);
varWordWithSpaceDiff=newDiff();
WordDiff.tokenize=WordWithSpaceDiff.tokenize=function(value){
returnremoveEmpty(value.split(/(\s+|\b)/));
};
varCssDiff=newDiff(true);
CssDiff.tokenize=function(value){
returnremoveEmpty(value.split(/([{}:;,]|\s+)/));
};
varLineDiff=newDiff();
varTrimmedLineDiff=newDiff();
TrimmedLineDiff.ignoreTrim=true;
LineDiff.tokenize=TrimmedLineDiff.tokenize=function(value){
varretLines=[],
lines=value.split(/^/m);
for(vari=0;i<lines.length;i++){
varline=lines[i],
lastLine=lines[i-1],
lastLineLastChar=lastLine ? lastLine[lastLine.length-1] : '';
// Merge lines that may contain windows new lines
if(line==='\n'&&lastLineLastChar==='\r'){
retLines[retLines.length-1]=retLines[retLines.length-1].slice(0,-1)+'\r\n';
}elseif(line){
if(this.ignoreTrim){
line=line.trim();
//add a newline unless this is the last line.
if(i<lines.length-1){
line+='\n';
}
}
retLines.push(line);
}
}
returnretLines;
};
varSentenceDiff=newDiff();
SentenceDiff.tokenize=function(value){
returnremoveEmpty(value.split(/(\S.+?[.!?])(?=\s+|$)/));
};
varJsonDiff=newDiff();
// Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
JsonDiff.useLongestToken=true;
JsonDiff.tokenize=LineDiff.tokenize;
JsonDiff.equals=function(left,right){
returnLineDiff.equals(left.replace(/,([\r\n])/g,'$1'),right.replace(/,([\r\n])/g,'$1'));
};
varobjectPrototypeToString=Object.prototype.toString;
// This function handles the presence of circular references by bailing out when encountering an
// object that is already on the "stack" of items being processed.
functioncanonicalize(obj,stack,replacementStack){
stack=stack||[];
replacementStack=replacementStack||[];
vari;
for(vari=0;i<stack.length;i+=1){
if(stack[i]===obj){
returnreplacementStack[i];
}
}
varcanonicalizedObj;
if('[object Array]'===objectPrototypeToString.call(obj)){
stack.push(obj);
canonicalizedObj=newArray(obj.length);
replacementStack.push(canonicalizedObj);
for(i=0;i<obj.length;i+=1){
canonicalizedObj[i]=canonicalize(obj[i],stack,replacementStack);
}
stack.pop();
replacementStack.pop();
}elseif(typeofobj==='object'&&obj!==null){
stack.push(obj);
canonicalizedObj={};
replacementStack.push(canonicalizedObj);
varsortedKeys=[];
for(varkeyinobj){
sortedKeys.push(key);
}
sortedKeys.sort();
for(i=0;i<sortedKeys.length;i+=1){
varkey=sortedKeys[i];
canonicalizedObj[key]=canonicalize(obj[key],stack,replacementStack);
}
stack.pop();
replacementStack.pop();
}else{
canonicalizedObj=obj;
}
returncanonicalizedObj;
}
return{
Diff: Diff,
diffChars: function(oldStr,newStr,callback){returnCharDiff.diff(oldStr,newStr,callback);},
diffWords: function(oldStr,newStr,callback){returnWordDiff.diff(oldStr,newStr,callback);},
diffWordsWithSpace: function(oldStr,newStr,callback){returnWordWithSpaceDiff.diff(oldStr,newStr,callback);},
diffLines: function(oldStr,newStr,callback){returnLineDiff.diff(oldStr,newStr,callback);},
diffTrimmedLines: function(oldStr,newStr,callback){returnTrimmedLineDiff.diff(oldStr,newStr,callback);},
diffSentences: function(oldStr,newStr,callback){returnSentenceDiff.diff(oldStr,newStr,callback);},
diffCss: function(oldStr,newStr,callback){returnCssDiff.diff(oldStr,newStr,callback);},
diffJson: function(oldObj,newObj,callback){
returnJsonDiff.diff(
typeofoldObj==='string' ? oldObj : JSON.stringify(canonicalize(oldObj),undefined,' '),
typeofnewObj==='string' ? newObj : JSON.stringify(canonicalize(newObj),undefined,' '),
callback
);
},
createPatch: function(fileName,oldStr,newStr,oldHeader,newHeader){
varret=[];
ret.push('Index: '+fileName);
ret.push('===================================================================');
ret.push('--- '+fileName+(typeofoldHeader==='undefined' ? '' : '\t'+oldHeader));
ret.push('+++ '+fileName+(typeofnewHeader==='undefined' ? '' : '\t'+newHeader));
vardiff=LineDiff.diff(oldStr,newStr);
if(!diff[diff.length-1].value){
diff.pop();// Remove trailing newline add
}
diff.push({value: '',lines: []});// Append an empty value to make cleanup easier
functioncontextLines(lines){
returnmap(lines,function(entry){return' '+entry;});
}
functioneofNL(curRange,i,current){
varlast=diff[diff.length-2],
isLast=i===diff.length-2,
isLastOfType=i===diff.length-3&&(current.added!==last.added||current.removed!==last.removed);
// Figure out if this is the last line for the given file and missing NL
if(!/\n$/.test(current.value)&&(isLast||isLastOfType)){
curRange.push('\\ No newline at end of file');
}
}
varoldRangeStart=0,newRangeStart=0,curRange=[],
oldLine=1,newLine=1;
for(vari=0;i<diff.length;i++){
varcurrent=diff[i],
lines=current.lines||current.value.replace(/\n$/,'').split('\n');
current.lines=lines;
if(current.added||current.removed){
if(!oldRangeStart){
varprev=diff[i-1];
oldRangeStart=oldLine;
newRangeStart=newLine;
if(prev){
curRange=contextLines(prev.lines.slice(-4));
oldRangeStart-=curRange.length;
newRangeStart-=curRange.length;
}
}
curRange.push.apply(curRange,map(lines,function(entry){return(current.added?'+':'-')+entry;}));
eofNL(curRange,i,current);
if(current.added){
newLine+=lines.length;
}else{
oldLine+=lines.length;
}
}else{
if(oldRangeStart){
// Close out any changes that have been output (or join overlapping)
if(lines.length<=8&&i<diff.length-2){
// Overlapping
curRange.push.apply(curRange,contextLines(lines));
}else{
// end the range and output
varcontextSize=Math.min(lines.length,4);
ret.push(
'@@ -'+oldRangeStart+','+(oldLine-oldRangeStart+contextSize)
+' +'+newRangeStart+','+(newLine-newRangeStart+contextSize)
+' @@');
ret.push.apply(ret,curRange);
ret.push.apply(ret,contextLines(lines.slice(0,contextSize)));
if(lines.length<=4){
eofNL(ret,i,current);
}
oldRangeStart=0;newRangeStart=0;curRange=[];
}
}
oldLine+=lines.length;
newLine+=lines.length;
}
}
returnret.join('\n')+'\n';
},
applyPatch: function(oldStr,uniDiff){
vardiffstr=uniDiff.split('\n');
vardiff=[];
varremEOFNL=false,
addEOFNL=false;
for(vari=(diffstr[0][0]==='I'?4:0);i<diffstr.length;i++){
if(diffstr[i][0]==='@'){
varmeh=diffstr[i].split(/@@-(\d+),(\d+)\+(\d+),(\d+)@@/);
diff.unshift({
start:meh[3],
oldlength:meh[2],
oldlines:[],
newlength:meh[4],
newlines:[]
});
}elseif(diffstr[i][0]==='+'){
diff[0].newlines.push(diffstr[i].substr(1));
}elseif(diffstr[i][0]==='-'){
diff[0].oldlines.push(diffstr[i].substr(1));
}elseif(diffstr[i][0]===' '){
diff[0].newlines.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1));
}elseif(diffstr[i][0]==='\\'){
if(diffstr[i-1][0]==='+'){
remEOFNL=true;
}elseif(diffstr[i-1][0]==='-'){
addEOFNL=true;
}
}
}
varstr=oldStr.split('\n');
for(vari=diff.length-1;i>=0;i--){
vard=diff[i];
for(varj=0;j<d.oldlength;j++){
if(str[d.start-1+j]!==d.oldlines[j]){
returnfalse;
}
}
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
}
if(remEOFNL){
while(!str[str.length-1]){
str.pop();
}
}elseif(addEOFNL){
str.push('');
}
returnstr.join('\n');
},
convertChangesToXML: function(changes){
varret=[];
for(vari=0;i<changes.length;i++){
varchange=changes[i];
if(change.added){
ret.push('<ins>');
}elseif(change.removed){
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if(change.added){
ret.push('</ins>');
}elseif(change.removed){
ret.push('</del>');
}
}
returnret.join('');
},
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes){
varret=[],change;
for(vari=0;i<changes.length;i++){
change=changes[i];
ret.push([(change.added ? 1 : change.removed ? -1 : 0),change.value]);
}
returnret;
},
canonicalize: canonicalize
};
})();
/*istanbul ignore next */
if(typeofmodule!=='undefined'&&module.exports){
module.exports=JsDiff;
}
elseif(typeofdefine==='function'&&define.amd){
/*global define */
define([],function(){returnJsDiff;});
}
elseif(typeofglobal.JsDiff==='undefined'){
global.JsDiff=JsDiff;
}
})(this);