5 // A PHP diff engine for phpwiki.
7 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
8 // You may copy this code freely under the conditions of the GPL.
11 abstract class _DiffOp
17 abstract function reverse();
21 return $this->orig ? sizeof($this->orig) : 0;
26 return $this->final ? sizeof($this->final) : 0;
30 class _DiffOp_Copy extends _DiffOp
32 public $type = 'copy';
34 function _DiffOp_Copy($orig, $final = false)
36 if (!is_array($final))
39 $this->final = $final;
44 return new _DiffOp_Copy($this->final, $this->orig);
48 class _DiffOp_Delete extends _DiffOp
50 public $type = 'delete';
52 function _DiffOp_Delete($lines)
60 return new _DiffOp_Add($this->orig);
64 class _DiffOp_Add extends _DiffOp
68 function _DiffOp_Add($lines)
70 $this->final = $lines;
76 return new _DiffOp_Delete($this->final);
80 class _DiffOp_Change extends _DiffOp
82 public $type = 'change';
84 function _DiffOp_Change($orig, $final)
87 $this->final = $final;
92 return new _DiffOp_Change($this->final, $this->orig);
97 * Class used internally by Diff to actually compute the diffs.
99 * The algorithm used here is mostly lifted from the perl module
100 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
101 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
103 * More ideas are taken from:
104 * http://www.ics.uci.edu/~eppstein/161/960229.html
106 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
107 * diffutils-2.7, which can be found at:
108 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
110 * Finally, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
113 * @author Geoffrey T. Dairiki
118 function diff($from_lines, $to_lines)
120 $n_from = sizeof($from_lines);
121 $n_to = sizeof($to_lines);
123 $this->xchanged = $this->ychanged = array();
124 $this->xv = $this->yv = array();
125 $this->xind = $this->yind = array();
127 unset($this->in_seq);
130 // Skip leading common lines.
131 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
132 if ($from_lines[$skip] != $to_lines[$skip])
134 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
136 // Skip trailing common lines.
139 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
140 if ($from_lines[$xi] != $to_lines[$yi])
142 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
145 // Ignore lines which do not exist in both files.
146 for ($xi = $skip; $xi < $n_from - $endskip; $xi++)
147 $xhash[$from_lines[$xi]] = 1;
148 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
149 $line = $to_lines[$yi];
150 if (($this->ychanged[$yi] = empty($xhash[$line])))
156 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
157 $line = $from_lines[$xi];
158 if (($this->xchanged[$xi] = empty($yhash[$line])))
165 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
167 // Merge edits when possible
168 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
169 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
171 // Compute the edit operations.
174 while ($xi < $n_from || $yi < $n_to) {
175 assert($yi < $n_to || $this->xchanged[$xi]);
176 assert($xi < $n_from || $this->ychanged[$yi]);
178 // Skip matching "snake".
180 while ($xi < $n_from && $yi < $n_to
181 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
182 $copy[] = $from_lines[$xi++];
186 $edits[] = new _DiffOp_Copy($copy);
188 // Find deletes & adds.
190 while ($xi < $n_from && $this->xchanged[$xi])
191 $delete[] = $from_lines[$xi++];
194 while ($yi < $n_to && $this->ychanged[$yi])
195 $add[] = $to_lines[$yi++];
198 $edits[] = new _DiffOp_Change($delete, $add);
200 $edits[] = new _DiffOp_Delete($delete); elseif ($add)
201 $edits[] = new _DiffOp_Add($add);
206 /* Divide the Largest Common Subsequence (LCS) of the sequences
207 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
210 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
211 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
212 * sub sequences. The first sub-sequence is contained in [X0, X1),
213 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
214 * that (X0, Y0) == (XOFF, YOFF) and
215 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
217 * This function assumes that the first lines of the specified portions
218 * of the two files do not match, and likewise that the last lines do not
219 * match. The caller must trim matching lines from the beginning and end
220 * of the portions it is going to specify.
222 function _diag($xoff, $xlim, $yoff, $ylim, $nchunks)
226 if ($xlim - $xoff > $ylim - $yoff) {
227 // Things seems faster (I'm not sure I understand why)
228 // when the shortest sequence in X.
230 list ($xoff, $xlim, $yoff, $ylim)
231 = array($yoff, $ylim, $xoff, $xlim);
235 for ($i = $ylim - 1; $i >= $yoff; $i--)
236 $ymatches[$this->xv[$i]][] = $i;
238 for ($i = $ylim - 1; $i >= $yoff; $i--)
239 $ymatches[$this->yv[$i]][] = $i;
242 $this->seq[0] = $yoff - 1;
243 $this->in_seq = array();
246 $numer = $xlim - $xoff + $nchunks - 1;
248 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
250 for ($i = 0; $i <= $this->lcs; $i++)
251 $ymids[$i][$chunk - 1] = $this->seq[$i];
253 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $chunk) / $nchunks);
254 for (; $x < $x1; $x++) {
255 $line = $flip ? $this->yv[$x] : $this->xv[$x];
256 if (empty($ymatches[$line]))
258 $matches = $ymatches[$line];
260 while (list ($junk, $y) = each($matches))
261 if (empty($this->in_seq[$y])) {
262 $k = $this->_lcs_pos($y);
264 $ymids[$k] = $ymids[$k - 1];
267 while (list ($junk, $y) = each($matches)) {
268 if ($y > $this->seq[$k - 1]) {
269 assert($y < $this->seq[$k]);
270 // Optimization: this is a common case:
271 // next match is just replacing previous match.
272 $this->in_seq[$this->seq[$k]] = false;
274 $this->in_seq[$y] = 1;
275 } elseif (empty($this->in_seq[$y])) {
276 $k = $this->_lcs_pos($y);
278 $ymids[$k] = $ymids[$k - 1];
284 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
285 $ymid = $ymids[$this->lcs];
286 for ($n = 0; $n < $nchunks - 1; $n++) {
287 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
289 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
291 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
293 return array($this->lcs, $seps);
296 function _lcs_pos($ypos)
299 if ($end == 0 || $ypos > $this->seq[$end]) {
300 $this->seq[++$this->lcs] = $ypos;
301 $this->in_seq[$ypos] = 1;
306 while ($beg < $end) {
307 $mid = (int)(($beg + $end) / 2);
308 if ($ypos > $this->seq[$mid])
314 assert($ypos != $this->seq[$end]);
316 $this->in_seq[$this->seq[$end]] = false;
317 $this->seq[$end] = $ypos;
318 $this->in_seq[$ypos] = 1;
322 /* Find LCS of two sequences.
324 * The results are recorded in the vectors $this->{x,y}changed[], by
325 * storing a 1 in the element for each line that is an insertion
326 * or deletion (ie. is not in the LCS).
328 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
330 * Note that XLIM, YLIM are exclusive bounds.
331 * All line numbers are origin-0 and discarded lines are not counted.
333 function _compareseq($xoff, $xlim, $yoff, $ylim)
335 // Slide down the bottom initial diagonal.
336 while ($xoff < $xlim && $yoff < $ylim
337 && $this->xv[$xoff] == $this->yv[$yoff]) {
342 // Slide up the top initial diagonal.
343 while ($xlim > $xoff && $ylim > $yoff
344 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
349 if ($xoff == $xlim || $yoff == $ylim)
352 // This is ad hoc but seems to work well.
353 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
354 //$nchunks = max(2,min(8,(int)$nchunks));
355 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
357 = $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks);
361 // X and Y sequences have no common subsequence:
363 while ($yoff < $ylim)
364 $this->ychanged[$this->yind[$yoff++]] = 1;
365 while ($xoff < $xlim)
366 $this->xchanged[$this->xind[$xoff++]] = 1;
368 // Use the partitions to split this problem into subproblems.
371 while ($pt2 = next($seps)) {
372 $this->_compareseq($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
378 /* Adjust inserts/deletes of identical lines to join changes
379 * as much as possible.
381 * We do something when a run of changed lines include a
382 * line at one end and has an excluded, identical line at the other.
383 * We are free to choose which identical line is included.
384 * `compareseq' usually chooses the one at the beginning,
385 * but usually it is cleaner to consider the following identical line
386 * to be the "change".
388 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
390 function _shift_boundaries($lines, &$changed, $other_changed)
395 assert('sizeof($lines) == sizeof($changed)');
396 $len = sizeof($lines);
397 $other_len = sizeof($other_changed);
401 * Scan forwards to find beginning of another run of changes.
402 * Also keep track of the corresponding point in the other file.
404 * Throughout this code, $i and $j are adjusted together so that
405 * the first $i elements of $changed and the first $j elements
406 * of $other_changed both contain the same number of zeros
408 * Furthermore, $j is always kept so that $j == $other_len or
409 * $other_changed[$j] == false.
411 while ($j < $other_len && $other_changed[$j])
414 while ($i < $len && !$changed[$i]) {
415 assert('$j < $other_len && ! $other_changed[$j]');
418 while ($j < $other_len && $other_changed[$j])
427 // Find the end of this run of changes.
428 while (++$i < $len && $changed[$i])
433 * Record the length of this run of changes, so that
434 * we can later determine whether the run has grown.
436 $runlength = $i - $start;
439 * Move the changed region back, so long as the
440 * previous unchanged line matches the last changed one.
441 * This merges with previous changed regions.
443 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
444 $changed[--$start] = 1;
445 $changed[--$i] = false;
446 while ($start > 0 && $changed[$start - 1])
449 while ($other_changed[--$j])
451 assert('$j >= 0 && !$other_changed[$j]');
455 * Set CORRESPONDING to the end of the changed run, at the last
456 * point where it corresponds to a changed run in the other file.
457 * CORRESPONDING == LEN means no such point has been found.
459 $corresponding = $j < $other_len ? $i : $len;
462 * Move the changed region forward, so long as the
463 * first changed line matches the following unchanged one.
464 * This merges with following changed regions.
465 * Do this second, so that if there are no merges,
466 * the changed region is moved forward as far as possible.
468 while ($i < $len && $lines[$start] == $lines[$i]) {
469 $changed[$start++] = false;
471 while ($i < $len && $changed[$i])
474 assert('$j < $other_len && ! $other_changed[$j]');
476 if ($j < $other_len && $other_changed[$j]) {
478 while ($j < $other_len && $other_changed[$j])
482 } while ($runlength != $i - $start);
485 * If possible, move the fully-merged run of changes
486 * back to a corresponding run in the other file.
488 while ($corresponding < $i) {
489 $changed[--$start] = 1;
492 while ($other_changed[--$j])
494 assert('$j >= 0 && !$other_changed[$j]');
501 * Class representing a 'diff' between two sequences of strings.
509 * Computes diff between sequences of strings.
511 * @param $from_lines array An array of strings.
512 * (Typically these are lines from a file.)
513 * @param $to_lines array An array of strings.
515 function Diff($from_lines, $to_lines)
517 $eng = new _DiffEngine;
518 $this->edits = $eng->diff($from_lines, $to_lines);
519 //$this->_check($from_lines, $to_lines);
523 * Compute reversed Diff.
527 * $diff = new Diff($lines1, $lines2);
528 * $rev = $diff->reverse();
529 * @return object A Diff object representing the inverse of the
535 $rev->edits = array();
536 foreach ($this->edits as $edit) {
537 $rev->edits[] = $edit->reverse();
543 * Check for empty diff.
545 * @return bool True iff two sequences were identical.
549 foreach ($this->edits as $edit) {
550 if ($edit->type != 'copy')
557 * Compute the length of the Longest Common Subsequence (LCS).
559 * This is mostly for diagnostic purposed.
561 * @return int The length of the LCS.
566 foreach ($this->edits as $edit) {
567 if ($edit->type == 'copy')
568 $lcs += sizeof($edit->orig);
574 * Get the original set of lines.
576 * This reconstructs the $from_lines parameter passed to the
579 * @return array The original sequence of strings.
585 foreach ($this->edits as $edit) {
587 array_splice($lines, sizeof($lines), 0, $edit->orig);
593 * Get the final set of lines.
595 * This reconstructs the $to_lines parameter passed to the
598 * @return array The sequence of strings.
604 foreach ($this->edits as $edit) {
606 array_splice($lines, sizeof($lines), 0, $edit->final);
612 * Check a Diff for validity.
614 * This is here only for debugging purposes.
616 function _check($from_lines, $to_lines)
618 if (serialize($from_lines) != serialize($this->orig()))
619 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
620 if (serialize($to_lines) != serialize($this->_final()))
621 trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
623 $rev = $this->reverse();
624 if (serialize($to_lines) != serialize($rev->orig()))
625 trigger_error("Reversed original doesn't match", E_USER_ERROR);
626 if (serialize($from_lines) != serialize($rev->_final()))
627 trigger_error("Reversed final doesn't match", E_USER_ERROR);
630 foreach ($this->edits as $edit) {
631 if ($prevtype == $edit->type)
632 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
633 $prevtype = $edit->type;
637 trigger_error("Diff okay: LCS = $lcs", E_USER_NOTICE);
650 * Computes diff between sequences of strings.
652 * This can be used to compute things like
653 * case-insensitve diffs, or diffs which ignore
654 * changes in white-space.
656 * @param $from_lines array An array of strings.
657 * (Typically these are lines from a file.)
659 * @param $to_lines array An array of strings.
661 * @param $mapped_from_lines array This array should
662 * have the same size number of elements as $from_lines.
663 * The elements in $mapped_from_lines and
664 * $mapped_to_lines are what is actually compared
665 * when computing the diff.
667 * @param $mapped_to_lines array This array should
668 * have the same number of elements as $to_lines.
670 function MappedDiff($from_lines, $to_lines,
671 $mapped_from_lines, $mapped_to_lines)
674 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
675 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
677 $this->Diff($mapped_from_lines, $mapped_to_lines);
680 // Optimizing loop invariants:
681 // http://phplens.com/lens/php-book/optimizing-debugging-php.php
682 for ($i = 0, $max = sizeof($this->edits); $i < $max; $i++) {
683 $orig = &$this->edits[$i]->orig;
684 if (is_array($orig)) {
685 $orig = array_slice($from_lines, $xi, sizeof($orig));
686 $xi += sizeof($orig);
689 $final = &$this->edits[$i]->final;
690 if (is_array($final)) {
691 $final = array_slice($to_lines, $yi, sizeof($final));
692 $yi += sizeof($final);
699 * A class to format Diffs
701 * This class formats the diff in classic diff format.
702 * It is intended that this class be customized via inheritance,
703 * to obtain fancier outputs.
708 * Number of leading context "lines" to preserve.
710 * This should be left at zero for this class, but subclasses
711 * may want to set this to other values.
713 public $leading_context_lines = 0;
716 * Number of trailing context "lines" to preserve.
718 * This should be left at zero for this class, but subclasses
719 * may want to set this to other values.
721 public $trailing_context_lines = 0;
726 * @param $diff object A Diff object.
727 * @return string The formatted output.
729 function format($diff)
736 $nlead = $this->leading_context_lines;
737 $ntrail = $this->trailing_context_lines;
739 $this->_start_diff();
741 foreach ($diff->edits as $edit) {
742 if ($edit->type == 'copy') {
743 if (is_array($block)) {
744 if (sizeof($edit->orig) <= $nlead + $ntrail) {
748 $context = array_slice($edit->orig, 0, $ntrail);
749 $block[] = new _DiffOp_Copy($context);
751 $this->_block($x0, $ntrail + $xi - $x0,
752 $y0, $ntrail + $yi - $y0,
757 $context = $edit->orig;
759 if (!is_array($block)) {
760 $context = array_slice($context, max(0, sizeof($context) - $nlead));
761 $x0 = $xi - sizeof($context);
762 $y0 = $yi - sizeof($context);
765 $block[] = new _DiffOp_Copy($context);
771 $xi += sizeof($edit->orig);
773 $yi += sizeof($edit->final);
776 if (is_array($block))
777 $this->_block($x0, $xi - $x0,
781 return $this->_end_diff();
784 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits)
786 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
787 foreach ($edits as $edit) {
788 if ($edit->type == 'copy')
789 $this->_context($edit->orig);
790 elseif ($edit->type == 'add')
791 $this->_added($edit->final); elseif ($edit->type == 'delete')
792 $this->_deleted($edit->orig); elseif ($edit->type == 'change')
793 $this->_changed($edit->orig, $edit->final); else
794 trigger_error("Unknown edit type", E_USER_ERROR);
799 function _start_diff()
806 $val = ob_get_contents();
811 function _block_header($xbeg, $xlen, $ybeg, $ylen)
814 $xbeg .= "," . ($xbeg + $xlen - 1);
816 $ybeg .= "," . ($ybeg + $ylen - 1);
818 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
821 function _start_block($header)
826 function _end_block()
830 function _lines($lines, $prefix = ' ')
832 foreach ($lines as $line)
833 echo "$prefix $line\n";
836 function _context($lines)
838 $this->_lines($lines);
841 function _added($lines)
843 $this->_lines($lines, ">");
846 function _deleted($lines)
848 $this->_lines($lines, "<");
851 function _changed($orig, $final)
853 $this->_deleted($orig);
855 $this->_added($final);
860 * "Unified" diff formatter.
862 * This class formats the diff in classic "unified diff" format.
864 class UnifiedDiffFormatter extends DiffFormatter
866 function UnifiedDiffFormatter($context_lines = 4)
868 $this->leading_context_lines = $context_lines;
869 $this->trailing_context_lines = $context_lines;
872 function _block_header($xbeg, $xlen, $ybeg, $ylen)
875 $xbeg .= "," . $xlen;
877 $ybeg .= "," . $ylen;
878 return "@@ -$xbeg +$ybeg @@\n";
881 function _added($lines)
883 $this->_lines($lines, "+");
886 function _deleted($lines)
888 $this->_lines($lines, "-");
891 function _changed($orig, $final)
893 $this->_deleted($orig);
894 $this->_added($final);
899 * block conflict diff formatter.
901 * This class will format a diff identical to Diff3 (i.e. editpage
902 * conflicts), but when there are only two source files. To be used by
903 * future enhancements to reloading / upgrading pgsrc.
905 * Functional but not finished yet, need to eliminate redundant block
906 * suffixes (i.e. "=======" immediately followed by another prefix)
907 * see class LoadFileConflictPageEditor
909 class BlockDiffFormatter extends DiffFormatter
911 function BlockDiffFormatter($context_lines = 4)
913 $this->leading_context_lines = $context_lines;
914 $this->trailing_context_lines = $context_lines;
917 function _lines($lines, $prefix = '')
921 foreach ($lines as $line)
927 function _added($lines)
929 $this->_lines($lines, ">>>>>>>");
932 function _deleted($lines)
934 $this->_lines($lines, "<<<<<<<");
937 function _block_header($xbeg, $xlen, $ybeg, $ylen)
942 function _changed($orig, $final)
944 $this->_deleted($orig);
945 $this->_added($final);
953 // c-hanging-comment-ender-p: nil
954 // indent-tabs-mode: nil