forked from briandfoy/PerlPowerTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiff
executable file
·789 lines (652 loc) · 22.3 KB
/
diff
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
#!/usr/bin/perl
=begin metadata
Name: diff
Description: compute 'intelligent' differences between two files
Author: Mark-Jason Dominus, mjd-perl-diff@plover.com
Author: Christian Murphy, cpm@muc.de
Author: Amir D. Karger, karger@bead.aecom.yu.edu
License: perl
=end metadata
=cut
#
# `Diff' program in Perl
# Copyright 1998 M-J. Dominus. (mjd-perl-diff@plover.com)
#
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
#
# Altered to output in `context diff' format (but without context)
# September 1998 Christian Murphy (cpm@muc.de)
#
# Context lines feature added
# Unified, "Old" (Standard UNIX), Ed diff added September 1998
# Reverse_Ed (-f option) added March 1999
# Amir D. Karger (karger@bead.aecom.yu.edu)
#
# Modular functions integrated into program
# February 1999 M-J. Dominus (mjd-perl-diff@plover.com)
#
# In this file, "item" usually means "line of text", and "item number" usually
# means "line number". But theoretically the code could be used more generally
use strict;
use File::Basename qw(basename);
use File::Spec;
use Getopt::Std qw(getopts);
use constant EX_SUCCESS => 0;
use constant EX_DIFFERENT => 1;
use constant EX_FAILURE => 2;
use vars qw($opt_C $opt_c $opt_e $opt_f $opt_q $opt_s $opt_U $opt_u);
# GLOBAL VARIABLES ####
# After we've read up to a certain point in each file, the number of items
# we've read from each file will differ by $FLD (could be 0)
my $File_Length_Difference = 0;
my $Program = basename($0);
#ed diff outputs hunks *backwards*, so we need to save hunks when doing ed diff
my @Ed_Hunks = ();
########################
sub usage {
warn << "ENDUSAGE";
Usage: $Program [-c | -C lines | -e | -f | -q | -s | -u | -U lines] oldfile newfile
-c do a context diff with 3 lines of context
-C do a context diff with 'lines' lines of context (implies -c)
-e create a script for the ed editor to change oldfile to newfile
-f like -e but in reverse order
-u do a unified diff with 3 lines of context
-U do a unified diff with 'lines' lines of context (implies -u)
-q show a message when the files differ, instead of the difference
-s show a message when the files are identical
ENDUSAGE
exit EX_FAILURE;
}
my $Context_Lines = 0; # lines of context to print. 0 for old-style diff
my $Diff_Type = "OLD"; # by default, do standard UNIX diff
getopts('C:cefqsU:u') or usage();
if (defined $opt_C) {
$Context_Lines = checklen($opt_C);
set_diff_type('CONTEXT');
} elsif ($opt_c) {
$Context_Lines = 3;
set_diff_type('CONTEXT');
}
if ($opt_e) {
set_diff_type('ED');
}
if ($opt_f) {
set_diff_type('REVERSE_ED');
}
if (defined $opt_U) {
$Context_Lines = checklen($opt_U);
set_diff_type('UNIFIED');
} elsif ($opt_u) {
$Context_Lines = 3;
set_diff_type('UNIFIED');
}
if (scalar(@ARGV) < 2) {
warn "$Program: missing argument\n";
usage();
} elsif (scalar(@ARGV) > 2) {
warn "$Program: extra argument: '$ARGV[2]'\n";
usage();
}
######## DO THE DIFF!
my ($char1, $char2); # string to print before file names
if ($Diff_Type eq "CONTEXT") {
$char1 = '*' x 3; $char2 = '-' x 3;
} elsif ($Diff_Type eq "UNIFIED") {
$char1 = '-' x 3; $char2 = '+' x 3;
}
my ($file1, $file2) = @ARGV;
my ($fh1, $fh2);
if ($file1 eq '-') {
exit(EX_SUCCESS) if ($file2 eq '-');
bag("cannot compare '-' to a directory") if (-d $file2);
$fh1 = *STDIN;
} elsif (-d $file1) {
bag("cannot compare '-' to a directory") if ($file2 eq '-');
bag("'$file2': is a directory") if (-d $file2);
my $path = File::Spec->catfile($file1, basename($file2));
open($fh1, '<', $path) or bag("Couldn't open '$path': $!");
} else {
open($fh1, '<', $file1) or bag("Couldn't open '$file1': $!");
}
if ($file2 eq '-') {
$fh2 = *STDIN;
} elsif (-d $file2) {
bag("'$file1': is a directory") if (-d $file1);
my $path = File::Spec->catfile($file2, basename($file1));
open($fh2, '<', $path) or bag("Couldn't open '$path': $!");
} else {
open($fh2, '<', $file2) or bag("Couldn't open '$file2': $!");
}
my (@f1, @f2);
chomp(@f1 = <$fh1>);
close $fh1;
chomp(@f2 = <$fh2>);
close $fh2;
identical() if (scalar(@f1) == 0 && scalar(@f2) == 0);
# diff yields lots of pieces, each of which is basically a Block object
my $diffs = Algorithm::Diff::diff(\@f1, \@f2);
identical() unless @$diffs;
if ($opt_q) {
print "Files $file1 and $file2 differ\n";
exit EX_DIFFERENT;
}
if ($Diff_Type =~ /UNIFIED|CONTEXT/) {
my @st = stat($file1);
my $MTIME = 9;
print "$char1 $file1\t", scalar localtime($st[$MTIME]), "\n";
@st = stat($file2);
print "$char2 $file2\t", scalar localtime($st[$MTIME]), "\n";
}
my ($hunk,$oldhunk);
# Loop over hunks. If a hunk overlaps with the last hunk, join them.
# Otherwise, print out the old one.
foreach my $piece (@$diffs) {
$hunk = Hunk->new($piece, $Context_Lines);
next unless $oldhunk; # first time through
# Don't need to check for overlap if blocks have no context lines
if ($Context_Lines && $hunk->does_overlap($oldhunk)) {
$hunk->prepend_hunk($oldhunk);
} else {
$oldhunk->output_diff(\@f1, \@f2, $Diff_Type);
}
} continue {
$oldhunk = $hunk;
}
# print the last hunk
$oldhunk->output_diff(\@f1, \@f2, $Diff_Type);
# Print hunks backwards if we're doing an ed diff
if ($Diff_Type eq 'ED') {
foreach $hunk (@Ed_Hunks) {
$hunk->output_ed_diff(\@f1, \@f2, 'ED');
}
}
exit EX_DIFFERENT;
# END MAIN PROGRAM
sub identical {
print "Files $file1 and $file2 are identical\n" if $opt_s;
exit EX_SUCCESS;
}
sub bag {
my $msg = shift;
warn "$Program: $msg\n";
exit EX_FAILURE;
}
sub checklen {
my $n = shift;
return int($n) if ($n =~ m/\A[0-9]+\Z/);
warn "$Program: invalid context length '$n'\n";
usage();
}
sub set_diff_type {
my $val = shift;
if ($Diff_Type ne 'OLD') {
warn "$Program: incompatible diff type options\n";
usage();
}
$Diff_Type = $val;
}
########
# Package Hunk. A Hunk is a group of Blocks which overlap because of the
# context surrounding each block. (So if we're not using context, every
# hunk will contain one block.)
{
package
Hunk; # hide from PAUSE
sub new {
# Arg1 is output from &LCS::diff (which corresponds to one Block)
# Arg2 is the number of items (lines, e.g.,) of context around each block
#
# This subroutine changes $File_Length_Difference
#
# Fields in a Hunk:
# blocks - a list of Block objects
# start - index in file 1 where first block of the hunk starts
# end - index in file 1 where last block of the hunk ends
#
# Variables:
# before_diff - how much longer file 2 is than file 1 due to all hunks
# until but NOT including this one
# after_diff - difference due to all hunks including this one
my ($class, $piece, $context_items) = @_;
my $block = Block->new($piece); # this modifies $FLD!
my $before_diff = $File_Length_Difference; # BEFORE this hunk
my $after_diff = $before_diff + $block->{"length_diff"};
$File_Length_Difference += $block->{"length_diff"};
# @remove_array and @insert_array hold the items to insert and remove
# Save the start & beginning of each array. If the array doesn't exist
# though (e.g., we're only adding items in this block), then figure
# out the line number based on the line number of the other file and
# the current difference in file lenghts
my @remove_array = $block->remove;
my @insert_array = $block->insert;
my ($a1, $a2, $b1, $b2, $start1, $start2, $end1, $end2);
$a1 = @remove_array ? $remove_array[0 ]->{"item_no"} : -1;
$a2 = @remove_array ? $remove_array[-1]->{"item_no"} : -1;
$b1 = @insert_array ? $insert_array[0 ]->{"item_no"} : -1;
$b2 = @insert_array ? $insert_array[-1]->{"item_no"} : -1;
$start1 = $a1 == -1 ? $b1 - $before_diff : $a1;
$end1 = $a2 == -1 ? $b2 - $after_diff : $a2;
$start2 = $b1 == -1 ? $a1 + $before_diff : $b1;
$end2 = $b2 == -1 ? $a2 + $after_diff : $b2;
# At first, a hunk will have just one Block in it
my $hunk = {
"start1" => $start1,
"start2" => $start2,
"end1" => $end1,
"end2" => $end2,
"blocks" => [$block],
};
bless $hunk, $class;
$hunk->flag_context($context_items);
return $hunk;
}
# Change the "start" and "end" fields to note that context should be added
# to this hunk
sub flag_context {
my ($hunk, $context_items) = @_;
return unless $context_items; # no context
# add context before
my $start1 = $hunk->{"start1"};
my $num_added = $context_items > $start1 ? $start1 : $context_items;
$hunk->{"start1"} -= $num_added;
$hunk->{"start2"} -= $num_added;
# context after
my $end1 = $hunk->{"end1"};
$num_added = ($end1+$context_items > $#f1) ?
$#f1 - $end1 :
$context_items;
$hunk->{"end1"} += $num_added;
$hunk->{"end2"} += $num_added;
}
# Is there an overlap between hunk arg0 and old hunk arg1?
# Note: if end of old hunk is one less than beginning of second, they overlap
sub does_overlap {
my ($hunk, $oldhunk) = @_;
return "" unless $oldhunk; # first time through, $oldhunk is empty
# Do I actually need to test both?
return ($hunk->{"start1"} - $oldhunk->{"end1"} <= 1 ||
$hunk->{"start2"} - $oldhunk->{"end2"} <= 1);
}
# Prepend hunk arg1 to hunk arg0
# Note that arg1 isn't updated! Only arg0 is.
sub prepend_hunk {
my ($hunk, $oldhunk) = @_;
$hunk->{"start1"} = $oldhunk->{"start1"};
$hunk->{"start2"} = $oldhunk->{"start2"};
unshift (@{$hunk->{"blocks"}}, @{$oldhunk->{"blocks"}});
}
# DIFF OUTPUT ROUTINES. THESE ROUTINES CONTAIN DIFF FORMATTING INFO...
sub output_diff {
# First arg is the current hunk of course
# Next args are refs to the files
# last arg is type of diff
my $diff_type = $_[-1];
my %funchash = ("OLD" => \&output_old_diff,
"CONTEXT" => \&output_context_diff,
"ED" => \&store_ed_diff,
"REVERSE_ED" => \&output_ed_diff,
"UNIFIED" => \&output_unified_diff,
);
my $func = $funchash{$diff_type} or die "unknown diff type '$diff_type'\n";
$func->(@_);
}
sub output_old_diff {
# Note that an old diff can't have any context. Therefore, we know that
# there's only one block in the hunk.
my ($hunk, $fileref1, $fileref2) = @_;
my %op_hash = ('+' => 'a', '-' => 'd', '!' => 'c');
my @blocklist = @{$hunk->{"blocks"}};
warn ("Expecting one block in an old diff hunk!") if scalar @blocklist != 1;
my $block = $blocklist[0];
my $op = $block->op; # +, -, or !
# Calculate item number range.
# old diff range is just like a context diff range, except the ranges
# are on one line with the action between them.
my $range1 = $hunk->context_range(1);
my $range2 = $hunk->context_range(2);
my $action = $op_hash{$op} || warn "unknown op $op";
print "$range1$action$range2\n";
# If removing anything, just print out all the remove lines in the hunk
# which is just all the remove lines in the block
if ($block->remove) {
my @outlist = @$fileref1[$hunk->{"start1"}..$hunk->{"end1"}];
map {$_ = "< $_\n"} @outlist; # all lines will be '< text\n'
print @outlist;
}
print "---\n" if $op eq '!'; # only if inserting and removing
if ($block->insert) {
my @outlist = @$fileref2[$hunk->{"start2"}..$hunk->{"end2"}];
map {$_ = "> $_\n"} @outlist; # all lines will be '> text\n'
print @outlist;
}
}
sub output_unified_diff {
my ($hunk, $fileref1, $fileref2) = @_;
my @blocklist;
# Calculate item number range.
my $range1 = $hunk->unified_range(1);
my $range2 = $hunk->unified_range(2);
print "@@ -$range1 +$range2 @@\n";
# Outlist starts containing the hunk of file 1.
# Removing an item just means putting a '-' in front of it.
# Inserting an item requires getting it from file2 and splicing it in.
# We splice in $num_added items. Remove blocks use $num_added because
# splicing changed the length of outlist.
# We remove $num_removed items. Insert blocks use $num_removed because
# their item numbers---corresponding to positions in file *2*--- don't take
# removed items into account.
my $low = $hunk->{"start1"};
my $hi = $hunk->{"end1"};
my ($num_added, $num_removed) = (0,0);
my @outlist = @$fileref1[$low..$hi];
map {s/^/ /} @outlist; # assume it's just context
foreach my $block (@{$hunk->{"blocks"}}) {
foreach my $item ($block->remove) {
my $op = $item->{"sign"}; # -
my $offset = $item->{"item_no"} - $low + $num_added;
$outlist[$offset] =~ s/^ /$op/;
$num_removed++;
}
foreach my $item ($block->insert) {
my $op = $item->{"sign"}; # +
my $i = $item->{"item_no"};
my $offset = $i - $hunk->{"start2"} + $num_removed;
splice(@outlist,$offset,0,"$op$$fileref2[$i]");
$num_added++;
}
}
map {s/$/\n/} @outlist; # add \n's
print @outlist;
}
sub output_context_diff {
my ($hunk, $fileref1, $fileref2) = @_;
my @blocklist;
print "***************\n";
# Calculate item number range.
my $range1 = $hunk->context_range(1);
my $range2 = $hunk->context_range(2);
# Print out file 1 part for each block in context diff format if there are
# any blocks that remove items
print "*** $range1 ****\n";
my $low = $hunk->{"start1"};
my $hi = $hunk->{"end1"};
if (@blocklist = grep {$_->remove} @{$hunk->{"blocks"}}) {
my @outlist = @$fileref1[$low..$hi];
map {s/^/ /} @outlist; # assume it's just context
foreach my $block (@blocklist) {
my $op = $block->op; # - or !
foreach my $item ($block->remove) {
$outlist[$item->{"item_no"} - $low] =~ s/^ /$op/;
}
}
map {s/$/\n/} @outlist; # add \n's
print @outlist;
}
print "--- $range2 ----\n";
$low = $hunk->{"start2"};
$hi = $hunk->{"end2"};
if (@blocklist = grep {$_->insert} @{$hunk->{"blocks"}}) {
my @outlist = @$fileref2[$low..$hi];
map {s/^/ /} @outlist; # assume it's just context
foreach my $block (@blocklist) {
my $op = $block->op; # + or !
foreach my $item ($block->insert) {
$outlist[$item->{"item_no"} - $low] =~ s/^ /$op/;
}
}
map {s/$/\n/} @outlist; # add \n's
print @outlist;
}
}
sub store_ed_diff {
# ed diff prints out diffs *backwards*. So save them while we're generating
# them, then print them out at the end
my $hunk = shift;
unshift @Ed_Hunks, $hunk;
}
sub output_ed_diff {
# This sub is used for ed ('diff -e') OR reverse_ed ('diff -f').
my ($hunk, $fileref1, $fileref2, $diff_type) = @_;
my %op_hash = ('+' => 'a', '-' => 'd', '!' => 'c');
# Can't be any context for this kind of diff, so each hunk has one block
my @blocklist = @{$hunk->{"blocks"}};
warn ("Expecting one block in an ed diff hunk!") if scalar @blocklist != 1;
my $block = $blocklist[0];
my $op = $block->op; # +, -, or !
my $action = $op_hash{$op} || warn "unknown op $op";
# Calculate item number range.
# old diff range is just like a context diff range, except the ranges
# are on one line with the action between them.
my $range1 = $hunk->context_range(1);
if ($diff_type eq 'REVERSE_ED') {
$range1 =~ s/,/ /;
print $action, $range1, "\n";
} else {
print $range1, $action, "\n";
}
if ($block->insert) {
my @outlist = @$fileref2[$hunk->{"start2"}..$hunk->{"end2"}];
print join("\n", @outlist), "\n.\n"; # '.' signifies end of 'c' or 'a'
}
}
sub context_range {
# Generate a range of item numbers to print. Only print 1 number if the range
# has only one item in it. Otherwise, it's 'start,end'
# Flag is the number of the file (1 or 2)
my ($hunk, $flag) = @_;
my ($start, $end) = ($hunk->{"start$flag"},$hunk->{"end$flag"});
$start++; $end++; # index from 1, not zero
my $range = ($start < $end) ? "$start,$end" : $end;
return $range;
}
sub unified_range {
# Generate a range of item numbers to print for unified diff
# Print number where block starts, followed by number of lines in the block
# (don't print number of lines if it's 1)
my ($hunk, $flag) = @_;
my ($start, $end) = ($hunk->{"start$flag"},$hunk->{"end$flag"});
$start++; $end++; # index from 1, not zero
my $length = $end - $start + 1;
my $first = $length < 2 ? $end : $start; # strange, but correct...
my $range = $length== 1 ? $first : "$first,$length";
return $range;
}
} # end Package Hunk
########
# Package Block. A block is an operation removing, adding, or changing
# a group of items. Basically, this is just a list of changes, where each
# change adds or deletes a single item.
# (Change could be a separate class, but it didn't seem worth it)
{
package
Block; # hide from PAUSE
sub new {
# Input is a chunk from &Algorithm::Diff::diff
# Fields in a block:
# length_diff - how much longer file 2 is than file 1 due to this block
# Each change has:
# sign - '+' for insert, '-' for remove
# item_no - number of the item in the file (e.g., line number)
# We don't bother storing the text of the item
#
my ($class,$chunk) = @_;
my @changes = map { {'sign' => $_->[0], 'item_no' => $_->[1]} } @$chunk;
my $block = { "changes" => \@changes };
bless $block, $class;
$block->{"length_diff"} = $block->insert - $block->remove;
return $block;
}
# LOW LEVEL FUNCTIONS
sub op {
# what kind of block is this?
my $block = shift;
my $insert = $block->insert;
my $remove = $block->remove;
$remove && $insert and return '!';
$remove and return '-';
$insert and return '+';
warn "unknown block type";
return '^'; # context block
}
# Returns a list of the changes in this block that remove items
# (or the number of removals if called in scalar context)
sub remove { return grep {$_->{"sign"} eq '-'} @{shift->{"changes"}}; }
# Returns a list of the changes in this block that insert items
sub insert { return grep {$_->{"sign"} eq '+'} @{shift->{"changes"}}; }
} # end of package Block
################################################################
################################################################
################################################################
################################################################
#
# Algorithm::Diff
# -*- perl -*-
#
# Longest Common Subsequence algorithm
# Copyright 1998 M-J. Dominus. (mjd-perl-diff@plover.com)
#
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
#
# Algorithm: See `Longest Common Subsequences', at
# http://www.ics.uci.edu/~eppstein/161/960229.html
#
# The function `LCS_matrix' constructs the matrix described by this
# reference; then `traverse sequences' traverses the graph implied by
# this matrix and invokes callback functions on each traversed matrix
# element.
#
# This used to be an RCS Id line, but it broke since I (adk) use RCS, too.
# Id: LCS.pm,v 1.7 1998/08/13 00:39:53 mjd Exp mjd ;
#
package
Algorithm::Diff; # Hide from PAUSE
use strict;
use List::Util qw(max);
our $VERSION = '0.57';
sub LCS_matrix {
my @x;
my $a; # Sequence #1
my $b; # Sequence #2
$a = shift or usage();
$b = shift or usage();
(ref $a eq 'ARRAY') or usage();
(ref $b eq 'ARRAY') or usage();
my $eq = shift;
my ($al, $bl); # Lengths of sequences
$al = @$a;
$bl = @$b;
$x[0] = [(0) x ($bl+1)];
for my $i (1 .. $al) {
my $r = $x[$i] = [ 0 ];
for my $j (1 .. $bl) {
# If the first two items are the same...
if (defined $eq
? $eq->($a->[-$i], $b->[-$j])
: $a->[-$i] eq $b->[-$j]
) {
$r->[$j] = 1 + $x[$i-1][$j-1];
} else {
$r->[$j] = max($x[$i][$j-1], $x[$i-1][$j]);
}
}
}
\@x;
}
sub traverse_sequences {
my $dispatcher = shift;
my $a = shift;
my $b = shift;
my $equal = shift;
my $x = LCS_matrix($a, $b, $equal);
my ($al, $bl) = (scalar(@$x)-1, scalar(@{$x->[0]})-1);
my ($ap, $bp) = ($al, $bl);
my $dispf;
while (1) {
$dispf = undef;
my ($ai, $bi) = ($al-$ap, $bl-$bp);
if ($ap == 0) {
$dispf = $dispatcher->{A_FINISHED} || $dispatcher->{DISCARD_B};
$bp--; # Where to put this?
} elsif ($bp == 0) {
$dispf = $dispatcher->{B_FINISHED} || $dispatcher->{DISCARD_A};
$ap--; # Where to put this?
} elsif (defined($equal)
? $equal->($a->[$ai], $b->[$bi])
: $a->[$ai] eq $b->[$bi]
) {
$dispf = $dispatcher->{MATCH};
$ap--;
$bp--;
} else {
if ($x->[$ap][$bp] == $x->[$ap-1][$bp] + 1) {
$dispf = $dispatcher->{DISCARD_B};
$bp--;
} else {
$dispf = $dispatcher->{DISCARD_A};
$ap--;
}
}
$dispf->($ai, $bi, @_) if defined $dispf;
return 1 if $ap == 0 && $bp == 0;
}
}
sub diff {
my ($a, $b) = @_;
my @cur_diff = ();
my @diffs = ();
my $functions =
{ DISCARD_A => sub {push @cur_diff, ['-', $_[0], $a->[$_[0]]]},
DISCARD_B => sub {push @cur_diff, ['+', $_[1], $b->[$_[1]]]},
MATCH => sub { push @diffs, [@cur_diff] if @cur_diff;
@cur_diff = ()
},
};
traverse_sequences($functions, @_);
push @diffs, \@cur_diff if @cur_diff;
wantarray ? @diffs : \@diffs;
}
sub usage {
require Carp;
Carp::croak("Usage: LCS([...], [...]); aborting");
}
1;
__END__
=head1 NAME
diff - compute `intelligent' differences between two files
=head1 SYNOPSIS
diff [-c | -C lines | -e | -f | -q | -s | -u | -U lines] file1 file2
=head1 DESCRIPTION
The diff command compares file1 and file2, producing a listing on
standard output describing how to convert one file to the other.
Various formats are available for representing the file changes.
By default the output is in the traditional UNIX diff format.
Two directories cannot be compared. If either file1 or file2 is a
directory, diff is applied to the non-directory file and a file of
the same name within the directory.
=head1 OPTIONS
The following options are supported.
=over 8
=item -c
Produce a context diff with 3 lines of context
=item -C NUM
Produce a context diff with NUM lines of context
=item -e
Create a script for the ed editor
=item -f
Like -e but in reverse order (output cannot be processed by ed)
=item -u
Output a unified diff with 3 lines of context
=item -U NUM
Output a unified diff with NUM lines of context
=item -q
Print a message if the input files differ instead of displaying the difference.
=item -s
Print a message if the input files are identical.
By default no output is produced in this case.
=back
=head1 AUTHOR
Mark-Jason Dominus, C<< <mjd-perl-diff@plover.com> >>.
Visit my diff/LCS web page at L<http://www.plover.com/~mjd/perl/diff/>.
=cut