blib/lib/Algorithm/diffnew.pl untested

filter: Statementstmt 0.0% 0 / 288 Branchbran 0.0% 0 / 98 Conditioncond 0.0% 0 / 37 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 461 SCAR 67.7
CC
29
Cov
0%
new
90.0
output_old_diff
30.0
output_ed_diff
30.0
CRAP 870.0
1 #!/usr/bin/perl
2 #
3 # `Diff' program in Perl
4 # Copyright 1998 M-J. Dominus. (mjd-perl-diff@plover.com)
5 #
6 # This program is free software; you can redistribute it and/or modify it
7 # under the same terms as Perl itself.
8 #
9 # Altered to output in `context diff' format (but without context)
10 # September 1998 Christian Murphy (cpm@muc.de)
11 #
12 # Context lines feature added
13 # Unified, "Old" (Standard UNIX), Ed diff added September 1998
14 # Reverse_Ed (-f option) added March 1999
15 # Amir D. Karger (karger@bead.aecom.yu.edu)
16 #
17 # Modular functions integrated into program
18 # February 1999 M-J. Dominus (mjd-perl-diff@plover.com)
19 #
20 # In this file, "item" usually means "line of text", and "item number" usually
21 # means "line number". But theoretically the code could be used more generally
22 use strict;
23 use Algorithm::Diff qw(diff);
24  
25 # GLOBAL VARIABLES ####
26 # After we've read up to a certain point in each file, the number of items
27 # we've read from each file will differ by $FLD (could be 0)
28 my $File_Length_Difference = 0;
29  
30 #ed diff outputs hunks *backwards*, so we need to save hunks when doing ed diff
31 my @Ed_Hunks = ();
32 ########################
33  
34 my $usage = << "ENDUSAGE";
35 Usage: $0 [{-c | -C lines -e | -f | -u | -U lines |-q | -i | -w}] oldfile newfile
36 -c do a context diff with 3 lines of context
37 -C do a context diff with 'lines' lines of context (implies -c)
38 -e create a script for the ed editor to change oldfile to newfile
39 -f like -e but in reverse order
40 -u do a unified diff with 3 lines of context
41 -U do a unified diff with 'lines' lines of context (implies -u)
42 -q report only whether or not the files differ
43 -i ignore differences in Upper/lower-case
44 -w ignore differences in white-space (space and TAB characters)
45  
46 By default it will do an "old-style" diff, with output like UNIX diff
47 ENDUSAGE
48  
49 my $Context_Lines = 0; # lines of context to print. 0 for old-style diff
50 my $Diff_Type = "OLD"; # by default, do standard UNIX diff
51 my ($opt_c, $opt_u, $opt_e, $opt_f, $opt_q, $opt_i, $opt_w);
52 my $compareRoutineRef = undef;
53 while ($ARGV[0] =~ /^-/) {
54 my $opt = shift;
55 last if $opt eq '--';
56 if ($opt =~ /^-C(.*)/) {
57 $Context_Lines = $1 || shift;
58 $opt_c = 1;
59 $Diff_Type = "CONTEXT";
60 } elsif ($opt =~ /^-c$/) {
61 $Context_Lines = 3;
62 $opt_c = 1;
63 $Diff_Type = "CONTEXT";
64 } elsif ($opt =~ /^-e$/) {
65 $opt_e = 1;
66 $Diff_Type = "ED";
67 } elsif ($opt =~ /^-f$/) {
68 $opt_f = 1;
69 $Diff_Type = "REVERSE_ED";
70 } elsif ($opt =~ /^-U(.*)$/) {
71 $Context_Lines = $1 || shift;
72 $opt_u = 1;
73 $Diff_Type = "UNIFIED";
74 } elsif ($opt =~ /^-u$/) {
75 $Context_Lines = 3;
76 $opt_u = 1;
77 $Diff_Type = "UNIFIED";
78 } elsif ($opt =~ /^-q$/) {
79 $Context_Lines = 0;
80 $opt_q = 1;
81 $opt_e = 1;
82 $Diff_Type = "ED";
83 } elsif ($opt =~ /^-i$/) {
84 $opt_i = 1;
85 $compareRoutineRef = \&compareRoutine;
86 } elsif ($opt =~ /^-w$/) {
87 $opt_w = 1;
88 $compareRoutineRef = \&compareRoutine;
89 } else {
90 $opt =~ s/^-//;
91 bag("Illegal option -- $opt");
92 }
93 }
94  
95 if ($opt_q and grep($_,($opt_c, $opt_f, $opt_u)) > 1) {
96 bag("Combining -q with other options is nonsensical");
97 }
98  
99 if (grep($_,($opt_c, $opt_e, $opt_f, $opt_u)) > 1) {
100 bag("Only one of -c, -u, -f, -e are allowed");
101 }
102  
103 bag($usage) unless @ARGV == 2;
104  
105 ######## DO THE DIFF!
106 my ($file1, $file2) = @ARGV;
107  
108 my ($char1, $char2); # string to print before file names
109 if ($Diff_Type eq "CONTEXT") {
110 $char1 = '*' x 3; $char2 = '-' x 3;
111 } elsif ($Diff_Type eq "UNIFIED") {
112 $char1 = '-' x 3; $char2 = '+' x 3;
113 }
114  
115 open (F1, $file1) or bag("Couldn't open $file1: $!");
116 open (F2, $file2) or bag("Couldn't open $file2: $!");
117 my (@f1, @f2);
118 chomp(@f1 = <F1>);
119 close F1;
120 chomp(@f2 = <F2>);
121 close F2;
122  
123 # diff yields lots of pieces, each of which is basically a Block object
124 my $diffs = diff(\@f1, \@f2, $compareRoutineRef);
125 exit 0 unless @$diffs;
126  
127 if ($opt_q and @$diffs) {
128 print "Files $file1 and $file2 differ\n";
129 exit 1;
130 }
131  
132 if ($Diff_Type =~ /UNIFIED|CONTEXT/) {
133 my @st = stat($file1);
134 my $MTIME = 9;
135 print "$char1 $file1\t", scalar localtime($st[$MTIME]), "\n";
136 @st = stat($file2);
137 print "$char2 $file2\t", scalar localtime($st[$MTIME]), "\n";
138 }
139  
140 my ($hunk,$oldhunk);
141 # Loop over hunks. If a hunk overlaps with the last hunk, join them.
142 # Otherwise, print out the old one.
143 foreach my $piece (@$diffs) {
144 $hunk = new Hunk ($piece, $Context_Lines);
145 next unless $oldhunk; # first time through
146  
147 # Don't need to check for overlap if blocks have no context lines
148 if ($Context_Lines && $hunk->does_overlap($oldhunk)) {
149 $hunk->prepend_hunk($oldhunk);
150 } else {
151 $oldhunk->output_diff(\@f1, \@f2, $Diff_Type);
152 }
153  
154 } continue {
155 $oldhunk = $hunk;
156 }
157  
158 # print the last hunk
159 $oldhunk->output_diff(\@f1, \@f2, $Diff_Type);
160  
161 # Print hunks backwards if we're doing an ed diff
162 map {$_->output_ed_diff(\@f1, \@f2, $Diff_Type)} @Ed_Hunks if @Ed_Hunks;
163  
164 exit 1;
165 # END MAIN PROGRAM
166  
167 sub bag {
168 my $msg = shift;
169 $msg .= "\n";
170 warn $msg;
171 exit 2;
172 }
173  
174 sub compareRoutine {
175 my $line = shift;
176 $line =~ s/[ \t\r\n]+//g if ($opt_w);
177 $line = uc( $line ) if ($opt_i);
178 return $line;
179 }
180  
181 ########
182 # Package Hunk. A Hunk is a group of Blocks which overlap because of the
183 # context surrounding each block. (So if we're not using context, every
184 # hunk will contain one block.)
185 {
186 package Hunk;
187  
188 sub new {
189 # Arg1 is output from &LCS::diff (which corresponds to one Block)
190 # Arg2 is the number of items (lines, e.g.,) of context around each block
191 #
192 # This subroutine changes $File_Length_Difference
193 #
194 # Fields in a Hunk:
195 # blocks - a list of Block objects
196 # start - index in file 1 where first block of the hunk starts
197 # end - index in file 1 where last block of the hunk ends
198 #
199 # Variables:
200 # before_diff - how much longer file 2 is than file 1 due to all hunks
201 # until but NOT including this one
202 # after_diff - difference due to all hunks including this one
203 my ($class, $piece, $context_items) = @_;
204  
205 my $block = new Block ($piece); # this modifies $FLD!
206  
207 my $before_diff = $File_Length_Difference; # BEFORE this hunk
208 my $after_diff = $before_diff + $block->{"length_diff"};
209 $File_Length_Difference += $block->{"length_diff"};
210  
211 # @remove_array and @insert_array hold the items to insert and remove
212 # Save the start & beginning of each array. If the array doesn't exist
213 # though (e.g., we're only adding items in this block), then figure
214 # out the line number based on the line number of the other file and
215 # the current difference in file lenghts
216 my @remove_array = $block->remove;
217 my @insert_array = $block->insert;
218 my ($a1, $a2, $b1, $b2, $start1, $start2, $end1, $end2);
219 $a1 = @remove_array ? $remove_array[0 ]->{"item_no"} : -1;
220 $a2 = @remove_array ? $remove_array[-1]->{"item_no"} : -1;
221 $b1 = @insert_array ? $insert_array[0 ]->{"item_no"} : -1;
222 $b2 = @insert_array ? $insert_array[-1]->{"item_no"} : -1;
223  
224 $start1 = $a1 == -1 ? $b1 - $before_diff : $a1;
225 $end1 = $a2 == -1 ? $b2 - $after_diff : $a2;
226 $start2 = $b1 == -1 ? $a1 + $before_diff : $b1;
227 $end2 = $b2 == -1 ? $a2 + $after_diff : $b2;
228  
229 # At first, a hunk will have just one Block in it
230 my $hunk = {
231 "start1" => $start1,
232 "start2" => $start2,
233 "end1" => $end1,
234 "end2" => $end2,
235 "blocks" => [$block],
236 };
237 bless $hunk, $class;
238  
239 $hunk->flag_context($context_items);
240  
241 return $hunk;
242 }
243  
244 # Change the "start" and "end" fields to note that context should be added
245 # to this hunk
246 sub flag_context {
247 my ($hunk, $context_items) = @_;
248 return unless $context_items; # no context
249  
250 # add context before
251 my $start1 = $hunk->{"start1"};
252 my $num_added = $context_items > $start1 ? $start1 : $context_items;
253 $hunk->{"start1"} -= $num_added;
254 $hunk->{"start2"} -= $num_added;
255  
256 # context after
257 my $end1 = $hunk->{"end1"};
258 $num_added = ($end1+$context_items > $#f1) ?
259 $#f1 - $end1 :
260 $context_items;
261 $hunk->{"end1"} += $num_added;
262 $hunk->{"end2"} += $num_added;
263 }
264  
265 # Is there an overlap between hunk arg0 and old hunk arg1?
266 # Note: if end of old hunk is one less than beginning of second, they overlap
267 sub does_overlap {
268 my ($hunk, $oldhunk) = @_;
269 return "" unless $oldhunk; # first time through, $oldhunk is empty
270  
271 # Do I actually need to test both?
272 return ($hunk->{"start1"} - $oldhunk->{"end1"} <= 1 ||
273 $hunk->{"start2"} - $oldhunk->{"end2"} <= 1);
274 }
275  
276 # Prepend hunk arg1 to hunk arg0
277 # Note that arg1 isn't updated! Only arg0 is.
278 sub prepend_hunk {
279 my ($hunk, $oldhunk) = @_;
280  
281 $hunk->{"start1"} = $oldhunk->{"start1"};
282 $hunk->{"start2"} = $oldhunk->{"start2"};
283  
284 unshift (@{$hunk->{"blocks"}}, @{$oldhunk->{"blocks"}});
285 }
286  
287  
288 # DIFF OUTPUT ROUTINES. THESE ROUTINES CONTAIN DIFF FORMATTING INFO...
289 sub output_diff {
290 # First arg is the current hunk of course
291 # Next args are refs to the files
292 # last arg is type of diff
293 my $diff_type = $_[-1];
294 my %funchash = ("OLD" => \&output_old_diff,
295 "CONTEXT" => \&output_context_diff,
296 "ED" => \&store_ed_diff,
297 "REVERSE_ED" => \&output_ed_diff,
298 "UNIFIED" => \&output_unified_diff,
299 );
300 if (exists $funchash{$diff_type}) {
301 &{$funchash{$diff_type}}(@_); # pass in all args
302 } else {die "unknown diff type $diff_type"}
303 }
304  
305 sub output_old_diff {
306 # Note that an old diff can't have any context. Therefore, we know that
307 # there's only one block in the hunk.
308 my ($hunk, $fileref1, $fileref2) = @_;
309 my %op_hash = ('+' => 'a', '-' => 'd', '!' => 'c');
310  
311 my @blocklist = @{$hunk->{"blocks"}};
312 warn ("Expecting one block in an old diff hunk!") if scalar @blocklist != 1;
313 my $block = $blocklist[0];
314 my $op = $block->op; # +, -, or !
315  
316 # Calculate item number range.
317 # old diff range is just like a context diff range, except the ranges
318 # are on one line with the action between them.
319 my $range1 = $hunk->context_range(1);
320 my $range2 = $hunk->context_range(2);
321 my $action = $op_hash{$op} || warn "unknown op $op";
322 print "$range1$action$range2\n";
323  
324 # If removing anything, just print out all the remove lines in the hunk
325 # which is just all the remove lines in the block
326 if ($block->remove) {
327 my @outlist = @$fileref1[$hunk->{"start1"}..$hunk->{"end1"}];
328 map {$_ = "< $_\n"} @outlist; # all lines will be '< text\n'
329 print @outlist;
330 }
331  
332 print "---\n" if $op eq '!'; # only if inserting and removing
333 if ($block->insert) {
334 my @outlist = @$fileref2[$hunk->{"start2"}..$hunk->{"end2"}];
335 map {$_ = "> $_\n"} @outlist; # all lines will be '> text\n'
336 print @outlist;
337 }
338 }
339  
340 sub output_unified_diff {
341 my ($hunk, $fileref1, $fileref2) = @_;
342 my @blocklist;
343  
344 # Calculate item number range.
345 my $range1 = $hunk->unified_range(1);
346 my $range2 = $hunk->unified_range(2);
347 print "@@ -$range1 +$range2 @@\n";
348  
349 # Outlist starts containing the hunk of file 1.
350 # Removing an item just means putting a '-' in front of it.
351 # Inserting an item requires getting it from file2 and splicing it in.
352 # We splice in $num_added items. Remove blocks use $num_added because
353 # splicing changed the length of outlist.
354 # We remove $num_removed items. Insert blocks use $num_removed because
355 # their item numbers---corresponding to positions in file *2*--- don't take
356 # removed items into account.
357 my $low = $hunk->{"start1"};
358 my $hi = $hunk->{"end1"};
359 my ($num_added, $num_removed) = (0,0);
360 my @outlist = @$fileref1[$low..$hi];
361 map {s/^/ /} @outlist; # assume it's just context
362  
363 foreach my $block (@{$hunk->{"blocks"}}) {
364 foreach my $item ($block->remove) {
365 my $op = $item->{"sign"}; # -
366 my $offset = $item->{"item_no"} - $low + $num_added;
367 $outlist[$offset] =~ s/^ /$op/;
368 $num_removed++;
369 }
370 foreach my $item ($block->insert) {
371 my $op = $item->{"sign"}; # +
372 my $i = $item->{"item_no"};
373 my $offset = $i - $hunk->{"start2"} + $num_removed;
374 splice(@outlist,$offset,0,"$op$$fileref2[$i]");
375 $num_added++;
376 }
377 }
378  
379 map {s/$/\n/} @outlist; # add \n's
380 print @outlist;
381  
382 }
383  
384 sub output_context_diff {
385 my ($hunk, $fileref1, $fileref2) = @_;
386 my @blocklist;
387  
388 print "***************\n";
389 # Calculate item number range.
390 my $range1 = $hunk->context_range(1);
391 my $range2 = $hunk->context_range(2);
392  
393 # Print out file 1 part for each block in context diff format if there are
394 # any blocks that remove items
395 print "*** $range1 ****\n";
396 my $low = $hunk->{"start1"};
397 my $hi = $hunk->{"end1"};
398 if (@blocklist = grep {$_->remove} @{$hunk->{"blocks"}}) {
399 my @outlist = @$fileref1[$low..$hi];
400 map {s/^/ /} @outlist; # assume it's just context
401 foreach my $block (@blocklist) {
402 my $op = $block->op; # - or !
403 foreach my $item ($block->remove) {
404 $outlist[$item->{"item_no"} - $low] =~ s/^ /$op/;
405 }
406 }
407 map {s/$/\n/} @outlist; # add \n's
408 print @outlist;
409 }
410  
411 print "--- $range2 ----\n";
412 $low = $hunk->{"start2"};
413 $hi = $hunk->{"end2"};
414 if (@blocklist = grep {$_->insert} @{$hunk->{"blocks"}}) {
415 my @outlist = @$fileref2[$low..$hi];
416 map {s/^/ /} @outlist; # assume it's just context
417 foreach my $block (@blocklist) {
418 my $op = $block->op; # + or !
419 foreach my $item ($block->insert) {
420 $outlist[$item->{"item_no"} - $low] =~ s/^ /$op/;
421 }
422 }
423 map {s/$/\n/} @outlist; # add \n's
424 print @outlist;
425 }
426 }
427  
428 sub store_ed_diff {
429 # ed diff prints out diffs *backwards*. So save them while we're generating
430 # them, then print them out at the end
431 my $hunk = shift;
432 unshift @Ed_Hunks, $hunk;
433 }
434  
435 sub output_ed_diff {
436 # This sub is used for ed ('diff -e') OR reverse_ed ('diff -f').
437 # last arg is type of diff
438 my $diff_type = $_[-1];
439 my ($hunk, $fileref1, $fileref2) = @_;
440 my %op_hash = ('+' => 'a', '-' => 'd', '!' => 'c');
441  
442 # Can't be any context for this kind of diff, so each hunk has one block
443 my @blocklist = @{$hunk->{"blocks"}};
444 warn ("Expecting one block in an ed diff hunk!") if scalar @blocklist != 1;
445 my $block = $blocklist[0];
446 my $op = $block->op; # +, -, or !
447  
448 # Calculate item number range.
449 # old diff range is just like a context diff range, except the ranges
450 # are on one line with the action between them.
451 my $range1 = $hunk->context_range(1);
452 $range1 =~ s/,/ / if $diff_type eq "REVERSE_ED";
453 my $action = $op_hash{$op} || warn "unknown op $op";
454 print ($diff_type eq "ED" ? "$range1$action\n" : "$action$range1\n");
455  
456 if ($block->insert) {
457 my @outlist = @$fileref2[$hunk->{"start2"}..$hunk->{"end2"}];
458 map {s/$/\n/} @outlist; # add \n's
459 print @outlist;
460 print ".\n"; # end of ed 'c' or 'a' command
461 }
462 }
463  
464 sub context_range {
465 # Generate a range of item numbers to print. Only print 1 number if the range
466 # has only one item in it. Otherwise, it's 'start,end'
467 # Flag is the number of the file (1 or 2)
468 my ($hunk, $flag) = @_;
469 my ($start, $end) = ($hunk->{"start$flag"},$hunk->{"end$flag"});
470 $start++; $end++; # index from 1, not zero
471 my $range = ($start < $end) ? "$start,$end" : $end;
472 return $range;
473 }
474  
475 sub unified_range {
476 # Generate a range of item numbers to print for unified diff
477 # Print number where block starts, followed by number of lines in the block
478 # (don't print number of lines if it's 1)
479 my ($hunk, $flag) = @_;
480 my ($start, $end) = ($hunk->{"start$flag"},$hunk->{"end$flag"});
481 $start++; $end++; # index from 1, not zero
482 my $length = $end - $start + 1;
483 my $first = $length < 2 ? $end : $start; # strange, but correct...
484 my $range = $length== 1 ? $first : "$first,$length";
485 return $range;
486 }
487 } # end Package Hunk
488  
489 ########
490 # Package Block. A block is an operation removing, adding, or changing
491 # a group of items. Basically, this is just a list of changes, where each
492 # change adds or deletes a single item.
493 # (Change could be a separate class, but it didn't seem worth it)
494 {
495 package Block;
496 sub new {
497 # Input is a chunk from &Algorithm::LCS::diff
498 # Fields in a block:
499 # length_diff - how much longer file 2 is than file 1 due to this block
500 # Each change has:
501 # sign - '+' for insert, '-' for remove
502 # item_no - number of the item in the file (e.g., line number)
503 # We don't bother storing the text of the item
504 #
505 my ($class,$chunk) = @_;
506 my @changes = ();
507  
508 # This just turns each change into a hash.
509 foreach my $item (@$chunk) {
510 my ($sign, $item_no, $text) = @$item;
511 my $hashref = {"sign" => $sign, "item_no" => $item_no};
512 push @changes, $hashref;
513 }
514  
515 my $block = { "changes" => \@changes };
516 bless $block, $class;
517  
518 $block->{"length_diff"} = $block->insert - $block->remove;
519 return $block;
520 }
521  
522  
523 # LOW LEVEL FUNCTIONS
524 sub op {
525 # what kind of block is this?
526 my $block = shift;
527 my $insert = $block->insert;
528 my $remove = $block->remove;
529  
530 $remove && $insert and return '!';
531 $remove and return '-';
532 $insert and return '+';
533 warn "unknown block type";
534 return '^'; # context block
535 }
536  
537 # Returns a list of the changes in this block that remove items
538 # (or the number of removals if called in scalar context)
539 sub remove { return grep {$_->{"sign"} eq '-'} @{shift->{"changes"}}; }
540  
541 # Returns a list of the changes in this block that insert items
542 sub insert { return grep {$_->{"sign"} eq '+'} @{shift->{"changes"}}; }
543  
544 } # end of package Block