[Bio] / FigKernelPackages / Tracer.pm Repository:
ViewVC logotype

Diff of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.39, Fri Feb 24 19:45:29 2006 UTC revision 1.62, Thu Aug 24 07:58:29 2006 UTC
# Line 19  Line 19 
19    
20      require Exporter;      require Exporter;
21      @ISA = ('Exporter');      @ISA = ('Exporter');
22      @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup ScriptSetup ScriptFinish Insure);      @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup ScriptSetup ScriptFinish Insure ChDir);
23      @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);      @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);
24      use strict;      use strict;
25      use Carp qw(longmess croak);      use Carp qw(longmess croak);
26      use CGI;      use CGI;
27        use Cwd;
28      use FIG_Config;      use FIG_Config;
29      use PageBuilder;      use PageBuilder;
30      use Digest::MD5;      use Digest::MD5;
31      use File::Basename;      use File::Basename;
32      use File::Path;      use File::Path;
33        use File::stat;
34        use LWP::UserAgent;
35    
36  =head1 Tracing and Debugging Helpers  =head1 Tracing and Debugging Helpers
37    
# Line 275  Line 278 
278  of a keyword, the value is separated from the option name by an equal sign. You  of a keyword, the value is separated from the option name by an equal sign. You
279  can see this last in the command-line example above.  can see this last in the command-line example above.
280    
281    You can specify a different default trace level by setting C<$options->{trace}>
282    prior to calling this method.
283    
284  An example at this point would help. Consider, for example, the command-line utility  An example at this point would help. Consider, for example, the command-line utility
285  C<TransactFeatures>. It accepts a list of positional parameters plus the options  C<TransactFeatures>. It accepts a list of positional parameters plus the options
286  C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute  C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
# Line 314  Line 320 
320  need to be added in the future, they can be processed by this method without  need to be added in the future, they can be processed by this method without
321  upsetting the command-line utilities.  upsetting the command-line utilities.
322    
323    If the C<background> option is specified on the command line, then the
324    standard and error outputs will be directed to files in the temporary
325    directory, using the same suffix as the trace file. So, if the command
326    line specified
327    
328        -user=Bruce -background
329    
330    then the trace output would go to C<traceBruce.log>, the standard output to
331    C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to
332    simplify starting a command in the background.
333    
334  Finally, if the special option C<-h> is specified, the option names will  Finally, if the special option C<-h> is specified, the option names will
335  be traced at level 0 and the program will exit without processing.  be traced at level 0 and the program will exit without processing.
336  This provides a limited help capability. For example, if the user enters  This provides a limited help capability. For example, if the user enters
# Line 330  Line 347 
347          -start    start with this genome          -start    start with this genome
348          -tblFiles output TBL files containing the corrected IDs          -tblFiles output TBL files containing the corrected IDs
349    
350    The caller has the option of modifying the tracing scheme by placing a value
351    for C<trace> in the incoming options hash. The default value can be overridden,
352    or the tracing to the standard output can be turned off by suffixing a minus
353    sign to the trace level. So, for example,
354    
355        { trace => [0, "tracing level (default 0)"],
356           ...
357    
358    would set the default trace level to 0 instead of 2, while
359    
360        { trace => ["2-", "tracing level (default 2)"],
361           ...
362    
363    would leave the default at 2, but trace only to the log file, not to the
364    standard output.
365    
366  The parameters to this method are as follows.  The parameters to this method are as follows.
367    
368  =over 4  =over 4
# Line 347  Line 380 
380  by specifying the options as command-line switches prefixed by a hyphen.  by specifying the options as command-line switches prefixed by a hyphen.
381  Tracing-related options may be added to this hash. If the C<-h> option is  Tracing-related options may be added to this hash. If the C<-h> option is
382  specified on the command line, the option descriptions will be used to  specified on the command line, the option descriptions will be used to
383  explain the options.  explain the options. To turn off tracing to the standard output, add a
384    minus sign to the value for C<trace> (see above).
385    
386  =item parmHelp  =item parmHelp
387    
388  A string that vaguely describes the positional parameters. This is used  A string that vaguely describes the positional parameters. This is used
389  if the user specifies the C<-h> option.  if the user specifies the C<-h> option.
390    
391  =item ARGV  =item argv
392    
393  List of command line parameters, including the option switches, which must  List of command line parameters, including the option switches, which must
394  precede the positional parameters and be prefixed by a hyphen.  precede the positional parameters and be prefixed by a hyphen.
# Line 374  Line 408 
408      # Get the parameters.      # Get the parameters.
409      my ($categories, $options, $parmHelp, @argv) = @_;      my ($categories, $options, $parmHelp, @argv) = @_;
410      # Add the tracing options.      # Add the tracing options.
411        if (! exists $options->{trace}) {
412      $options->{trace} = [2, "tracing level"];      $options->{trace} = [2, "tracing level"];
413        }
414      $options->{sql} = [0, "turn on SQL tracing"];      $options->{sql} = [0, "turn on SQL tracing"];
415      $options->{h} = [0, "display command-line options"];      $options->{h} = [0, "display command-line options"];
416      $options->{user} = [$$, "trace log file name suffix"];      $options->{user} = [$$, "trace log file name suffix"];
417        $options->{background} = [0, "spool standard and error output"];
418      # Create a parsing hash from the options hash. The parsing hash      # Create a parsing hash from the options hash. The parsing hash
419      # contains the default values rather than the default value      # contains the default values rather than the default value
420      # and the description. While we're at it, we'll memorize the      # and the description. While we're at it, we'll memorize the
# Line 392  Line 429 
429      }      }
430      # Parse the command line.      # Parse the command line.
431      my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);      my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
432        # Get the logfile suffix.
433        my $suffix = $retOptions->{user};
434        # Check for background mode.
435        if ($retOptions->{background}) {
436            my $outFileName = "$FIG_Config::temp/out$suffix.log";
437            my $errFileName = "$FIG_Config::temp/err$suffix.log";
438            open STDOUT, ">$outFileName";
439            open STDERR, ">$errFileName";
440        }
441      # Now we want to set up tracing. First, we need to know if SQL is to      # Now we want to set up tracing. First, we need to know if SQL is to
442      # be traced.      # be traced.
443      my @cats = @{$categories};      my @cats = @{$categories};
# Line 400  Line 446 
446      }      }
447      # Add the default categories.      # Add the default categories.
448      push @cats, "Tracer", "FIG";      push @cats, "Tracer", "FIG";
449      # Next, we create the category string by prefixing the trace level      # Next, we create the category string by joining the categories.
450      # and joining the categories.      my $cats = join(" ", @cats);
451      my $cats = join(" ", $parseOptions{trace}, @cats);      # Check to determine whether or not the caller wants to turn off tracing
452        # to the standard output.
453        my $traceLevel = $retOptions->{trace};
454        my $textOKFlag = 1;
455        if ($traceLevel =~ /^(.)-/) {
456            $traceLevel = $1;
457            $textOKFlag = 0;
458        }
459        # Now we set up the trace mode.
460        my $traceMode;
461        # Verify that we can open a file in the FIG temporary directory.
462        my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
463        if (open TESTTRACE, ">$traceFileName") {
464            # Here we can trace to a file.
465            $traceMode = ">$traceFileName";
466            if ($textOKFlag) {
467                # Echo to standard output if the text-OK flag is set.
468                $traceMode = "+$traceMode";
469            }
470            # Close the test file.
471            close TESTTRACE;
472        } else {
473            # Here we can't trace to a file. We trace to the standard output if it's
474            # okay, and the error log otherwise.
475            if ($textOKFlag) {
476                $traceMode = "TEXT";
477            } else {
478                $traceMode = "WARN";
479            }
480        }
481      # Now set up the tracing.      # Now set up the tracing.
482      my $suffix = $retOptions->{user};      TSetup("$traceLevel $cats", $traceMode);
     TSetup($cats, "+>$FIG_Config::temp/trace$suffix.log");  
483      # Check for the "h" option. If it is specified, dump the command-line      # Check for the "h" option. If it is specified, dump the command-line
484      # options and exit the program.      # options and exit the program.
485      if ($retOptions->{h}) {      if ($retOptions->{h}) {
# Line 1275  Line 1349 
1349      return @inputList;      return @inputList;
1350  }  }
1351    
1352    =head3 Percent
1353    
1354    C<< my $percent = Tracer::Percent($number, $base); >>
1355    
1356    Returns the percent of the base represented by the given number. If the base
1357    is zero, returns zero.
1358    
1359    =over 4
1360    
1361    =item number
1362    
1363    Percent numerator.
1364    
1365    =item base
1366    
1367    Percent base.
1368    
1369    =item RETURN
1370    
1371    Returns the percentage of the base represented by the numerator.
1372    
1373    =back
1374    
1375    =cut
1376    
1377    sub Percent {
1378        # Get the parameters.
1379        my ($number, $base) = @_;
1380        # Declare the return variable.
1381        my $retVal = 0;
1382        # Compute the percent.
1383        if ($base != 0) {
1384            $retVal = $number * 100 / $base;
1385        }
1386        # Return the result.
1387        return $retVal;
1388    }
1389    
1390  =head3 GetFile  =head3 GetFile
1391    
1392  C<< my @fileContents = Tracer::GetFile($fileName); >>  C<< my @fileContents = Tracer::GetFile($fileName); >>
# Line 1308  Line 1420 
1420      # Declare the return variable.      # Declare the return variable.
1421      my @retVal = ();      my @retVal = ();
1422      # Open the file for input.      # Open the file for input.
1423      my $ok = open INPUTFILE, "<$fileName";      my $handle = Open(undef, "<$fileName");
     if (!$ok) {  
         # If we had an error, trace it. We will automatically return a null value.  
         Trace("Could not open \"$fileName\" for input: $!") if T(0);  
     } else {  
1424          # Read the whole file into the return variable, stripping off any terminator          # Read the whole file into the return variable, stripping off any terminator
1425          # characters.          # characters.
1426          my $lineCount = 0;          my $lineCount = 0;
1427          while (my $line = <INPUTFILE>) {      while (my $line = <$handle>) {
1428              $lineCount++;              $lineCount++;
1429              $line = Strip($line);              $line = Strip($line);
1430              push @retVal, $line;              push @retVal, $line;
1431          }          }
1432          # Close it.          # Close it.
1433          close INPUTFILE;      close $handle;
1434          my $actualLines = @retVal;          my $actualLines = @retVal;
     }  
1435      # Return the file's contents in the desired format.      # Return the file's contents in the desired format.
1436      if (wantarray) {      if (wantarray) {
1437          return @retVal;          return @retVal;
# Line 1333  Line 1440 
1440      }      }
1441  }  }
1442    
1443    =head3 PutFile
1444    
1445    C<< Tracer::PutFile($fileName, \@lines); >>
1446    
1447    Write out a file from a list of lines of text.
1448    
1449    =over 4
1450    
1451    =item fileName
1452    
1453    Name of the output file.
1454    
1455    =item lines
1456    
1457    Reference to a list of text lines. The lines will be written to the file in order, with trailing
1458    new-line characters.
1459    
1460    =back
1461    
1462    =cut
1463    
1464    sub PutFile {
1465        # Get the parameters.
1466        my ($fileName, $lines) = @_;
1467        # Open the output file.
1468        my $handle = Open(undef, ">$fileName");
1469        # Write the lines.
1470        for my $line (@{$lines}) {
1471            print $handle "$line\n";
1472        }
1473        # Close the output file.
1474        close $handle;
1475    }
1476    
1477  =head3 QTrace  =head3 QTrace
1478    
1479  C<< my $data = QTrace($format); >>  C<< my $data = QTrace($format); >>
# Line 1533  Line 1674 
1674    
1675  =head3 AddToListMap  =head3 AddToListMap
1676    
1677  C<< Tracer::AddToListMap(\%hash, $key, $value); >>  C<< Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN); >>
1678    
1679  Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list  Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list
1680  is created for the key. Otherwise, the new value is pushed onto the list.  is created for the key. Otherwise, the new value is pushed onto the list.
# Line 1548  Line 1689 
1689    
1690  Key for which the value is to be added.  Key for which the value is to be added.
1691    
1692  =item value  =item value1, value2, ... valueN
1693    
1694  Value to add to the key's value list.  List of values to add to the key's value list.
1695    
1696  =back  =back
1697    
# Line 1558  Line 1699 
1699    
1700  sub AddToListMap {  sub AddToListMap {
1701      # Get the parameters.      # Get the parameters.
1702      my ($hash, $key, $value) = @_;      my ($hash, $key, @values) = @_;
1703      # Process according to whether or not the key already has a value.      # Process according to whether or not the key already has a value.
1704      if (! exists $hash->{$key}) {      if (! exists $hash->{$key}) {
1705          $hash->{$key} = [$value];          $hash->{$key} = [@values];
1706      } else {      } else {
1707          push @{$hash->{$key}}, $value;          push @{$hash->{$key}}, @values;
1708      }      }
1709  }  }
1710    
# Line 1593  Line 1734 
1734          $retVal = 1;          $retVal = 1;
1735      } else {      } else {
1736          # Here debug mode is off, so we generate an error page.          # Here debug mode is off, so we generate an error page.
1737          my $pageString = PageBuilder::Build("<Html/ErrorPage.html", {}, "Html");          my $pageString = PageBuilder::Build("<<Html/ErrorPage.html", {}, "Html");
1738          print $pageString;          print $pageString;
1739      }      }
1740      # Return the determination indicator.      # Return the determination indicator.
# Line 1861  Line 2002 
2002      my $outputString;      my $outputString;
2003      if (defined $varHash) {      if (defined $varHash) {
2004          # Here we have a template file. We need to apply the variables to the template.          # Here we have a template file. We need to apply the variables to the template.
2005          $outputString = PageBuilder::Build("<$webData", $varHash, "Html");          $outputString = PageBuilder::Build("<<$webData", $varHash, "Html");
2006      } else {      } else {
2007          # Here the user gave us a raw string.          # Here the user gave us a raw string.
2008          $outputString = $webData;          $outputString = $webData;
# Line 1901  Line 2042 
2042      my ($dirName) = @_;      my ($dirName) = @_;
2043      if (! -d $dirName) {      if (! -d $dirName) {
2044          Trace("Creating $dirName directory.") if T(2);          Trace("Creating $dirName directory.") if T(2);
2045          mkpath $dirName;          eval { mkpath $dirName; };
2046            if ($@) {
2047                Confess("Error creating $dirName: $@");
2048            }
2049        }
2050    }
2051    
2052    =head3 ChDir
2053    
2054    C<< ChDir($dirName); >>
2055    
2056    Change to the specified directory.
2057    
2058    =over 4
2059    
2060    =item dirName
2061    
2062    Name of the directory to which we want to change.
2063    
2064    =back
2065    
2066    =cut
2067    
2068    sub ChDir {
2069        my ($dirName) = @_;
2070        if (! -d $dirName) {
2071            Confess("Cannot change to directory $dirName: no such directory.");
2072        } else {
2073            Trace("Changing to directory $dirName.") if T(4);
2074            my $okFlag = chdir $dirName;
2075            if (! $okFlag) {
2076                Confess("Error switching to directory $dirName.");
2077            }
2078        }
2079    }
2080    
2081    =head3 SendSMS
2082    
2083    C<< my $msgID = Tracer::SendSMS($phoneNumber, $msg); >>
2084    
2085    Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
2086    user name, password, and API ID for the relevant account in the hash reference variable
2087    I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
2088    example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
2089    is C<2561022>, then the FIG_Config file must contain
2090    
2091        $phone =  { user => 'BruceTheHumanPet',
2092                    password => 'silly',
2093                    api_id => '2561022' };
2094    
2095    The original purpose of this method was to insure Bruce would be notified immediately when the
2096    Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
2097    when you call this method.
2098    
2099    The message ID will be returned if successful, and C<undef> if an error occurs.
2100    
2101    =over 4
2102    
2103    =item phoneNumber
2104    
2105    Phone number to receive the message, in international format. A United States phone number
2106    would be prefixed by "1". A British phone number would be prefixed by "44".
2107    
2108    =item msg
2109    
2110    Message to send to the specified phone.
2111    
2112    =item RETURN
2113    
2114    Returns the message ID if successful, and C<undef> if the message could not be sent.
2115    
2116    =back
2117    
2118    =cut
2119    
2120    sub SendSMS {
2121        # Get the parameters.
2122        my ($phoneNumber, $msg) = @_;
2123        # Declare the return variable. If we do not change it, C<undef> will be returned.
2124        my $retVal;
2125        # Only proceed if we have phone support.
2126        if (! defined $FIG_Config::phone) {
2127            Trace("Phone support not present in FIG_Config.") if T(1);
2128        } else {
2129            # Get the phone data.
2130            my $parms = $FIG_Config::phone;
2131            # Get the Clickatell URL.
2132            my $url = "http://api.clickatell.com/http/";
2133            # Create the user agent.
2134            my $ua = LWP::UserAgent->new;
2135            # Request a Clickatell session.
2136            my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
2137                                         password => $parms->{password},
2138                                         api_id => $parms->{api_id},
2139                                         to => $phoneNumber,
2140                                         text => $msg});
2141            # Check for an error.
2142            if (! $resp->is_success) {
2143                Trace("Alert failed.") if T(1);
2144            } else {
2145                # Get the message ID.
2146                my $rstring = $resp->content;
2147                if ($rstring =~ /^ID:\s+(.*)$/) {
2148                    $retVal = $1;
2149                } else {
2150                    Trace("Phone attempt failed with $rstring") if T(1);
2151                }
2152            }
2153        }
2154        # Return the result.
2155        return $retVal;
2156    }
2157    
2158    =head3 CommaFormat
2159    
2160    C<< my $formatted = Tracer::CommaFormat($number); >>
2161    
2162    Insert commas into a number.
2163    
2164    =over 4
2165    
2166    =item number
2167    
2168    A sequence of digits.
2169    
2170    =item RETURN
2171    
2172    Returns the same digits with commas strategically inserted.
2173    
2174    =back
2175    
2176    =cut
2177    
2178    sub CommaFormat {
2179        # Get the parameters.
2180        my ($number) = @_;
2181        # Pad the length up to a multiple of three.
2182        my $padded = "$number";
2183        $padded = " " . $padded while length($padded) % 3 != 0;
2184        # This is a fancy PERL trick. The parentheses in the SPLIT pattern
2185        # cause the delimiters to be included in the output stream. The
2186        # GREP removes the empty strings in between the delimiters.
2187        my $retVal = join(",", grep { $_ ne '' } split(/(...)/, $padded));
2188        # Clean out the spaces.
2189        $retVal =~ s/ //g;
2190        # Return the result.
2191        return $retVal;
2192    }
2193    =head3 SetPermissions
2194    
2195    C<< Tracer::SetPermissions($dirName, $group, $mask, %otherMasks); >>
2196    
2197    Set the permissions for a directory and all the files and folders inside it.
2198    In addition, the group ownership will be changed to the specified value.
2199    
2200    This method is more vulnerable than most to permission and compatability
2201    problems, so it does internal error recovery.
2202    
2203    =over 4
2204    
2205    =item dirName
2206    
2207    Name of the directory to process.
2208    
2209    =item group
2210    
2211    Name of the group to be assigned.
2212    
2213    =item mask
2214    
2215    Permission mask. Bits that are C<1> in this mask will be ORed into the
2216    permission bits of any file or directory that does not already have them
2217    set to 1.
2218    
2219    =item otherMasks
2220    
2221    Map of search patterns to permission masks. If a directory name matches
2222    one of the patterns, that directory and all its members and subdirectories
2223    will be assigned the new pattern. For example, the following would
2224    assign 01664 to most files, but would use 01777 for directories named C<tmp>.
2225    
2226        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2227    
2228    The list is ordered, so the following would use 0777 for C<tmp1> and
2229    0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2230    
2231        Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2232                                                       '^tmp' => 0666);
2233    
2234    Note that the pattern matches are all case-insensitive, and only directory
2235    names are matched, not file names.
2236    
2237    =back
2238    
2239    =cut
2240    
2241    sub SetPermissions {
2242        # Get the parameters.
2243        my ($dirName, $group, $mask, @otherMasks) = @_;
2244        # Set up for error recovery.
2245        eval {
2246            # Switch to the specified directory.
2247            ChDir($dirName);
2248            # Get the group ID.
2249            my $gid = getgrnam($group);
2250            # Get the mask for tracing.
2251            my $traceMask = sprintf("%04o", $mask) . "($mask)";
2252            Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(2);
2253            my $fixCount = 0;
2254            my $lookCount = 0;
2255            # @dirs will be a stack of directories to be processed.
2256            my @dirs = (getcwd());
2257            while (scalar(@dirs) > 0) {
2258                # Get the current directory.
2259                my $dir = pop @dirs;
2260                # Check for a match to one of the specified directory names. To do
2261                # that, we need to pull the individual part of the name off of the
2262                # whole path.
2263                my $simpleName = $dir;
2264                if ($dir =~ m!/([^/]+)$!) {
2265                    $simpleName = $1;
2266                }
2267                Trace("Simple directory name for $dir is $simpleName.") if T(4);
2268                # Search for a match.
2269                my $match = 0;
2270                my $i;
2271                for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2272                    my $pattern = $otherMasks[$i];
2273                    if ($simpleName =~ /$pattern/i) {
2274                        $match = 1;
2275                    }
2276                }
2277                # Check for a match. Note we use $i-1 because the loop added 2
2278                # before terminating due to the match.
2279                if ($match && $otherMasks[$i-1] != $mask) {
2280                    # This directory matches one of the incoming patterns, and it's
2281                    # a different mask, so we process it recursively with that mask.
2282                    SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2283                } else {
2284                    # Here we can process normally. Get all of the non-hidden members.
2285                    my @submems = OpenDir($dir, 1);
2286                    for my $submem (@submems) {
2287                        # Get the full name.
2288                        my $thisMem = "$dir/$submem";
2289                        Trace("Checking member $thisMem.") if T(4);
2290                        $lookCount++;
2291                        if ($lookCount % 1000 == 0) {
2292                            Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(3);
2293                        }
2294                        # Fix the group.
2295                        chown -1, $gid, $thisMem;
2296                        # Insure this member is not a symlink.
2297                        if (! -l $thisMem) {
2298                            # Get its info.
2299                            my $fileInfo = stat $thisMem;
2300                            # Only proceed if we got the info. Otherwise, it's a hard link
2301                            # and we want to skip it anyway.
2302                            if ($fileInfo) {
2303                                my $fileMode = $fileInfo->mode;
2304                                if (($fileMode & $mask) != $mask) {
2305                                    # Fix this member.
2306                                    $fileMode |= $mask;
2307                                    chmod $fileMode, $thisMem;
2308                                    $fixCount++;
2309                                }
2310                                # If it's a subdirectory, stack it.
2311                                if (-d $thisMem) {
2312                                    push @dirs, $thisMem;
2313                                }
2314                            }
2315                        }
2316                    }
2317                }
2318            }
2319            Trace("$lookCount files and directories processed, $fixCount fixed.") if T(2);
2320        };
2321        # Check for an error.
2322        if ($@) {
2323            Confess("SetPermissions error: $@");
2324        }
2325    }
2326    
2327    =head3 CompareLists
2328    
2329    C<< my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex); >>
2330    
2331    Compare two lists of tuples, and return a hash analyzing the differences. The lists
2332    are presumed to be sorted alphabetically by the value in the $keyIndex column.
2333    The return value contains a list of items that are only in the new list
2334    (inserted) and only in the old list (deleted).
2335    
2336    =over 4
2337    
2338    =item newList
2339    
2340    Reference to a list of new tuples.
2341    
2342    =item oldList
2343    
2344    Reference to a list of old tuples.
2345    
2346    =item keyIndex (optional)
2347    
2348    Index into each tuple of its key field. The default is 0.
2349    
2350    =item RETURN
2351    
2352    Returns a 2-tuple consisting of a reference to the list of items that are only in the new
2353    list (inserted) followed by a reference to the list of items that are only in the old
2354    list (deleted).
2355    
2356    =back
2357    
2358    =cut
2359    
2360    sub CompareLists {
2361        # Get the parameters.
2362        my ($newList, $oldList, $keyIndex) = @_;
2363        if (! defined $keyIndex) {
2364            $keyIndex = 0;
2365        }
2366        # Declare the return variables.
2367        my ($inserted, $deleted) = ([], []);
2368        # Loop through the two lists simultaneously.
2369        my ($newI, $oldI) = (0, 0);
2370        my ($newN, $oldN) = (scalar @{$newList}, scalar @{$oldList});
2371        while ($newI < $newN || $oldI < $oldN) {
2372            # Get the current object in each list. Note that if one
2373            # of the lists is past the end, we'll get undef.
2374            my $newItem = $newList->[$newI];
2375            my $oldItem = $oldList->[$oldI];
2376            if (! defined($newItem) || $newItem->[$keyIndex] gt $oldItem->[$keyIndex]) {
2377                # The old item is not in the new list, so mark it deleted.
2378                push @{$deleted}, $oldItem;
2379                $oldI++;
2380            } elsif (! defined($oldItem) || $oldItem->[$keyIndex] gt $newItem->[$keyIndex]) {
2381                # The new item is not in the old list, so mark it inserted.
2382                push @{$inserted}, $newItem;
2383                $newI++;
2384            } else {
2385                # The item is in both lists, so push forward.
2386                $oldI++;
2387                $newI++;
2388      }      }
2389  }  }
2390        # Return the result.
2391        return ($inserted, $deleted);
2392    }
2393    
2394    
2395  1;  1;

Legend:
Removed from v.1.39  
changed lines
  Added in v.1.62

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3