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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.10 - (view) (download) (as text)

1 : olson 1.1 package Tracer;
2 :    
3 :     require Exporter;
4 :     @ISA = ('Exporter');
5 : parrello 1.10 @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open);
6 : parrello 1.9 @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);
7 : olson 1.1 use strict;
8 :     use Carp qw(longmess croak);
9 :     use CGI;
10 : parrello 1.7 use FIG_Config;
11 : parrello 1.9 use PageBuilder;
12 : olson 1.1
13 :     =head1 Tracing and Debugging Helpers
14 :    
15 :     =head2 Introduction
16 :    
17 :     This package provides simple tracing for debugging and reporting purposes. To use it simply call the
18 :     L</TSetup> method to set the options and call L</Trace> to write out trace messages. Each trace
19 : parrello 1.2 message has a I<trace level> and I<category> associated with it. In addition, the tracing package itself
20 :     has a list of categories and a single trace level set by the B<TSetup> method. Only messages whose trace
21 : olson 1.1 level is less than or equal to this package's trace level and whose category is activated will
22 : parrello 1.2 be written. Thus, a higher trace level on a message indicates that the message
23 : parrello 1.10 is less likely to be seen. A higher trace level passed to B<TSetup> means more trace messages will
24 : olson 1.1 appear. To generate a trace message, use the following syntax.
25 :    
26 :     C<< Trace($message) if T(errors => 4); >>
27 :    
28 : parrello 1.2 This statement will produce a trace message if the trace level is 4 or more and the C<errors>
29 : parrello 1.3 category is active. Note that the special category C<main> is always active, so
30 : olson 1.1
31 : parrello 1.3 C<< Trace($message) if T(main => 4); >>
32 : olson 1.1
33 :     will trace if the trace level is 4 or more.
34 :    
35 :     If the category name is the same as the package name, all you need is the number. So, if the
36 :     following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is
37 :     active and the trace level is 2 or more.
38 :    
39 :     C<< Trace($message) if T(2); >>
40 :    
41 : parrello 1.10 To set up tracing, you call the L</TSetup> method. The method takes as input a trace level, a list
42 : olson 1.1 of category names, and a set of options. The trace level and list of category names are
43 :     specified as a space-delimited string. Thus
44 :    
45 :     C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>
46 :    
47 : parrello 1.7 sets the trace level to 3, activates the C<errors>, C<Sprout>, and C<ERDB> categories, and
48 :     specifies that messages should be output as HTML paragraphs. The parameters are formatted
49 : parrello 1.10 a little clumsily, but it makes them easier to input on a web form or in a query URL.
50 : olson 1.1
51 :     In addition to HTML and file output for trace messages, you can specify that the trace messages
52 :     be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach
53 :     is useful if you are building a web page. Instead of having the trace messages interspersed with
54 :     the page output, they can be gathered together and displayed at the end of the page. This makes
55 :     it easier to debug page formatting problems.
56 :    
57 : parrello 1.4 Finally, you can specify that all trace messages be emitted as warnings.
58 :    
59 : olson 1.1 The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.
60 :     Tracer calls can be left in the code with minimal overhead and then turned on only when needed.
61 :     Thus, debugging information is available and easily retrieved even when the application is
62 :     being used out in the field.
63 :    
64 : parrello 1.10 There is no hard and fast rule on how to use trace levels. The following is therefore only
65 :     a suggestion.
66 :    
67 :     =over 4
68 :    
69 :     =item 0 Error
70 :    
71 :     Message indicates an error that may lead to incorrect results or that has stopped the
72 :     application entirely.
73 :    
74 :     =item 1 Warning
75 :    
76 :     Message indicates something that is unexpected but that probably did not interfere
77 :     with program execution.
78 :    
79 :     =item 2 Notice
80 :    
81 :     Message indicates the beginning or end of a major task.
82 :    
83 :     =item 3 Information
84 :    
85 :     Message indicates a subtask. In the FIG system, a subtask generally relates to a single
86 :     genome. This would be a big loop that is not expected to execute more than 500 times or so.
87 :    
88 :     =item 4 Detail
89 :    
90 :     Message indicates a low-level loop iteration.
91 :    
92 :     =back
93 :    
94 : olson 1.1 =cut
95 : parrello 1.2
96 : olson 1.1 # Declare the configuration variables.
97 :    
98 :     my $Destination = "NONE"; # Description of where to send the trace output.
99 : parrello 1.10 my $TeeFlag = 0; # TRUE if output is going to a file and to the
100 :     # standard output
101 : parrello 1.3 my %Categories = ( main => 1 );
102 : olson 1.1 # hash of active category names
103 :     my $TraceLevel = 0; # trace level; a higher trace level produces more
104 :     # messages
105 :     my @Queue = (); # queued list of trace messages.
106 : parrello 1.7 my $LastCategory = "main"; # name of the last category interrogated
107 : olson 1.1
108 :     =head2 Public Methods
109 :    
110 :     =head3 TSetup
111 :    
112 :     C<< TSetup($categoryList, $target); >>
113 :    
114 :     This method is used to specify the trace options. The options are stored as package data
115 :     and interrogated by the L</Trace> and L</T> methods.
116 :    
117 :     =over 4
118 :    
119 :     =item categoryList
120 :    
121 :     A string specifying the trace level and the categories to be traced, separated by spaces.
122 :     The trace level must come first.
123 :    
124 :     =item target
125 :    
126 :     The destination for the trace output. To send the trace output to a file, specify the file
127 :     name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended
128 : parrello 1.10 to the file. Otherwise the file is cleared before tracing begins. Precede the first ">"
129 :     symbol with a C<+> to echo output to a file AND to the standard output. In addition to
130 :     sending the trace messages to a file, you can specify a special destination. C<HTML> will
131 :     cause tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>
132 : parrello 1.5 will cause tracing to the standard output as ordinary text. C<ERROR> will cause trace
133 : parrello 1.9 messages to be sent to the standard error output as ordinary text. C<QUEUE> will cause trace
134 : parrello 1.6 messages to be stored in a queue for later retrieval by the L</QTrace> method. C<WARN> will
135 : parrello 1.9 cause trace messages to be emitted as warnings using the B<warn> directive. C<NONE> will
136 : parrello 1.6 cause tracing to be suppressed.
137 : olson 1.1
138 :     =back
139 :    
140 :     =cut
141 :    
142 :     sub TSetup {
143 :     # Get the parameters.
144 :     my ($categoryList, $target) = @_;
145 :     # Parse the category list.
146 :     my @categoryData = split /\s+/, $categoryList;
147 :     # Extract the trace level.
148 :     $TraceLevel = shift @categoryData;
149 :     # Build the category hash.
150 :     for my $category (@categoryData) {
151 :     $Categories{$category} = 1;
152 :     }
153 :     # Now we need to process the destination information. The most important special
154 : parrello 1.10 # cases are the single ">", which requires we clear the file first, and the
155 :     # "+" prefix which indicates a double echo.
156 :     if ($target =~ m/^\+?>>?/) {
157 :     if ($target =~ m/^\+/) {
158 :     $TeeFlag = 1;
159 :     $target = substr($target, 1);
160 :     }
161 :     if ($target =~ m/^>[^>]/) {
162 :     open TRACEFILE, $target;
163 :     print TRACEFILE Now() . " Tracing initialized.\n";
164 :     close TRACEFILE;
165 :     $Destination = ">$target";
166 :     } else {
167 :     $Destination = $target;
168 :     }
169 : olson 1.1 } else {
170 :     $Destination = uc($target);
171 :     }
172 :     }
173 :    
174 : parrello 1.10 =head3 Open
175 :    
176 :     C<< my $handle = Open($fileHandle, $fileSpec, $message); >>
177 :    
178 :     Open a file and throw an exception if the open fails.
179 :    
180 :     The I<$fileSpec> is essentially the second argument of the PERL C<open>
181 :     function. The mode is specified using Unix-like shell information. So, for
182 :     example,
183 :    
184 :     Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
185 :    
186 :     would open for output appended to the specified file, and
187 :    
188 :     Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
189 :    
190 :     would open a pipe that sorts the records written and removes duplicates. Note
191 :     that the file handle is specified as a string. Note the use of file handle
192 :     syntax in the Open call. To use anonymous file handles, code as follows.
193 :    
194 :     my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
195 :    
196 :     The I<$message> parameter is used if the open fails to construct an error message.
197 :     If the parameter is omitted, a standard message is constructed using the file spec.
198 :    
199 :     Could not open "/usr/spool/news/twitlog"
200 :    
201 :     Note that the mode characters are automatically cleaned from the file name.
202 :     The actual error message from the file system will be captured and appended to the
203 :     message in any case.
204 :    
205 :     Could not open "/usr/spool/news/twitlog": file not found.
206 :    
207 :     In some versions of PERL the only error message we get is a number, which
208 :     corresponds to the C++ C<errno> value.
209 :    
210 :     Could not open "/usr/spool/news/twitlog": 6.
211 :    
212 :     This method has no provision for passing back error information. Its purpose is
213 :     to simplify the standard coding practice of opening files and killing the process
214 :     if the open doesn't work. If the trace level for C<Tracer> is set to level 1,
215 :     it will automatically show a stack trace as well.
216 :    
217 :     =over 4
218 :    
219 :     =item fileHandle
220 :    
221 :     File handle. If this parameter is C<undef>, a file handle will be generated
222 :     and returned as the value of this method.
223 :    
224 :     =item fileSpec
225 :    
226 :     File name and mode, as per the PERL C<open> function.
227 :    
228 :     =item message (optional)
229 :    
230 :     Error message to use if the open fails. If omitted, a standard error message
231 :     will be generated. In either case, the error information from the file system
232 :     is appended to the message.
233 :    
234 :     =item RETURN
235 :    
236 :     Returns the name of the file handle assigned to the file.
237 :    
238 :     =back
239 :    
240 :     =cut
241 :    
242 :     sub Open {
243 :     # Get the parameters.
244 :     my ($fileHandle, $fileSpec, $message) = @_;
245 :     # Attempt to open the file.
246 :     my $rv = open $fileHandle, $fileSpec;
247 :     # If the open failed, generate an error message.
248 :     if (! $rv) {
249 :     # Save the system error message.
250 :     my $sysMessage = $!;
251 :     # Clean any obvious mode characters and leading spaces from the
252 :     # filename.
253 :     $fileSpec =~ s/^(<|>*)\s*//;
254 :     if (!$message) {
255 :     $message = "Could not open \"$fileSpec\"";
256 :     }
257 :     # Terminate with an error using the supplied message and the
258 :     # error message from the file system.
259 :     Confess("$message: $!");
260 :     }
261 :     # Return the file handle.
262 :     return $fileHandle;
263 :     }
264 :    
265 : parrello 1.6 =head3 SetLevel
266 :    
267 :     C<< Tracer::SetLevel($newLevel); >>
268 :    
269 :     Modify the trace level. A higher trace level will cause more messages to appear.
270 :    
271 :     =over 4
272 :    
273 :     =item newLevel
274 :    
275 :     Proposed new trace level.
276 :    
277 :     =back
278 :    
279 :     =cut
280 :    
281 :     sub SetLevel {
282 :     $TraceLevel = $_[0];
283 :     }
284 :    
285 : olson 1.1 =head3 Now
286 :    
287 :     C<< my $string = Tracer::Now(); >>
288 :    
289 :     Return a displayable time stamp containing the local time.
290 :    
291 :     =cut
292 :    
293 :     sub Now {
294 :     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
295 :     my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
296 :     _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
297 : parrello 1.2 return $retVal;
298 : olson 1.1 }
299 :    
300 :     # Pad a number to 2 digits.
301 :     sub _p2 {
302 :     my ($value) = @_;
303 :     $value = "0$value" if ($value < 10);
304 :     return $value;
305 :     }
306 :    
307 :     =head3 LogErrors
308 :    
309 :     C<< Tracer::LogErrors($fileName); >>
310 :    
311 :     Route the standard error output to a log file.
312 :    
313 :     =over 4
314 :    
315 :     =item fileName
316 :    
317 :     Name of the file to receive the error output.
318 :    
319 :     =back
320 :    
321 :     =cut
322 :    
323 :     sub LogErrors {
324 :     # Get the file name.
325 :     my ($fileName) = @_;
326 :     # Open the file as the standard error output.
327 :     open STDERR, '>', $fileName;
328 :     }
329 :    
330 : parrello 1.5 =head3 ReadOptions
331 :    
332 :     C<< my %options = Tracer::ReadOptions($fileName); >>
333 :    
334 :     Read a set of options from a file. Each option is encoded in a line of text that has the
335 :     format
336 :    
337 :     I<optionName>C<=>I<optionValue>C<; >I<comment>
338 :    
339 :     The option name must consist entirely of letters, digits, and the punctuation characters
340 : parrello 1.9 C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
341 :     character is a semi-colon will be ignored. The return hash will map each option name to
342 : parrello 1.5 the corresponding option value.
343 :    
344 :     =over 4
345 :    
346 :     =item fileName
347 :    
348 :     Name of the file containing the option data.
349 :    
350 :     =item RETURN
351 :    
352 :     Returns a hash mapping the option names specified in the file to their corresponding option
353 :     value.
354 :    
355 :     =back
356 :    
357 :     =cut
358 :    
359 :     sub ReadOptions {
360 :     # Get the parameters.
361 :     my ($fileName) = @_;
362 :     # Open the file.
363 :     (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
364 :     # Count the number of records read.
365 :     my ($records, $comments) = 0;
366 :     # Create the return hash.
367 :     my %retVal = ();
368 :     # Loop through the file, accumulating key-value pairs.
369 :     while (my $line = <CONFIGFILE>) {
370 :     # Denote we've read a line.
371 :     $records++;
372 :     # Determine the line type.
373 :     if ($line =~ /^\s*[\n\r]/) {
374 :     # A blank line is a comment.
375 :     $comments++;
376 :     } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
377 :     # Here we have an option assignment.
378 :     retVal{$1} = $2;
379 :     } elsif ($line =~ /^\s*;/) {
380 :     # Here we have a text comment.
381 :     $comments++;
382 :     } else {
383 :     # Here we have an invalid line.
384 :     Trace("Invalid option statement in record $records.") if T(0);
385 :     }
386 :     }
387 :     # Return the hash created.
388 :     return %retVal;
389 :     }
390 :    
391 : olson 1.1 =head3 GetOptions
392 :    
393 :     C<< Tracer::GetOptions(\%defaults, \%options); >>
394 :    
395 :     Merge a specified set of options into a table of defaults. This method takes two hash references
396 :     as input and uses the data from the second to update the first. If the second does not exist,
397 :     there will be no effect. An error will be thrown if one of the entries in the second hash does not
398 :     exist in the first.
399 :    
400 :     Consider the following example.
401 :    
402 :     C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>
403 :    
404 :     In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
405 :     B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
406 :     B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
407 :     the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
408 :     will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
409 :    
410 :     C<< {databaseType => 'Oracle'} >>
411 :    
412 :     an error will occur because the B<databaseType> option does not exist.
413 :    
414 :     =over 4
415 :    
416 :     =item defaults
417 :    
418 :     Table of default option values.
419 :    
420 :     =item options
421 :    
422 :     Table of overrides, if any.
423 :    
424 :     =item RETURN
425 :    
426 :     Returns a reference to the default table passed in as the first parameter.
427 :    
428 :     =back
429 :    
430 :     =cut
431 :    
432 :     sub GetOptions {
433 :     # Get the parameters.
434 :     my ($defaults, $options) = @_;
435 :     # Check for overrides.
436 :     if ($options) {
437 :     # Loop through the overrides.
438 :     while (my ($option, $setting) = each %{$options}) {
439 :     # Insure this override exists.
440 :     if (!exists $defaults->{$option}) {
441 :     croak "Unrecognized option $option encountered.";
442 :     } else {
443 :     # Apply the override.
444 :     $defaults->{$option} = $setting;
445 :     }
446 :     }
447 :     }
448 :     # Return the merged table.
449 :     return $defaults;
450 :     }
451 :    
452 :     =head3 MergeOptions
453 :    
454 :     C<< Tracer::MergeOptions(\%table, \%defaults); >>
455 :    
456 :     Merge default values into a hash table. This method looks at the key-value pairs in the
457 :     second (default) hash, and if a matching key is not found in the first hash, the default
458 :     pair is copied in. The process is similar to L</GetOptions>, but there is no error-
459 :     checking and no return value.
460 :    
461 :     =over 4
462 :    
463 :     =item table
464 :    
465 :     Hash table to be updated with the default values.
466 :    
467 :     =item defaults
468 :    
469 :     Default values to be merged into the first hash table if they are not already present.
470 :    
471 :     =back
472 :    
473 :     =cut
474 :    
475 :     sub MergeOptions {
476 :     # Get the parameters.
477 :     my ($table, $defaults) = @_;
478 :     # Loop through the defaults.
479 :     while (my ($key, $value) = each %{$defaults}) {
480 :     if (!exists $table->{$key}) {
481 :     $table->{$key} = $value;
482 :     }
483 :     }
484 :     }
485 :    
486 :     =head3 Trace
487 :    
488 :     C<< Trace($message); >>
489 :    
490 :     Write a trace message to the target location specified in L</TSetup>. If there has not been
491 :     any prior call to B<TSetup>.
492 :    
493 :     =over 4
494 :    
495 :     =item message
496 :    
497 :     Message to write.
498 :    
499 :     =back
500 :    
501 :     =cut
502 :    
503 :     sub Trace {
504 :     # Get the parameters.
505 :     my ($message) = @_;
506 :     # Get the timestamp.
507 :     my $timeStamp = Now();
508 : parrello 1.9 # Format the message. Note we strip off any line terminators at the end.
509 :     my $formatted = "$timeStamp <$LastCategory>: " . Strip($message);
510 : olson 1.1 # Process according to the destination.
511 :     if ($Destination eq "TEXT") {
512 :     # Write the message to the standard output.
513 : parrello 1.5 print "$formatted\n";
514 :     } elsif ($Destination eq "ERROR") {
515 :     # Write the message to the error output.
516 :     print STDERR "$formatted\n";
517 : olson 1.1 } elsif ($Destination eq "QUEUE") {
518 :     # Push the message into the queue.
519 : parrello 1.5 push @Queue, "$formatted";
520 : olson 1.1 } elsif ($Destination eq "HTML") {
521 :     # Convert the message to HTML and write it to the standard output.
522 :     my $escapedMessage = CGI::escapeHTML($message);
523 : parrello 1.5 print "<p>$formatted</p>\n";
524 : parrello 1.4 } elsif ($Destination eq "WARN") {
525 :     # Emit the message as a warning.
526 :     warn $message;
527 : olson 1.1 } elsif ($Destination =~ m/^>>/) {
528 :     # Write the trace message to an output file.
529 :     open TRACING, $Destination;
530 : parrello 1.5 print TRACING "$formatted\n";
531 : olson 1.1 close TRACING;
532 : parrello 1.10 # If the Tee flag is on, echo it to the standard output.
533 :     if ($TeeFlag) {
534 :     print "$formatted\n";
535 :     }
536 : olson 1.1 }
537 :     }
538 :    
539 :     =head3 T
540 :    
541 : parrello 1.2 C<< my $switch = T($category, $traceLevel); >>
542 : olson 1.1
543 :     or
544 : parrello 1.2
545 : olson 1.1 C<< my $switch = T($traceLevel); >>
546 :    
547 :     Return TRUE if the trace level is at or above a specified value and the specified category
548 :     is active, else FALSE. If no category is specified, the caller's package name is used.
549 :    
550 :     =over 4
551 :    
552 :     =item category
553 :    
554 :     Category to which the message belongs. If not specified, the caller's package name is
555 :     used.
556 :    
557 :     =item traceLevel
558 :    
559 :     Relevant tracing level.
560 :    
561 :     =item RETURN
562 :    
563 :     TRUE if a message at the specified trace level would appear in the trace, else FALSE.
564 :    
565 :     =back
566 :    
567 :     =cut
568 :    
569 :     sub T {
570 :     # Declare the return variable.
571 :     my $retVal = 0;
572 :     # Only proceed if tracing is turned on.
573 :     if ($Destination ne "NONE") {
574 :     # Get the parameters.
575 :     my ($category, $traceLevel) = @_;
576 :     if (!defined $traceLevel) {
577 :     # Here we have no category, so we need to get the calling package.
578 :     $traceLevel = $category;
579 :     my ($package, $fileName, $line) = caller;
580 : parrello 1.3 # If there is no calling package, we default to "main".
581 : olson 1.1 if (!$package) {
582 : parrello 1.3 $category = "main";
583 : olson 1.1 } else {
584 :     $category = $package;
585 :     }
586 :     }
587 : parrello 1.7 # Save the category name.
588 :     $LastCategory = $category;
589 :     # Use the category and tracelevel to compute the result.
590 : olson 1.1 $retVal = ($traceLevel <= $TraceLevel && exists $Categories{$category});
591 : parrello 1.3 }
592 : olson 1.1 # Return the computed result.
593 : parrello 1.3 return $retVal;
594 : olson 1.1 }
595 :    
596 :     =head3 ParseCommand
597 :    
598 :     C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>
599 :    
600 :     Parse a command line consisting of a list of parameters. The initial parameters may be option
601 : parrello 1.2 specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
602 :     off and merged into a table of default options. The remainder of the command line is
603 : olson 1.1 returned as a list of positional arguments. For example, consider the following invocation.
604 :    
605 :     C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>
606 :    
607 :     In this case, the list @words will be treated as a command line. There are two options available,
608 :     B<errors> and B<logFile>. If @words has the following format
609 :    
610 :     C<< -logFile=error.log apple orange rutabaga >>
611 :    
612 :     then at the end of the invocation, C<$options> will be
613 :    
614 :     C<< { errors => 0, logFile => 'error.log' } >>
615 :    
616 :     and C<@arguments> will contain
617 :    
618 :     C<< apple orange rutabaga >>
619 :    
620 : parrello 1.2 The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
621 : olson 1.1 support for quote characters.
622 :    
623 :     =over 4
624 :    
625 :     =item optionTable
626 :    
627 :     Table of default options.
628 :    
629 :     =item inputList
630 :    
631 :     List of words on the command line.
632 :    
633 :     =item RETURN
634 :    
635 :     Returns a reference to the option table and a list of the positional arguments.
636 :    
637 :     =back
638 :    
639 :     =cut
640 :    
641 :     sub ParseCommand {
642 :     # Get the parameters.
643 :     my ($optionTable, @inputList) = @_;
644 :     # Process any options in the input list.
645 :     my %overrides = ();
646 :     while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {
647 :     # Get the current option.
648 :     my $arg = shift @inputList;
649 :     # Pull out the option name.
650 :     $arg =~ /^-([^=]*)/g;
651 :     my $name = $1;
652 :     # Check for an option value.
653 :     if ($arg =~ /\G=(.*)$/g) {
654 :     # Here we have a value for the option.
655 :     $overrides{$name} = UnEscape($1);
656 :     } else {
657 :     # Here there is no value, so we use 1.
658 :     $overrides{$name} = 1;
659 :     }
660 :     }
661 :     # Merge the options into the defaults.
662 :     GetOptions($optionTable, \%overrides);
663 :     # Translate the remaining parameters.
664 :     my @retVal = ();
665 :     for my $inputParm (@inputList) {
666 :     push @retVal, UnEscape($inputParm);
667 :     }
668 :     # Return the results.
669 :     return ($optionTable, @retVal);
670 :     }
671 :    
672 : parrello 1.9 =head3 Escape
673 :    
674 :     C<< my $codedString = Tracer::Escape($realString); >>
675 :    
676 :     Escape a string for use in a command length. Spaces will be replaced by C<\b>,
677 :     tabs replaced by C<\t>, new-lines replaced by C<\n>, and backslashes will be
678 :     doubled. The effect is to exactly reverse the effect of L</UnEscape>.
679 :    
680 :     =over 4
681 :    
682 :     =item realString
683 :    
684 :     String to escape.
685 :    
686 :     =item RETURN
687 :    
688 :     Escaped equivalent of the real string.
689 :    
690 :     =back
691 :    
692 :     =cut
693 :    
694 :     sub Escape {
695 :     # Get the parameter.
696 :     my ($realString) = @_;
697 :     # Initialize the return variable.
698 :     my $retVal = "";
699 :     # Loop through the parameter string, looking for sequences to escape.
700 :     while (length $realString > 0) {
701 :     # Look for the first sequence to escape.
702 :     if ($realString =~ /^(.*?)([ \n\t\\])/) {
703 :     # Here we found it. The text preceding the sequence is in $1. The sequence
704 :     # itself is in $2. First, move the clear text to the return variable.
705 :     $retVal .= $1;
706 :     $realString = substr $realString, (length $2 + length $1);
707 :     # Encode the escape sequence.
708 :     my $char = $2;
709 :     $char =~ tr/ \t\n/btn/;
710 :     $retVal .= "\\" . $char;
711 :     } else {
712 :     # Here there are no more escape sequences. The rest of the string is
713 :     # transferred unmodified.
714 :     $retVal .= $realString;
715 :     $realString = "";
716 :     }
717 :     }
718 :     # Return the result.
719 :     return $retVal;
720 :     }
721 :    
722 : olson 1.1 =head3 UnEscape
723 :    
724 :     C<< my $realString = Tracer::UnEscape($codedString); >>
725 :    
726 :     Replace escape sequences with their actual equivalents. C<\b> will be replaced by a space,
727 :     C<\t> by a tab, C<\n> by a new-line character, and C<\\> by a back-slash.
728 :    
729 :     =over 4
730 :    
731 :     =item codedString
732 :    
733 :     String to un-escape.
734 :    
735 :     =item RETURN
736 :    
737 :     Returns a copy of the original string with the escape sequences converted to their actual
738 :     values.
739 :    
740 :     =back
741 :    
742 :     =cut
743 :    
744 :     sub UnEscape {
745 :     # Get the parameter.
746 :     my ($codedString) = @_;
747 :     # Initialize the return variable.
748 :     my $retVal = "";
749 : parrello 1.9 # Only proceed if the incoming string is nonempty.
750 :     if (defined $codedString) {
751 :     # Loop through the parameter string, looking for escape sequences. We can't do
752 :     # translating because it causes problems with the escaped slash. ("\\b" becomes
753 :     # "\ " no matter what we do.)
754 :     while (length $codedString > 0) {
755 :     # Look for the first escape sequence.
756 :     if ($codedString =~ /^(.*?)\\(\\|b|n|t)/) {
757 :     # Here we found it. The text preceding the sequence is in $1. The sequence
758 :     # itself is in $2. First, move the clear text to the return variable.
759 :     $retVal .= $1;
760 :     $codedString = substr $codedString, (2 + length $1);
761 :     # Decode the escape sequence.
762 :     my $char = $2;
763 :     $char =~ tr/\\btn/\\ \t\n/;
764 :     $retVal .= $char;
765 :     } else {
766 :     # Here there are no more escape sequences. The rest of the string is
767 :     # transferred unmodified.
768 :     $retVal .= $codedString;
769 :     $codedString = "";
770 :     }
771 : olson 1.1 }
772 :     }
773 :     # Return the result.
774 : parrello 1.2 return $retVal;
775 : olson 1.1 }
776 :    
777 :     =head3 ParseRecord
778 :    
779 :     C<< my @fields = Tracer::ParseRecord($line); >>
780 :    
781 :     Parse a tab-delimited data line. The data line is split into field values. Embedded tab
782 :     and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
783 :     These will automatically be converted.
784 :    
785 :     =over 4
786 :    
787 :     =item line
788 :    
789 :     Line of data containing the tab-delimited fields.
790 :    
791 :     =item RETURN
792 :    
793 :     Returns a list of the fields found in the data line.
794 :    
795 :     =back
796 :    
797 :     =cut
798 :    
799 :     sub ParseRecord {
800 :     # Get the parameter.
801 :     my ($line) = @_;
802 :     # Remove the trailing new-line, if any.
803 :     chomp $line;
804 :     # Split the line read into pieces using the tab character.
805 :     my @retVal = split /\t/, $line;
806 :     # Trim and fix the escapes in each piece.
807 :     for my $value (@retVal) {
808 :     # Trim leading whitespace.
809 :     $value =~ s/^\s+//;
810 :     # Trim trailing whitespace.
811 :     $value =~ s/\s+$//;
812 :     # Delete the carriage returns.
813 :     $value =~ s/\r//g;
814 :     # Convert the escapes into their real values.
815 :     $value =~ s/\\t/"\t"/ge;
816 :     $value =~ s/\\n/"\n"/ge;
817 :     }
818 :     # Return the result.
819 :     return @retVal;
820 :     }
821 :    
822 :     =head3 Merge
823 :    
824 :     C<< my @mergedList = Tracer::Merge(@inputList); >>
825 :    
826 :     Sort a list of strings and remove duplicates.
827 :    
828 :     =over 4
829 :    
830 :     =item inputList
831 :    
832 :     List of scalars to sort and merge.
833 :    
834 :     =item RETURN
835 :    
836 :     Returns a list containing the same elements sorted in ascending order with duplicates
837 :     removed.
838 :    
839 :     =back
840 :    
841 :     =cut
842 :    
843 :     sub Merge {
844 :     # Get the input list in sort order.
845 :     my @inputList = sort @_;
846 :     # Only proceed if the list has at least two elements.
847 :     if (@inputList > 1) {
848 :     # Now we want to move through the list splicing out duplicates.
849 :     my $i = 0;
850 :     while ($i < @inputList) {
851 :     # Get the current entry.
852 :     my $thisEntry = $inputList[$i];
853 :     # Find out how many elements duplicate the current entry.
854 :     my $j = $i + 1;
855 :     my $dup1 = $i + 1;
856 :     while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
857 :     # If the number is nonzero, splice out the duplicates found.
858 :     if ($j > $dup1) {
859 :     splice @inputList, $dup1, $j - $dup1;
860 :     }
861 :     # Now the element at position $dup1 is different from the element before it
862 :     # at position $i. We push $i forward one position and start again.
863 :     $i++;
864 :     }
865 :     }
866 :     # Return the merged list.
867 :     return @inputList;
868 :     }
869 :    
870 :     =head3 GetFile
871 :    
872 : parrello 1.6 C<< my @fileContents = Tracer::GetFile($fileName); >>
873 : olson 1.1
874 :     Return the entire contents of a file.
875 :    
876 :     =over 4
877 :    
878 :     =item fileName
879 :    
880 :     Name of the file to read.
881 :    
882 :     =item RETURN
883 :    
884 : parrello 1.6 In a list context, returns the entire file as a list with the line terminators removed.
885 :     In a scalar context, returns the entire file as a string.
886 : olson 1.1
887 :     =back
888 :    
889 :     =cut
890 :    
891 :     sub GetFile {
892 :     # Get the parameters.
893 :     my ($fileName) = @_;
894 :     # Declare the return variable.
895 : parrello 1.6 my @retVal = ();
896 : olson 1.1 # Open the file for input.
897 :     my $ok = open INPUTFILE, "<$fileName";
898 :     if (!$ok) {
899 : parrello 1.6 # If we had an error, trace it. We will automatically return a null value.
900 :     Trace("Could not open \"$fileName\" for input.") if T(0);
901 : olson 1.1 } else {
902 : parrello 1.9 # Read the whole file into the return variable, stripping off any terminator
903 : parrello 1.6 # characters.
904 :     my $lineCount = 0;
905 :     while (my $line = <INPUTFILE>) {
906 :     $lineCount++;
907 : parrello 1.9 $line = Strip($line);
908 : parrello 1.6 push @retVal, $line;
909 : olson 1.1 }
910 :     # Close it.
911 :     close INPUTFILE;
912 : parrello 1.6 my $actualLines = @retVal;
913 : olson 1.1 }
914 : parrello 1.6 # Return the file's contents in the desired format.
915 : parrello 1.9 if (wantarray) {
916 : parrello 1.6 return @retVal;
917 :     } else {
918 :     return join "\n", @retVal;
919 :     }
920 : olson 1.1 }
921 :    
922 :     =head3 QTrace
923 :    
924 :     C<< my $data = QTrace($format); >>
925 :    
926 :     Return the queued trace data in the specified format.
927 :    
928 :     =over 4
929 :    
930 :     =item format
931 :    
932 :     C<html> to format the data as an HTML list, C<text> to format it as straight text.
933 :    
934 :     =back
935 :    
936 :     =cut
937 :    
938 :     sub QTrace {
939 :     # Get the parameter.
940 :     my ($format) = @_;
941 :     # Create the return variable.
942 :     my $retVal = "";
943 :     # Process according to the format.
944 :     if ($format =~ m/^HTML$/i) {
945 :     # Convert the queue into an HTML list.
946 :     $retVal = "<ul>\n";
947 :     for my $line (@Queue) {
948 :     my $escapedLine = CGI::escapeHTML($line);
949 :     $retVal .= "<li>$escapedLine</li>\n";
950 :     }
951 :     $retVal .= "</ul>\n";
952 :     } elsif ($format =~ m/^TEXT$/i) {
953 :     # Convert the queue into a list of text lines.
954 :     $retVal = join("\n", @Queue) . "\n";
955 :     }
956 :     # Clear the queue.
957 :     @Queue = ();
958 :     # Return the formatted list.
959 :     return $retVal;
960 :     }
961 :    
962 :     =head3 Confess
963 :    
964 :     C<< Confess($message); >>
965 :    
966 :     Trace the call stack and abort the program with the specified message. The stack
967 :     trace will only appear if the trace level for this package is 1 or more. When used with
968 : parrello 1.9 the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
969 : parrello 1.6 So, for example
970 : olson 1.1
971 : parrello 1.6 C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
972 : olson 1.1
973 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
974 :    
975 :     =over 4
976 :    
977 :     =item message
978 :    
979 :     Message to include in the trace.
980 :    
981 :     =back
982 :    
983 :     =cut
984 :    
985 :     sub Confess {
986 :     # Get the parameters.
987 :     my ($message) = @_;
988 :     # Trace the call stack.
989 :     Cluck($message) if T(1);
990 :     # Abort the program.
991 : parrello 1.5 croak(">>> $message");
992 : olson 1.1 }
993 :    
994 : parrello 1.6 =head3 Assert
995 :    
996 :     C<< Assert($condition1, $condition2, ... $conditionN); >>
997 :    
998 :     Return TRUE if all the conditions are true. This method can be used in conjunction with
999 :     the OR operator and the L</Confess> method, B<Assert> can function as a debugging assert.
1000 :     So, for example
1001 :    
1002 :     C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
1003 :    
1004 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
1005 :    
1006 :     =cut
1007 :     sub Assert {
1008 :     my $retVal = 1;
1009 :     LOOP: for my $condition (@_) {
1010 :     if (! $condition) {
1011 :     $retVal = 0;
1012 :     last LOOP;
1013 :     }
1014 :     }
1015 :     return $retVal;
1016 :     }
1017 :    
1018 : olson 1.1 =head3 Cluck
1019 :    
1020 :     C<< Cluck($message); >>
1021 :    
1022 :     Trace the call stack. Note that for best results, you should qualify the call with a
1023 :     trace condition. For example,
1024 :    
1025 :     C<< Cluck("Starting record parse.") if T(3); >>
1026 :    
1027 :     will only trace the stack if the trace level for the package is 3 or more.
1028 :    
1029 :     =over 4
1030 :    
1031 :     =item message
1032 :    
1033 :     Message to include in the trace.
1034 :    
1035 :     =back
1036 :    
1037 :     =cut
1038 :    
1039 :     sub Cluck {
1040 :     # Get the parameters.
1041 :     my ($message) = @_;
1042 : parrello 1.5 # Trace what's happening.
1043 :     Trace("Stack trace for event: $message");
1044 : olson 1.1 my $confession = longmess($message);
1045 : parrello 1.5 # Convert the confession to a series of trace messages. Note we skip any
1046 :     # messages relating to calls into Tracer.
1047 : olson 1.1 for my $line (split /\s*\n/, $confession) {
1048 : parrello 1.5 Trace($line) if ($line !~ /Tracer\.pm/);
1049 : olson 1.1 }
1050 :     }
1051 :    
1052 : parrello 1.5 =head3 Min
1053 :    
1054 :     C<< my $min = Min($value1, $value2, ... $valueN); >>
1055 :    
1056 :     Return the minimum argument. The arguments are treated as numbers.
1057 :    
1058 :     =over 4
1059 :    
1060 :     =item $value1, $value2, ... $valueN
1061 :    
1062 :     List of numbers to compare.
1063 :    
1064 :     =item RETURN
1065 :    
1066 :     Returns the lowest number in the list.
1067 :    
1068 :     =back
1069 :    
1070 :     =cut
1071 :    
1072 :     sub Min {
1073 :     # Get the parameters. Note that we prime the return value with the first parameter.
1074 :     my ($retVal, @values) = @_;
1075 :     # Loop through the remaining parameters, looking for the lowest.
1076 :     for my $value (@values) {
1077 :     if ($value < $retVal) {
1078 :     $retVal = $value;
1079 :     }
1080 :     }
1081 :     # Return the minimum found.
1082 :     return $retVal;
1083 :     }
1084 :    
1085 :     =head3 Max
1086 :    
1087 :     C<< my $max = Max($value1, $value2, ... $valueN); >>
1088 :    
1089 :     Return the maximum argument. The arguments are treated as numbers.
1090 :    
1091 :     =over 4
1092 :    
1093 :     =item $value1, $value2, ... $valueN
1094 :    
1095 :     List of numbers to compare.
1096 :    
1097 :     =item RETURN
1098 :    
1099 :     Returns the highest number in the list.
1100 :    
1101 :     =back
1102 :    
1103 :     =cut
1104 :    
1105 :     sub Max {
1106 :     # Get the parameters. Note that we prime the return value with the first parameter.
1107 :     my ($retVal, @values) = @_;
1108 :     # Loop through the remaining parameters, looking for the highest.
1109 :     for my $value (@values) {
1110 :     if ($value > $retVal) {
1111 :     $retVal = $value;
1112 :     }
1113 :     }
1114 :     # Return the maximum found.
1115 :     return $retVal;
1116 :     }
1117 :    
1118 :     =head3 AddToListMap
1119 :    
1120 :     C<< Tracer::AddToListMap(\%hash, $key, $value); >>
1121 :    
1122 :     Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list
1123 :     is created for the key. Otherwise, the new value is pushed onto the list.
1124 :    
1125 :     =over 4
1126 :    
1127 :     =item hash
1128 :    
1129 :     Reference to the target hash.
1130 :    
1131 :     =item key
1132 :    
1133 :     Key for which the value is to be added.
1134 :    
1135 :     =item value
1136 :    
1137 :     Value to add to the key's value list.
1138 :    
1139 :     =back
1140 :    
1141 :     =cut
1142 :    
1143 :     sub AddToListMap {
1144 :     # Get the parameters.
1145 :     my ($hash, $key, $value) = @_;
1146 :     # Process according to whether or not the key already has a value.
1147 :     if (! exists $hash->{$key}) {
1148 :     $hash->{$key} = [$value];
1149 :     } else {
1150 :     push @{$hash->{$key}}, $value;
1151 :     }
1152 :     }
1153 : olson 1.1
1154 : parrello 1.7 =head3 DebugMode
1155 :    
1156 :     C<< if (Tracer::DebugMode) { ...code... } >>
1157 :    
1158 :     Return TRUE if debug mode has been turned on in FIG_Config, else output
1159 :     an error page and return FALSE.
1160 :    
1161 :     Certain CGI scripts are too dangerous to exist in the production
1162 :     environment. This method provides a simple way to prevent them
1163 :     from working unless they are explicitly turned on in the configuration
1164 :     file by setting C<$FIG_Config::debug_mode> to 1. If debugging mode
1165 :     is not turned on, an error web page will be output.
1166 :    
1167 :     =cut
1168 :    
1169 :     sub DebugMode {
1170 :     # Declare the return variable.
1171 :     my $retVal;
1172 :     # Check the debug configuration.
1173 :     if ($FIG_Config::debug_mode) {
1174 :     $retVal = 1;
1175 :     } else {
1176 :     # Here debug mode is off, so we generate an error page.
1177 : parrello 1.9 my $pageString = PageBuilder::Build("<Html/ErrorPage.html", {}, "Html");
1178 :     print $pageString;
1179 :     }
1180 :     # Return the determination indicator.
1181 :     return $retVal;
1182 :     }
1183 :    
1184 :     =head3 Strip
1185 :    
1186 :     C<< my $string = Tracer::Strip($line); >>
1187 :    
1188 :     Strip all line terminators off a string. This is necessary when dealing with files
1189 :     that may have been transferred back and forth several times among different
1190 :     operating environments.
1191 :    
1192 :     =over 4
1193 :    
1194 :     =item line
1195 :    
1196 :     Line of text to be stripped.
1197 :    
1198 :     =item RETURN
1199 :    
1200 :     The same line of text with all the line-ending characters chopped from the end.
1201 :    
1202 :     =back
1203 :    
1204 :     =cut
1205 :    
1206 :     sub Strip {
1207 :     # Get a copy of the parameter string.
1208 :     my ($string) = @_;
1209 :     my $retVal = $string;
1210 :     # Strip the line terminator characters.
1211 :     $retVal =~ s/(\r|\n)+$//g;
1212 :     # Return the result.
1213 :     return $retVal;
1214 :     }
1215 :    
1216 :     =head3 Pad
1217 :    
1218 :     C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>
1219 :    
1220 :     Pad a string to a specified length. The pad character will be a
1221 :     space, and the padding will be on the right side unless specified
1222 :     in the third parameter.
1223 :    
1224 :     =over 4
1225 :    
1226 :     =item string
1227 :    
1228 :     String to be padded.
1229 :    
1230 :     =item len
1231 :    
1232 :     Desired length of the padded string.
1233 :    
1234 :     =item left (optional)
1235 :    
1236 :     TRUE if the string is to be left-padded; otherwise it will be padded on the right.
1237 :    
1238 :     =item padChar (optional)
1239 :    
1240 :     =item RETURN
1241 :    
1242 :     Returns a copy of the original string with the spaces added to the specified end so
1243 :     that it achieves the desired length.
1244 :    
1245 :     =back
1246 :    
1247 :     =cut
1248 :    
1249 :     sub Pad {
1250 :     # Get the parameters.
1251 :     my ($string, $len, $left, $padChar) = @_;
1252 :     # Compute the padding character.
1253 :     if (! defined $padChar) {
1254 :     $padChar = " ";
1255 :     }
1256 :     # Compute the number of spaces needed.
1257 :     my $needed = $len - length $string;
1258 :     # Copy the string into the return variable.
1259 :     my $retVal = $string;
1260 :     # Only proceed if padding is needed.
1261 :     if ($needed > 0) {
1262 :     # Create the pad string.
1263 :     my $pad = $padChar x $needed;
1264 :     # Affix it to the return value.
1265 :     if ($left) {
1266 :     $retVal = $pad . $retVal;
1267 :     } else {
1268 :     $retVal .= $pad;
1269 : redwards 1.8 }
1270 : parrello 1.7 }
1271 : parrello 1.9 # Return the result.
1272 : parrello 1.7 return $retVal;
1273 :     }
1274 :    
1275 : redwards 1.8 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3