Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
74e6f0c1c4c2bf193c140229df4bb2bd1f83afff
[simgrid.git] / tools / tesh / tesh.pl
1 #! /usr/bin/env perl
2
3 # Copyright (c) 2012-2014. The SimGrid Team.
4 # All rights reserved.
5
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the license (GNU LGPL) which comes with this package.
8 eval 'exec perl -S $0 ${1+"$@"}'
9   if $running_under_some_shell;
10
11 =encoding UTF-8
12
13 =head1 NAME
14
15 tesh -- testing shell
16
17 =head1 SYNOPSIS
18
19 B<tesh> [I<options>] I<tesh_file>
20
21 =cut
22 my($bindir)=".";
23 my($srcdir)=".";
24 my($timeout)=0;
25 my($time_to_wait)=0;
26 my $path = $0;
27 my $enable_coverage=0;
28 my $diff_tool=0;
29 my $diff_tool_tmp_fh=0;
30 my $diff_tool_tmp_filename=0;
31 my $sort_prefix = -1;
32 my $tesh_file;
33 my $tesh_name;
34 my $error=0;
35 my $exitcode=0;
36 my @bg_cmds;
37 my (%environ);
38 $SIG{'PIPE'} = 'IGNORE';
39 $path =~ s|[^/]*$||;
40 push @INC,$path;
41
42 use Getopt::Long qw(GetOptions);
43 use strict;
44 use Term::ANSIColor;
45 use Text::ParseWords;
46 use IPC::Open3;
47 use IO::File;
48
49 ## 
50 ## Portability bits for windows
51 ##
52
53 use constant RUNNING_ON_WINDOWS => ($^O =~ /^(?:mswin|dos|os2)/oi);
54 use POSIX qw(:sys_wait_h WIFEXITED WIFSIGNALED WIFSTOPPED WEXITSTATUS WTERMSIG WSTOPSIG
55              :signal_h SIGINT SIGTERM SIGKILL SIGABRT SIGSEGV);
56 # These are not implemented on windows (see bug 6798 and 6470)
57 BEGIN {
58     if (RUNNING_ON_WINDOWS) {
59         *WIFEXITED   = sub { not $_[0] & 127 };
60         *WEXITSTATUS = sub { $_[0] >> 8 };
61         *WIFSIGNALED = sub { ($_[0] & 127) && ($_[0] & 127 != 127) };
62         *WTERMSIG    = sub { $_[0] & 127 };
63     }
64 }
65
66
67 ##
68 ## Command line option handling
69 ##
70
71 sub var_subst {
72     my ($text, $name, $value) = @_;
73     if ($value) {
74         $text =~ s/\${$name(?::[=-][^}]*)?}/$value/g;
75         $text =~ s/\$$name(\W|$)/$value$1/g;
76     }
77     else {
78         $text =~ s/\${$name:=([^}]*)}/$1/g;
79         $text =~ s/\${$name}//g;
80         $text =~ s/\$$name(\W|$)/$1/g;
81     }
82     return $text;
83 }
84
85 # option handling helper subs
86 sub cd_cmd {
87     my $directory=$_[1];
88     my $failure=1;
89     if (-e $directory && -d $directory) {
90         chdir("$directory");
91         print "[Tesh/INFO] change directory to $directory\n";
92         $failure=0;
93     } elsif (-e $directory) {
94         print "Cannot change directory to '$directory': it is not a directory\n";
95     } else {
96         print "Chdir to $directory failed: No such file or directory\n";
97     }
98     if($failure==1){
99         $error=1;
100         $exitcode=4;
101         print "Test suite `$tesh_file': NOK (system error)\n";
102         exit 4;
103     }
104 }
105
106 sub setenv_cmd {
107   my($var,$ctn);
108   if ($_[0] =~ /^(.*)=(.*)$/) {
109     ($var,$ctn)=($1,$2);
110   }elsif ($_[1] =~ /^(.*)=(.*)$/) {
111     ($var,$ctn)=($1,$2);
112   } else {
113       die "[Tesh/CRITICAL] Malformed argument to setenv: expected 'name=value' but got '$_[1]'\n";
114   }
115
116   print "[Tesh/INFO] setenv $var=$ctn\n";
117   $environ{$var} = $ctn;
118 }
119
120 # Main option parsing sub
121
122 sub get_options {
123   # remove the tesh file from the ARGV used
124   my @ARGV = @_;
125   $tesh_file = pop @ARGV;
126
127   # temporary arrays for GetOption
128   my @verbose = ();
129   my @cfg;
130   my $log; # ignored
131
132
133   my %opt = (
134     "help"  => 0,
135     "debug"   => 0,
136     "verbose" => 0
137     );
138
139   Getopt::Long::config('bundling', 'no_getopt_compat', 'no_auto_abbrev');
140
141   GetOptions(
142     'help|h'   => \$opt{'help'},
143
144     'verbose|v'  => \@verbose,
145     'debug|d'  => \$opt{"debug"},
146
147     'difftool=s' => \$diff_tool,
148
149     'cd=s'     => \&cd_cmd,
150     'timeout=s'  => \$opt{'timeout'},
151     'setenv=s'   => \&setenv_cmd,
152     'cfg=s'    => \@cfg,
153     'log=s'    => \$log,
154     'enable-coverage+'  => \$enable_coverage,
155     );
156
157   if($enable_coverage){
158     print "Enable coverage\n";
159   }
160
161   if($diff_tool){
162     use File::Temp qw/ tempfile /;
163     ($diff_tool_tmp_fh, $diff_tool_tmp_filename) = tempfile();
164     print "New tesh: $diff_tool_tmp_filename\n";
165   }
166
167   unless($tesh_file=~/(.*)\.tesh/){
168     $tesh_file="(stdin)";
169     $tesh_name="(stdin)";
170     print "Test suite from stdin\n";
171   }else{
172     $tesh_name=$1;
173     print "Test suite `$tesh_name'\n";
174   }
175
176   $opt{'verbose'} = scalar @verbose;
177   foreach (@cfg) {
178     $opt{'cfg'} .= " --cfg=$_";
179   }
180   return %opt;
181 }
182
183 my %opts = get_options(@ARGV);
184
185 ##
186 ## File parsing
187 ##
188 my($nb_arg)=0;
189 my($old_buffer);
190 my($linebis);
191 my($SIGABRT)=0;
192 my($verbose)=0;
193 my($return)=-1;
194 my($pid);
195 my($result);
196 my($result_err);
197 my($forked);
198 my($config)="";
199 my($tesh_command)=0;
200 my(@buffer_tesh)=();
201
202 ###########################################################################
203
204 sub exit_status {
205     my $status = shift;
206     if (WIFEXITED($status)) {
207         $exitcode=WEXITSTATUS($status)+40;
208         return "returned code ".WEXITSTATUS($status);
209     } elsif (WIFSIGNALED($status)) {
210         my $code;
211         if (WTERMSIG($status) == SIGINT){$code="SIGINT"; }
212         elsif  (WTERMSIG($status) == SIGTERM) {$code="SIGTERM"; }
213         elsif  (WTERMSIG($status) == SIGKILL) {$code= "SIGKILL"; }
214         elsif  (WTERMSIG($status) == SIGABRT) {$code="SIGABRT"; }
215         elsif  (WTERMSIG($status) == SIGSEGV) {$code="SIGSEGV" ;}
216         $exitcode=WTERMSIG($status)+4;
217         return "got signal $code";
218     }
219     return "Unparsable status. Is the process stopped?";
220 }
221
222 sub exec_cmd {
223   my %cmd = %{$_[0]};
224   if ($opts{'debug'}) {
225     print "IN BEGIN\n";
226     map {print "  $_"} @{$cmd{'in'}};
227     print "IN END\n";
228     print "OUT BEGIN\n";
229     map {print "  $_"} @{$cmd{'out'}};
230     print "OUT END\n";
231     print "CMD: $cmd{'cmd'}\n";
232   }
233
234   # cleanup the command line
235   if(RUNNING_ON_WINDOWS) {
236       var_subst($cmd{'cmd'}, "EXEEXT", ".exe");
237   } else {
238       var_subst($cmd{'cmd'}, "EXEEXT", "");
239   }
240
241   # substitute environ variables
242   foreach my $key (keys %environ) {
243       $cmd{'cmd'} = var_subst($cmd{'cmd'}, $key, $environ{$key});
244   }
245   # substitute remaining variables, if any
246   while ($cmd{'cmd'} =~ /\${(\w+)(?::[=-][^}]*)?}/) {
247       $cmd{'cmd'} = var_subst($cmd{'cmd'}, $1, "");
248   }
249   while ($cmd{'cmd'} =~ /\$(\w+)/) {
250       $cmd{'cmd'} = var_subst($cmd{'cmd'}, $1, "");
251   }
252
253   # add cfg options
254   $cmd{'cmd'} .= " $opts{'cfg'}" if (defined($opts{'cfg'}) && length($opts{'cfg'}));
255
256   # final cleanup
257   $cmd{'cmd'} =~ s/^\s+//;
258   $cmd{'cmd'} =~ s/\s+$//;
259
260   print "[$tesh_name:$cmd{'line'}] $cmd{'cmd'}\n" ;
261
262   ###
263   # exec the command line
264   ###  $line =~ s/\r//g;
265
266   $cmd{'got'} = IO::File->new_tmpfile;
267   $cmd{'got'}->autoflush(1);
268   local *E = $cmd{'got'};
269   $cmd{'pid'} = open3(\*CHILD_IN,  ">&E",  ">&E",
270                       quotewords('\s+', 0, $cmd{'cmd'}));
271
272   # push all provided input to executing child
273   map { print CHILD_IN "$_\n"; }  @{$cmd{'in'}};
274   close CHILD_IN;
275
276   # if timeout specified, fork and kill executing child at the end of timeout
277   if (defined($cmd{'timeout'}) or defined($opts{'timeout'})){
278     $time_to_wait= defined($cmd{'timeout'}) ? $cmd{'timeout'} : $opts{'timeout'};
279     $forked = fork();
280     $timeout=-1;
281     die "fork() failed: $!" unless defined $forked;
282     if ( $forked == 0 ) { # child
283       sleep $time_to_wait;
284 #      if (RUNNING_ON_WINDOWS) {
285 #         system("TASKKILL /F /T /PID $cmd{'pid'}"); 
286 #          # /F: Forcefully
287 #         # /T: Tree kill
288 #         # /PID: poor soul
289 #      } else {
290           kill('TERM', $cmd{'pid'});
291           sleep 1;
292           kill('KILL', $cmd{'pid'});
293 #      }
294       exit $time_to_wait;
295     }
296   }
297
298
299   # Cleanup the executing child, and kill the timeouter brother on need
300   $cmd{'return'} = 0 unless defined($cmd{'return'});
301   if($cmd{'background'} != 1){
302     waitpid ($cmd{'pid'}, 0);
303     $cmd{'gotret'} = exit_status($?);
304     parse_out(\%cmd);
305   }else{
306     # & commands, which will be handled at the end
307     push @bg_cmds, \%cmd;
308     # no timeout for background commands
309     if($forked){
310        kill(SIGKILL, $forked);
311        $timeout=0;
312        $forked=0;
313     }
314   }
315 }
316
317
318 sub parse_out {
319   my %cmd = %{$_[0]};
320   my $gotret=$cmd{'gotret'};
321
322   my $wantret;
323
324   if(defined($cmd{'expect'}) and ($cmd{'expect'} ne "")){
325     $wantret = "got signal $cmd{'expect'}";
326   }else{
327     $wantret = "returned code ".(defined($cmd{'return'})? $cmd{'return'} : 0);
328   }
329
330   local *got = $cmd{'got'};
331   seek(got,0,0);
332   # pop all output from executing child
333   my @got;
334   while(defined(my $got=<got>)) {
335     $got =~ s/\r//g;
336     chomp $got;
337     print $diff_tool_tmp_fh "> $got\n" if ($diff_tool);
338
339     if (!($enable_coverage and $got=~ /^profiling:/)){
340       push @got, $got;
341     }
342   }
343
344   if ($cmd{'sort'}){
345     # Save the unsorted observed output to report it on error.
346     map { push @{$cmd{'unsorted got'}}, $_ } @got;
347
348     sub mysort{
349         substr($a, 0, $sort_prefix) cmp substr($b, 0, $sort_prefix)
350     }
351     use sort 'stable';
352     if ($sort_prefix>0) {
353         @got = sort mysort @got;
354     } else {
355         @got = sort @got;
356     }       
357     while (@got and $got[0] eq "") {
358       shift @got;
359     }
360
361     # Sort the expected output to make it easier to write for humans
362     if(defined($cmd{'out'})){
363       if ($sort_prefix>0) {
364           @{$cmd{'out'}} = sort mysort @{$cmd{'out'}};
365       } else {
366           @{$cmd{'out'}} = sort @{$cmd{'out'}};
367       }
368       while (@{$cmd{'out'}} and ${$cmd{'out'}}[0] eq "") {
369         shift @{$cmd{'out'}};
370       }
371     }
372   }
373
374   # Did we timeout ? If yes, handle it. If not, kill the forked process.
375
376   if($timeout==-1 and ($gotret eq "got signal SIGTERM" or $gotret eq "got signal SIGKILL")){
377     $gotret="return code 0";
378     $timeout=1;
379     $gotret= "timeout after $time_to_wait sec";
380     $error=1;
381     $exitcode=3;
382     print STDERR "<$cmd{'file'}:$cmd{'line'}> timeouted. Kill the process.\n";
383   }else{
384     $timeout=0;
385   }
386   if($gotret ne $wantret) {
387     $error=1;
388     my $msg = "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> $gotret)\n";
389     if ($timeout!=1) {
390         $msg=$msg."Output of <$cmd{'file'}:$cmd{'line'}> so far:\n";
391     }
392     map {$msg .=  "|| $_\n"} @got;
393     if(!@got) {
394         if($timeout==1){
395         print STDERR "<$cmd{'file'}:$cmd{'line'}> No output before timeout\n";
396         }else{
397         $msg .= "||\n";
398         }
399     }
400     $timeout = 0;
401     print STDERR "$msg";
402   }
403
404
405   ###
406   # Check the result of execution
407   ###
408   my $diff;
409   if (defined($cmd{'output display'})){
410     print "[Tesh/INFO] Here is the (ignored) command output:\n";
411     map { print "||$_\n" } @got;
412   }
413   elsif (!defined($cmd{'output ignore'})){
414     $diff = build_diff(\@{$cmd{'out'}}, \@got);
415   }else{
416     print "(ignoring the output of <$cmd{'file'}:$cmd{'line'}> as requested)\n"
417   }
418   if (length $diff) {
419     print "Output of <$cmd{'file'}:$cmd{'line'}> mismatch".($cmd{'sort'}?" (even after sorting)":"").":\n";
420     map { print "$_\n" } split(/\n/,$diff);
421     if ($cmd{'sort'}) {
422         print "WARNING: Both the observed output and expected output were sorted as requested.\n";
423         print "WARNING: Output were only sorted using the $sort_prefix first chars.\n"
424           if ($sort_prefix>0);
425         print "WARNING: Use <! output sort 19> to sort by simulated date and process ID only.\n";
426         # print "----8<---------------  Begin of unprocessed observed output (as it should appear in file):\n";
427         # map {print "> $_\n"} @{$cmd{'unsorted got'}};
428         # print "--------------->8----  End of the unprocessed observed output.\n";
429     }
430
431     print "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> output mismatch)\n";
432     $error=1;
433     $exitcode=2;
434   }
435 }
436
437 sub mkfile_cmd {
438   my %cmd = %{$_[0]};
439   my $file = $cmd{'arg'};
440   print "[Tesh/INFO] mkfile $file\n";
441
442   unlink($file);
443   open(FILE,">$file") or die "[Tesh/CRITICAL] Unable to create file $file: $!\n";
444   print FILE join("\n", @{$cmd{'in'}});
445   print FILE "\n" if (scalar @{$cmd{'in'}} > 0);
446   close(FILE);
447 }
448
449 # parse tesh file
450 #my $teshfile=$tesh_file;
451 #$teshfile=~ s{\.[^.]+$}{};
452
453 unless($tesh_file eq "(stdin)"){
454   open TESH_FILE, $tesh_file or die "[Tesh/CRITICAL] Unable to open $tesh_file $!\n";
455 }
456
457 my %cmd; # everything about the next command to run
458 my $line_num=0;
459 my $finished =0;
460 LINE: while (not $finished and not $error) {
461   my $line;
462
463
464   if ($tesh_file ne "(stdin)" and !defined($line=<TESH_FILE>)){
465     $finished=1;
466     next LINE;
467   }elsif ($tesh_file eq "(stdin)" and !defined($line=<>)){
468     $finished=1;
469     next LINE;
470   }
471
472   $line_num++;
473   chomp $line;
474   $line =~ s/\r//g;
475   print "[TESH/debug] $line_num: $line\n" if $opts{'debug'};
476   my $next;
477   # deal with line continuations
478   while ($line =~ /^(.*?)\\$/) {
479     $next=<TESH_FILE>;
480     die "[TESH/CRITICAL] Continued line at end of file\n"
481       unless defined($next);
482     $line_num++;
483     chomp $next;
484     print "[TESH/debug] $line_num: $next\n" if $opts{'debug'};
485     $line = $1.$next;
486   }
487
488   # Push delayed commands on empty lines
489   unless ($line =~ m/^(.)(.*)$/) {
490     if (defined($cmd{'cmd'}))  {
491       exec_cmd(\%cmd);
492       %cmd = ();
493     }
494     print $diff_tool_tmp_fh "$line\n" if ($diff_tool);
495     next LINE;
496   }
497
498   my ($cmd,$arg) = ($1,$2);
499   print $diff_tool_tmp_fh "$line\n" if ($diff_tool and $cmd ne '>');
500   $arg =~ s/^ //g;
501   $arg =~ s/\r//g;
502   $arg =~ s/\\\\/\\/g;
503   # handle the commands
504   if ($cmd =~ /^#/) {    #comment
505   } elsif ($cmd eq '>'){    #expected result line
506     print "[TESH/debug] push expected result\n" if $opts{'debug'};
507     push @{$cmd{'out'}}, $arg;
508
509   } elsif ($cmd eq '<') {    # provided input
510     print "[TESH/debug] push provided input\n" if $opts{'debug'};
511     push @{$cmd{'in'}}, $arg;
512
513   } elsif ($cmd eq 'p') {    # comment
514     print "[$tesh_name:$line_num] $arg\n";
515
516   } elsif ($cmd eq '$') {  # Command
517     # if we have something buffered, run it now
518     if (defined($cmd{'cmd'})) {
519       exec_cmd(\%cmd);
520       %cmd = ();
521     }
522     if ($arg =~ /^\s*mkfile /){      # "mkfile" command line
523       die "[TESH/CRITICAL] Output expected from mkfile command!\n" if scalar @{cmd{'out'}};
524
525       $cmd{'arg'} = $arg;
526       $cmd{'arg'} =~ s/\s*mkfile //;
527       mkfile_cmd(\%cmd);
528       %cmd = ();
529
530     } elsif ($arg =~ /^\s*cd /) {
531       die "[TESH/CRITICAL] Input provided to cd command!\n" if scalar @{cmd{'in'}};
532       die "[TESH/CRITICAL] Output expected from cd command!\n" if scalar @{cmd{'out'}};
533
534       $arg =~ s/^ *cd //;
535       cd_cmd("",$arg);
536       %cmd = ();
537
538     } else { # regular command
539       $cmd{'cmd'} = $arg;
540       $cmd{'file'} = $tesh_file;
541       $cmd{'line'} = $line_num;
542     }
543   }
544   elsif($cmd eq '&'){      # parallel command line
545
546     if (defined($cmd{'cmd'})) {
547       exec_cmd(\%cmd);
548       %cmd = ();
549     }
550     $cmd{'background'} = 1;
551     $cmd{'cmd'} = $arg;
552     $cmd{'file'} = $tesh_file;
553     $cmd{'line'} = $line_num;
554   }
555   elsif($line =~ /^!\s*output sort/){    #output sort
556     if (defined($cmd{'cmd'})) {
557       exec_cmd(\%cmd);
558       %cmd = ();
559     }
560     $cmd{'sort'} = 1;
561     if ($line =~ /^!\s*output sort\s+(\d+)/) {
562         $sort_prefix = $1;
563     }
564   }
565   elsif($line =~ /^!\s*output ignore/){    #output ignore
566     if (defined($cmd{'cmd'})) {
567       exec_cmd(\%cmd);
568       %cmd = ();
569     }
570     $cmd{'output ignore'} = 1;
571   }
572   elsif($line =~ /^!\s*output display/){    #output display
573     if (defined($cmd{'cmd'})) {
574       exec_cmd(\%cmd);
575       %cmd = ();
576     }
577     $cmd{'output display'} = 1;
578   }
579   elsif($line =~ /^!\s*expect signal (\w*)/) {#expect signal SIGABRT
580     if (defined($cmd{'cmd'})) {
581       exec_cmd(\%cmd);
582       %cmd = ();
583     }
584 print "hey\n";
585     $cmd{'expect'} = "$1";
586   }
587   elsif($line =~ /^!\s*expect return/){    #expect return
588     if (defined($cmd{'cmd'})) {
589       exec_cmd(\%cmd);
590       %cmd = ();
591     }
592     $line =~ s/^! expect return //g;
593     $line =~ s/\r//g;
594     $cmd{'return'} = $line;
595   }
596   elsif($line =~ /^!\s*setenv/){    #setenv
597     if (defined($cmd{'cmd'})) {
598       exec_cmd(\%cmd);
599       %cmd = ();
600     }
601     $line =~ s/^! setenv //g;
602     $line =~ s/\r//g;
603     setenv_cmd($line);
604   }
605   elsif($line =~ /^!\s*include/){    #include
606     if (defined($cmd{'cmd'})) {
607       exec_cmd(\%cmd);
608       %cmd = ();
609     }
610     print color("red"), "[Tesh/CRITICAL] need include";
611     print color("reset"), "\n";
612     die;
613   }
614   elsif($line =~ /^!\s*timeout/){    #timeout
615     if (defined($cmd{'cmd'})) {
616       exec_cmd(\%cmd);
617       %cmd = ();
618     }
619     $line =~ s/^! timeout //;
620     $line =~ s/\r//g;
621     $cmd{'timeout'} = $line;
622   } else {
623     die "[TESH/CRITICAL] parse error: $line\n";
624   }
625   if($forked){
626    kill(SIGKILL, $forked);
627    $timeout=0;
628   }
629
630 }
631
632
633
634 # Deal with last command
635 if (defined($cmd{'cmd'})) {
636   exec_cmd(\%cmd);
637   %cmd = ();
638 }
639
640
641 if($forked){
642    kill(SIGKILL, $forked);
643    $timeout=0;
644 }
645
646 foreach(@bg_cmds){
647   my %test=%{$_};
648   waitpid ($test{'pid'}, 0);
649   $test{'gotret'} = exit_status($?);
650   parse_out(\%test);
651 }
652
653 @bg_cmds=();
654
655 if ($diff_tool) {
656   close $diff_tool_tmp_fh;
657   system("$diff_tool $diff_tool_tmp_filename $tesh_file");
658   unlink $diff_tool_tmp_filename;
659 }
660
661 if($error !=0){
662     exit $exitcode;
663 }elsif($tesh_file eq "(stdin)"){
664     print "Test suite from stdin OK\n";
665 }else{
666     print "Test suite `$tesh_name' OK\n";
667 }
668
669 #my (@a,@b);
670 #push @a,"bl1";   push @b,"bl1";
671 #push @a,"bl2";   push @b,"bl2";
672 #push @a,"bl3";   push @b,"bl3";
673 #push @a,"bl4";   push @b,"bl4";
674 #push @a,"bl5";   push @b,"bl5";
675 #push @a,"bl6";   push @b,"bl6";
676 #push @a,"bl7";   push @b,"bl7";
677 ##push @a,"Perl";  push @b,"ruby";
678 #push @a,"END1";   push @b,"END1";
679 #push @a,"END2";   push @b,"END2";
680 #push @a,"END3";   push @b,"END3";
681 #push @a,"END4";   push @b,"END4";
682 #push @a,"END5";   push @b,"END5";
683 #push @a,"END6";   push @b,"END6";
684 #push @a,"END7";   push @b,"END7";
685 #print "Identical:\n". build_diff(\@a,\@b);
686
687 #@a = (); @b =();
688 #push @a,"AZE"; push @b,"EZA";
689 #print "Different:\n".build_diff(\@a,\@b);
690
691 use lib "@CMAKE_BINARY_DIR@/bin" ;
692
693 use Diff qw(diff); # postpone a bit to have time to change INC
694
695 sub build_diff {
696   my $res;
697   my $diff = Diff->new(@_);
698
699   $diff->Base( 1 );   # Return line numbers, not indices
700   my $chunk_count = $diff->Next(-1); # Compute the amount of chuncks
701   return ""   if ($chunk_count == 1 && $diff->Same());
702   $diff->Reset();
703   while(  $diff->Next()  ) {
704     my @same = $diff->Same();
705     if ($diff->Same() ) {
706       if ($diff->Next(0) > 1) { # not first chunk: print 2 first lines
707         $res .= '  '.$same[0]."\n" ;
708         $res .= '  '.$same[1]."\n" if (scalar @same>1);
709       }
710       $res .= "...\n"  if (scalar @same>2);
711 #    $res .= $diff->Next(0)."/$chunk_count\n";
712       if ($diff->Next(0) < $chunk_count) { # not last chunk: print 2 last lines
713         $res .= '  '.$same[scalar @same -2]."\n" if (scalar @same>1);
714         $res .= '  '.$same[scalar @same -1]."\n";
715       }
716     }
717     next if  $diff->Same();
718     map { $res .= "- $_\n" } $diff->Items(1);
719     map { $res .= "+ $_\n" } $diff->Items(2);
720   }
721   return $res;
722 }
723
724