Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use temporary files to store output of the command in perl tesh
[simgrid.git] / buildtools / Cmake / Scripts / tesh.pl
1 #! /usr/bin/perl
2 eval 'exec perl -S $0 ${1+"$@"}'
3   if $running_under_some_shell;
4
5 =encoding UTF-8
6
7 =head1 NAME
8
9 tesh -- testing shell
10
11 =head1 SYNOPSIS
12
13 B<tesh> [I<options>] I<tesh_file>
14
15 =cut
16 my($bindir)=".";
17 my($srcdir)=".";
18 my($timeout)=0;
19 my($time_to_wait)=0;
20 my $path = $0;
21 my $OS;
22 my $enable_coverage=0;
23 my $tesh_file;
24 my $tesh_name;
25 my $error=0;
26 my $exitcode=0;
27
28 $path =~ s|[^/]*$||;
29 push @INC,$path;
30
31 use Getopt::Long qw(GetOptions);
32 use strict;
33 use Term::ANSIColor;
34 use IPC::Open3;
35
36 if($^O eq "linux"){
37     $OS = "UNIX";
38 }
39 else{
40     $OS = "WIN";
41     $ENV{"PRINTF_EXPONENT_DIGITS"} = "2"; 
42 }
43
44
45 sub trim($)
46 {
47     my $string = shift;
48     $string =~ s/^\s+//;
49     $string =~ s/\s+$//;
50     return $string;
51 }
52
53 # make sure we received a tesh file
54 scalar @ARGV > 0 || die "Usage:\n  tesh [*options*] *tesh_file*\n";
55
56 #Add current directory to path
57 $ENV{PATH} = "$ENV{PATH}:.";
58
59 ##
60 ## Command line option handling
61 ##
62
63 # option handling helper subs
64 sub cd_cmd {
65   my $directory=$_[1];
66   my $failure=1;
67   if (-e $directory && -d $directory) {
68     chdir("$directory");
69     print "[Tesh/INFO] change directory to $directory\n";
70   $failure=0;
71   } elsif (-e $directory) {
72     print "Cannot change directory to '$directory': it is not a directory\n";
73   } else {
74     print "Chdir to $directory failed: No such file or directory\n";
75   }
76   if($failure==1){
77   $error=1;
78   $exitcode=4;
79   print "Test suite `$tesh_file': NOK (system error)\n";
80   exit 4;
81   }
82 }
83
84 sub setenv_cmd {
85   my($var,$ctn);
86   if ($_[0] =~ /^(.*)=(.*)$/) {
87     ($var,$ctn)=($1,$2);
88   }elsif ($_[1] =~ /^(.*)=(.*)$/) {
89     ($var,$ctn)=($1,$2);
90   } else { 
91       die "[Tesh/CRITICAL] Malformed argument to setenv: expected 'name=value' but got '$_[1]'\n";
92   }
93     
94     if($var =~ /bindir/){
95         print "[Tesh/INFO] setenv $var=$ctn\n";
96         $bindir = $ctn;
97     }
98     else
99     {
100         if($var =~ /srcdir/){
101             $srcdir = $ctn;
102         }
103         else{
104             $ENV{$var} = $ctn;
105             print "[Tesh/INFO] setenv $var=$ctn\n";
106         }
107     }    
108 }
109
110 # Main option parsing sub
111
112 sub get_options {
113   # remove the tesh file from the ARGV used
114   my @ARGV = @_;
115   $tesh_file = pop @ARGV;
116
117   # temporary arrays for GetOption
118   my @verbose = ();
119   my @cfg;
120   my $log; # ignored
121
122
123   my %opt = (
124     "help"  => 0,
125     "debug"   => 0,
126     "verbose" => 0
127     );
128
129   Getopt::Long::config('bundling', 'no_getopt_compat', 'no_auto_abbrev');
130   
131   GetOptions(
132     'help|h'   => \$opt{'help'},
133
134     'verbose|v'  => \@verbose,
135     'debug|d'  => \$opt{"debug"},
136
137     'cd=s'     => \&cd_cmd,
138     'timeout=s'  => \$opt{'timeout'},    
139     'setenv=s'   => \&setenv_cmd,
140     'cfg=s'    => \@cfg,
141     'log=s'    => \$log,
142     'enable-coverage+'  => \$enable_coverage,    
143     );
144
145   if($enable_coverage){
146     print "Enable coverage\n";
147   }
148
149   unless($tesh_file=~/(.*)\.tesh/){
150     $tesh_file="(stdin)";
151     $tesh_name="(stdin)";
152     print "Test suite from stdin\n";
153   }else{
154     $tesh_name=$1;
155     print "Test suite `$tesh_name'\n";
156   }
157
158   $opt{'verbose'} = scalar @verbose;
159   foreach (@cfg) {
160     $opt{'cfg'} .= " --cfg=$_";
161   }
162   return %opt;
163 }
164
165 my %opts = get_options(@ARGV);
166
167 ##
168 ## File parsing
169 ##
170 my($nb_arg)=0;
171 my($old_buffer);
172 my($linebis);
173 my($SIGABRT)=0;
174 my($verbose)=0;
175 my($return)=-1;
176 my($pid);
177 my($result);
178 my($result_err);
179 my($forked);
180 my($config)="";
181 my($tesh_command)=0;
182 my(@buffer_tesh)=();
183
184 #eval {
185   use POSIX;
186
187   sub exit_status {
188     my $status = shift;
189     if (POSIX::WIFEXITED($status)) {
190       return "returned code ".POSIX::WEXITSTATUS($status);
191     } elsif (POSIX::WIFSIGNALED($status)) {
192         my $code;
193         if (POSIX::WTERMSIG($status) == SIGINT){$code="SIGINT"; }
194         elsif  (POSIX::WTERMSIG($status) == SIGTERM) {$code="SIGTERM"; }
195         elsif  (POSIX::WTERMSIG($status) == SIGKILL) {$code= "SIGKILL"; }
196         elsif  (POSIX::WTERMSIG($status) == SIGABRT) {$code="SIGABRT"; }
197         elsif  (POSIX::WTERMSIG($status) == SIGSEGV) {$code="SIGSEGV" ;}
198         $exitcode=POSIX::WTERMSIG($status)+4;
199         return "got signal $code";
200     }
201     return "Unparsable status. Is the process stopped?";
202   }
203 #};
204 #if ($@) { # no POSIX available?
205 #  warn "POSIX not usable to parse the return value of forked child: $@\n";
206 #  sub exit_status {
207 #    return "returned code -1 $@ ";
208 #  }
209 #}
210
211 sub exec_cmd { 
212   my %cmd = %{$_[0]};
213   if ($opts{'debug'}) {
214     print "IN BEGIN\n";
215     map {print "  $_"} @{$cmd{'in'}};
216     print "IN END\n";
217     print "OUT BEGIN\n";
218     map {print "  $_"} @{$cmd{'out'}};
219     print "OUT END\n";
220     print "CMD: $cmd{'cmd'}\n";
221   }
222
223   # cleanup the command line
224   if($OS eq "WIN"){
225         $cmd{'cmd'} =~ s/\${EXEEXT:=}/.exe/g;
226         $cmd{'cmd'} =~ s/\${EXEEXT}/.exe/g;
227         $cmd{'cmd'} =~ s/\$EXEEXT/.exe/g;
228     }
229     else{
230         $cmd{'cmd'} =~ s/\${EXEEXT:=}//g;
231     }
232   $cmd{'cmd'} =~ s/\${bindir:=}/$bindir/g;
233   $cmd{'cmd'} =~ s/\${srcdir:=}/$srcdir/g;
234   $cmd{'cmd'} =~ s/\${bindir:=.}/$bindir/g;
235   $cmd{'cmd'} =~ s/\${srcdir:=.}/$srcdir/g;
236   $cmd{'cmd'} =~ s/\${bindir}/$bindir/g;
237   $cmd{'cmd'} =~ s/\${srcdir}/$srcdir/g;
238 # $cmd{'cmd'} =~ s|^\./||g;
239 #  $cmd{'cmd'} =~ s|tesh|tesh.pl|g;
240   $cmd{'cmd'} =~ s/\(%i:%P@%h\)/\\\(%i:%P@%h\\\)/g;
241   $cmd{'cmd'} .= " $opts{'cfg'}" if (defined($opts{'cfg'}) && length($opts{'cfg'}));
242
243   print "[$tesh_name:$cmd{'line'}] $cmd{'cmd'}\n" ;
244
245   ###
246   # exec the command line
247   ###  $line =~ s/\r//g;
248
249   my $e = IO::File->new_tmpfile;
250   $e->autoflush(1);
251   local *E = $e; 
252   $pid = open3(\*CHILD_IN,  ">&E",  ">&E", $cmd{'cmd'} );
253
254   # push all provided input to executing child
255   map { print CHILD_IN "$_\n" }  @{$cmd{'in'}};
256   close CHILD_IN;
257
258   # if timeout specified, fork and kill executing child at the end of timeout
259   if (defined($cmd{'timeout'}) or defined($opts{'timeout'})){
260     $time_to_wait= defined($cmd{'timeout'}) ? $cmd{'timeout'} : $opts{'timeout'};
261     $forked = fork();
262     $timeout=-1;
263     die "fork() failed: $!" unless defined $forked;
264     if ( $forked == 0 ) { # child
265       sleep $time_to_wait;
266       kill(SIGKILL, $pid);
267       exit $time_to_wait;
268     }
269   }
270
271   
272   # Cleanup the executing child, and kill the timeouter brother on need
273   $cmd{'return'} = 0 unless defined($cmd{'return'});
274   my $wantret;
275   if(defined($cmd{'expect'}) and ($cmd{'expect'} ne "")){
276     $wantret = "got signal $cmd{'expect'}";
277   }else{
278     $wantret = "returned code ".(defined($cmd{'return'})? $cmd{'return'} : 0);
279     $exitcode= 41;
280   }
281   my $gotret;
282   waitpid ($pid, 0);
283   $gotret = exit_status($?);
284
285   seek($e,0,0);
286   # pop all output from executing child
287   my @got;
288   while(defined(my $got=<$e>)) {
289     $got =~ s/\r//g;
290     $got =~ s/^( )*//g;
291     chomp $got;
292     $got=trim($got);
293     if( $got ne ""){
294         if (!($enable_coverage and $got=~ /^profiling:/)){    
295         push @got, "$got";
296      }
297   }
298   }    
299
300   if ($cmd{'sort'}){   
301     sub mysort{
302     $a cmp $b
303     }
304     use sort qw(defaults _quicksort); # force quicksort
305     @got = sort mysort @got;
306     #also resort the other one, as perl sort is not the same as the C one used to generate teshes
307     if(defined($cmd{'out'})){
308       @{$cmd{'out'}}=sort mysort @{$cmd{'out'}};
309     }
310   }
311
312   #Did we timeout ? If yes, handle it. If not, kill the forked process.
313
314   if($timeout==-1 and $gotret eq "got signal SIGKILL"){
315     $gotret="return code 0";
316     $timeout=1;
317     $gotret= "timeout after $time_to_wait sec";
318     $error=1;
319     $exitcode=3;
320     print STDERR "<$cmd{'file'}:$cmd{'line'}> timeouted. Kill the process.\n";
321   }else{
322     $timeout=0;  
323   }
324   if($gotret ne $wantret) {
325     $error=1;
326     my $msg = "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> $gotret)\n";
327     if ($timeout!=1) {
328         $msg=$msg."Output of <$cmd{'file'}:$cmd{'line'}> so far:\n";    
329     }
330     map {$msg .=  "|| $_\n"} @got;
331     if(!@got) {
332         if($timeout==1){
333         print STDERR "<$cmd{'file'}:$cmd{'line'}> No output before timeout\n";
334         }else{
335         $msg .= "||\n";
336         }
337     }
338     $timeout = 0;
339     print STDERR "$msg";
340   }
341
342       
343   ###
344   # Check the result of execution 
345   ###
346   my $diff;
347   if (!defined($cmd{'output ignore'})){
348     $diff = build_diff(\@{$cmd{'out'}}, \@got);
349   }else{
350   print "(ignoring the output of <$cmd{'file'}:$cmd{'line'}> as requested)\n"
351   }
352   if (length $diff) {
353     print "Output of <$cmd{'file'}:$cmd{'line'}> mismatch:\n";
354     map { print "$_\n" } split(/\n/,$diff);
355
356     print "Test suite `$cmd{'file'}': NOK (<$cmd{'file'}:$cmd{'line'}> output mismatch)\n";
357     $error=1;
358     $exitcode=2;
359   }
360 }
361
362 sub mkfile_cmd {
363   my %cmd = %{$_[0]};
364   my $file = $cmd{'arg'};
365   print "[Tesh/INFO] mkfile $file\n";
366
367   die "[TESH/CRITICAL] no input provided to mkfile\n" unless defined($cmd{'in'}) && scalar @{$cmd{'in'}};
368   unlink($file);
369   open(FILE,">$file") or die "[Tesh/CRITICAL] Unable to create file $file: $!\n";
370   print FILE join("\n", @{$cmd{'in'}});
371   print FILE "\n" if (scalar @{$cmd{'in'}} > 0);
372   close(FILE);
373 }
374
375 # parse tesh file
376 #my $teshfile=$tesh_file;
377 #$teshfile=~ s{\.[^.]+$}{};
378
379 unless($tesh_file eq "(stdin)"){
380   open TESH_FILE, $tesh_file or die "[Tesh/CRITICAL] Unable to open $tesh_file $!\n";
381 }
382
383 my %cmd; # everything about the next command to run
384 my $line_num=0;
385 my $finished =0;
386 LINE: while (not $finished and not $error) {
387   my $line;
388
389
390   if ($tesh_file ne "(stdin)" and !defined($line=<TESH_FILE>)){
391     $finished=1;
392     next LINE;
393   }elsif ($tesh_file eq "(stdin)" and !defined($line=<>)){
394     $finished=1;
395     next LINE;
396   }
397
398
399   $line_num++;
400   chomp $line;
401   $line =~ s/\r//g;
402   print "[TESH/debug] $line_num: $line\n" if $opts{'debug'};
403   my $next;
404   # deal with line continuations
405   while ($line =~ /^(.*?)\\$/) {
406     $next=<TESH_FILE>;
407     die "[TESH/CRITICAL] Continued line at end of file\n"
408       unless defined($next);
409     $line_num++;
410     chomp $next;
411     print "[TESH/debug] $line_num: $next\n" if $opts{'debug'};
412     $line = $1.$next;
413   }
414
415   # Push delayed commands on empty lines
416   unless ($line =~ m/^(.).(.*)$/) {
417     if (defined($cmd{'cmd'})) {
418       exec_cmd(\%cmd);
419       %cmd = ();
420     }
421     next LINE;
422   }     
423  
424   my ($cmd,$arg) = ($1,$2);
425   $arg =~ s/\r//g;
426   $arg =~ s/\\\\/\\/g;
427   # handle the commands
428   if ($cmd =~ /^#/) {    #comment
429   } elsif ($cmd eq '>'){    #expected result line
430     print "[TESH/debug] push expected result\n" if $opts{'debug'};
431   $arg=trim($arg);
432     if($arg ne ""){
433     push @{$cmd{'out'}}, $arg;
434   }
435
436   } elsif ($cmd eq '<') {    # provided input
437     print "[TESH/debug] push provided input\n" if $opts{'debug'};
438     push @{$cmd{'in'}}, $arg;
439
440   } elsif ($cmd eq 'p') {    # comment
441     print "[$tesh_name:$line_num] $arg\n";
442
443   } elsif ($cmd eq '$') {  # Command
444     # if we have something buffered, run it now
445     if (defined($cmd{'cmd'})) {
446       exec_cmd(\%cmd);
447       %cmd = ();
448     }
449     if ($arg =~ /^\s*mkfile /){      # "mkfile" command line
450       die "[TESH/CRITICAL] Output expected from mkfile command!\n" if scalar @{cmd{'out'}};
451
452       $cmd{'arg'} = $arg;
453       $cmd{'arg'} =~ s/\s*mkfile //;
454       mkfile_cmd(\%cmd);
455       %cmd = ();
456
457     } elsif ($arg =~ /^\s*cd /) {
458       die "[TESH/CRITICAL] Input provided to cd command!\n" if scalar @{cmd{'in'}};
459       die "[TESH/CRITICAL] Output expected from cd command!\n" if scalar @{cmd{'out'}};
460
461       $arg =~ s/^ *cd //;
462       cd_cmd("",$arg);
463       %cmd = ();
464
465     } else { # regular command
466       $cmd{'cmd'} = $arg;
467       $cmd{'file'} = $tesh_file;
468       $cmd{'line'} = $line_num;
469     }
470   }
471   elsif($cmd eq '&'){      # parallel command line
472
473     if (defined($cmd{'cmd'})) {
474       exec_cmd(\%cmd);
475       %cmd = ();
476     }
477     $cmd{'background'} = 1;
478     $cmd{'cmd'} = $arg;
479     $cmd{'file'} = $tesh_file;
480     $cmd{'line'} = $line_num;
481   }    
482   elsif($line =~ /^!\s*output sort/){    #output sort
483     if (defined($cmd{'cmd'})) {
484       exec_cmd(\%cmd);
485       %cmd = ();
486     }
487     $cmd{'sort'} = 1;
488   }
489   elsif($line =~ /^!\s*output ignore/){    #output ignore
490     if (defined($cmd{'cmd'})) {
491       exec_cmd(\%cmd);
492       %cmd = ();
493     }
494     $cmd{'output ignore'} = 1;
495   }
496   elsif($line =~ /^!\s*expect signal (\w*)/) {#expect signal SIGABRT
497     if (defined($cmd{'cmd'})) {
498       exec_cmd(\%cmd);
499       %cmd = ();
500     }
501     $cmd{'expect'} = "$1";
502   }
503   elsif($line =~ /^!\s*expect return/){    #expect return
504     if (defined($cmd{'cmd'})) {
505       exec_cmd(\%cmd);
506       %cmd = ();
507     }
508     $line =~ s/^! expect return //g;
509     $line =~ s/\r//g;
510     $cmd{'return'} = $line;
511   }
512   elsif($line =~ /^!\s*setenv/){    #setenv
513     if (defined($cmd{'cmd'})) {
514       exec_cmd(\%cmd);
515       %cmd = ();
516     }
517     $line =~ s/^! setenv //g;
518     $line =~ s/\r//g;
519     setenv_cmd($line);
520   }
521   elsif($line =~ /^!\s*include/){    #output sort
522     if (defined($cmd{'cmd'})) {
523       exec_cmd(\%cmd);
524       %cmd = ();
525     }
526     print color("red"), "[Tesh/CRITICAL] need include";
527     print color("reset"), "\n";
528     die;
529   }
530   elsif($line =~ /^!\s*timeout/){    #timeout
531     if (defined($cmd{'cmd'})) {
532       exec_cmd(\%cmd);
533       %cmd = ();
534     }
535     $line =~ s/^! timeout //;
536     $line =~ s/\r//g;
537     $cmd{'timeout'} = $line;
538   } else {
539     die "[TESH/CRITICAL] parse error: $line\n";
540   }
541   if($forked){
542    kill(SIGKILL, $forked);
543    $timeout=0;
544   }
545
546 }
547
548
549
550 # Deal with last command
551 if (defined($cmd{'cmd'})) {
552   exec_cmd(\%cmd);
553   %cmd = ();
554 }
555
556
557 if($forked){
558    kill(SIGKILL, $forked);
559    $timeout=0;
560 }
561
562 if($error !=0){
563     exit $exitcode;
564 }elsif($tesh_file eq "(stdin)"){
565     print "Test suite from stdin OK\n";
566 }else{
567     print "Test suite `$tesh_name' OK\n";
568 }
569
570 #my (@a,@b);
571 #push @a,"bl1";   push @b,"bl1";
572 #push @a,"bl2";   push @b,"bl2";
573 #push @a,"bl3";   push @b,"bl3";
574 #push @a,"bl4";   push @b,"bl4";
575 #push @a,"bl5";   push @b,"bl5";
576 #push @a,"bl6";   push @b,"bl6";
577 #push @a,"bl7";   push @b,"bl7";
578 ##push @a,"Perl";  push @b,"ruby";
579 #push @a,"END1";   push @b,"END1";
580 #push @a,"END2";   push @b,"END2";
581 #push @a,"END3";   push @b,"END3";
582 #push @a,"END4";   push @b,"END4";
583 #push @a,"END5";   push @b,"END5";
584 #push @a,"END6";   push @b,"END6";
585 #push @a,"END7";   push @b,"END7";
586 #print "Identical:\n". build_diff(\@a,\@b);
587
588 #@a = (); @b =();
589 #push @a,"AZE"; push @b,"EZA";
590 #print "Different:\n".build_diff(\@a,\@b);
591
592 use lib "@CMAKE_BINARY_DIR@/bin" ;
593
594 use Diff qw(diff); # postpone a bit to have time to change INC
595
596 sub build_diff {
597   my $res;
598   my $diff = Diff->new(@_);
599   
600   $diff->Base( 1 );   # Return line numbers, not indices
601   my $chunk_count = $diff->Next(-1); # Compute the amount of chuncks
602   return ""   if ($chunk_count == 1 && $diff->Same());
603   $diff->Reset();
604   while(  $diff->Next()  ) {
605     my @same = $diff->Same();
606     if ($diff->Same() ) {
607       if ($diff->Next(0) > 1) { # not first chunk: print 2 first lines
608         $res .= '  '.$same[0]."\n" ;
609         $res .= '  '.$same[1]."\n" if (scalar @same>1);
610       }     
611       $res .= "...\n"  if (scalar @same>2);
612 #    $res .= $diff->Next(0)."/$chunk_count\n";
613       if ($diff->Next(0) < $chunk_count) { # not last chunk: print 2 last lines
614         $res .= '  '.$same[scalar @same -2]."\n" if (scalar @same>1);
615         $res .= '  '.$same[scalar @same -1]."\n";
616       } 
617     } 
618     next if  $diff->Same();
619     map { $res .= "- $_\n" } $diff->Items(1);
620     map { $res .= "+ $_\n" } $diff->Items(2);
621   }
622   return $res;
623 }
624
625