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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

1 : olson 1.30 #
2 :     # Copyright (c) 2003-2006 University of Chicago and Fellowship
3 :     # for Interpretations of Genomes. All Rights Reserved.
4 :     #
5 :     # This file is part of the SEED Toolkit.
6 :     #
7 :     # The SEED Toolkit is free software. You can redistribute
8 :     # it and/or modify it under the terms of the SEED Toolkit
9 :     # Public License.
10 :     #
11 :     # You should have received a copy of the SEED Toolkit Public License
12 :     # along with this program; if not write to the University of Chicago
13 :     # at info@ci.uchicago.edu or the Fellowship for Interpretation of
14 :     # Genomes at veronika@thefig.info or download a copy from
15 :     # http://www.theseed.org/LICENSE.TXT.
16 :     #
17 :    
18 : olson 1.1 package Tracer;
19 :    
20 : parrello 1.12 require Exporter;
21 :     @ISA = ('Exporter');
22 : parrello 1.31 @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup);
23 : parrello 1.12 @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);
24 :     use strict;
25 :     use Carp qw(longmess croak);
26 :     use CGI;
27 :     use FIG_Config;
28 : parrello 1.9 use PageBuilder;
29 : parrello 1.21 use Digest::MD5;
30 : olson 1.1
31 :     =head1 Tracing and Debugging Helpers
32 :    
33 :     =head2 Introduction
34 :    
35 :     This package provides simple tracing for debugging and reporting purposes. To use it simply call the
36 :     L</TSetup> method to set the options and call L</Trace> to write out trace messages. Each trace
37 : parrello 1.2 message has a I<trace level> and I<category> associated with it. In addition, the tracing package itself
38 :     has a list of categories and a single trace level set by the B<TSetup> method. Only messages whose trace
39 : olson 1.1 level is less than or equal to this package's trace level and whose category is activated will
40 : parrello 1.2 be written. Thus, a higher trace level on a message indicates that the message
41 : parrello 1.10 is less likely to be seen. A higher trace level passed to B<TSetup> means more trace messages will
42 : olson 1.1 appear. To generate a trace message, use the following syntax.
43 :    
44 :     C<< Trace($message) if T(errors => 4); >>
45 :    
46 : parrello 1.2 This statement will produce a trace message if the trace level is 4 or more and the C<errors>
47 : parrello 1.3 category is active. Note that the special category C<main> is always active, so
48 : olson 1.1
49 : parrello 1.3 C<< Trace($message) if T(main => 4); >>
50 : olson 1.1
51 :     will trace if the trace level is 4 or more.
52 :    
53 :     If the category name is the same as the package name, all you need is the number. So, if the
54 :     following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is
55 :     active and the trace level is 2 or more.
56 :    
57 :     C<< Trace($message) if T(2); >>
58 :    
59 : parrello 1.10 To set up tracing, you call the L</TSetup> method. The method takes as input a trace level, a list
60 : olson 1.1 of category names, and a set of options. The trace level and list of category names are
61 :     specified as a space-delimited string. Thus
62 :    
63 :     C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>
64 :    
65 : parrello 1.7 sets the trace level to 3, activates the C<errors>, C<Sprout>, and C<ERDB> categories, and
66 : parrello 1.12 specifies that messages should be output as HTML paragraphs.
67 :    
68 :     To turn on tracing for ALL categories, use an asterisk. The call below sets every category to
69 :     level 3 and writes the output to the standard error output. This sort of thing might be
70 :     useful in a CGI environment.
71 :    
72 :     C<< TSetup('3 *', 'WARN'); >>
73 : olson 1.1
74 :     In addition to HTML and file output for trace messages, you can specify that the trace messages
75 :     be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach
76 :     is useful if you are building a web page. Instead of having the trace messages interspersed with
77 :     the page output, they can be gathered together and displayed at the end of the page. This makes
78 :     it easier to debug page formatting problems.
79 :    
80 : parrello 1.4 Finally, you can specify that all trace messages be emitted as warnings.
81 :    
82 : olson 1.1 The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.
83 :     Tracer calls can be left in the code with minimal overhead and then turned on only when needed.
84 :     Thus, debugging information is available and easily retrieved even when the application is
85 :     being used out in the field.
86 :    
87 : parrello 1.10 There is no hard and fast rule on how to use trace levels. The following is therefore only
88 :     a suggestion.
89 :    
90 :     =over 4
91 :    
92 : parrello 1.32 =item Error 0
93 : parrello 1.10
94 :     Message indicates an error that may lead to incorrect results or that has stopped the
95 :     application entirely.
96 :    
97 : parrello 1.32 =item Warning 1
98 : parrello 1.10
99 :     Message indicates something that is unexpected but that probably did not interfere
100 :     with program execution.
101 :    
102 : parrello 1.32 =item Notice 2
103 : parrello 1.10
104 :     Message indicates the beginning or end of a major task.
105 :    
106 : parrello 1.32 =item Information 3
107 : parrello 1.10
108 :     Message indicates a subtask. In the FIG system, a subtask generally relates to a single
109 :     genome. This would be a big loop that is not expected to execute more than 500 times or so.
110 :    
111 : parrello 1.32 =item Detail 4
112 : parrello 1.10
113 :     Message indicates a low-level loop iteration.
114 :    
115 :     =back
116 :    
117 : olson 1.1 =cut
118 : parrello 1.2
119 : olson 1.1 # Declare the configuration variables.
120 :    
121 : parrello 1.12 my $Destination = "NONE"; # Description of where to send the trace output.
122 :     my $TeeFlag = 0; # TRUE if output is going to a file and to the
123 :     # standard output
124 : parrello 1.3 my %Categories = ( main => 1 );
125 : parrello 1.12 # hash of active category names
126 :     my $TraceLevel = 0; # trace level; a higher trace level produces more
127 :     # messages
128 :     my @Queue = (); # queued list of trace messages.
129 : parrello 1.7 my $LastCategory = "main"; # name of the last category interrogated
130 : parrello 1.11 my $SetupCount = 0; # number of times TSetup called
131 : parrello 1.12 my $AllTrace = 0; # TRUE if we are tracing all categories.
132 : olson 1.1
133 :     =head2 Public Methods
134 :    
135 :     =head3 TSetup
136 :    
137 :     C<< TSetup($categoryList, $target); >>
138 :    
139 :     This method is used to specify the trace options. The options are stored as package data
140 :     and interrogated by the L</Trace> and L</T> methods.
141 :    
142 :     =over 4
143 :    
144 :     =item categoryList
145 :    
146 :     A string specifying the trace level and the categories to be traced, separated by spaces.
147 :     The trace level must come first.
148 :    
149 :     =item target
150 :    
151 :     The destination for the trace output. To send the trace output to a file, specify the file
152 :     name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended
153 : parrello 1.10 to the file. Otherwise the file is cleared before tracing begins. Precede the first ">"
154 :     symbol with a C<+> to echo output to a file AND to the standard output. In addition to
155 :     sending the trace messages to a file, you can specify a special destination. C<HTML> will
156 :     cause tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>
157 : parrello 1.5 will cause tracing to the standard output as ordinary text. C<ERROR> will cause trace
158 : parrello 1.9 messages to be sent to the standard error output as ordinary text. C<QUEUE> will cause trace
159 : parrello 1.6 messages to be stored in a queue for later retrieval by the L</QTrace> method. C<WARN> will
160 : parrello 1.9 cause trace messages to be emitted as warnings using the B<warn> directive. C<NONE> will
161 : parrello 1.6 cause tracing to be suppressed.
162 : olson 1.1
163 :     =back
164 :    
165 :     =cut
166 :    
167 :     sub TSetup {
168 : parrello 1.12 # Get the parameters.
169 :     my ($categoryList, $target) = @_;
170 :     # Parse the category list.
171 :     my @categoryData = split /\s+/, $categoryList;
172 :     # Extract the trace level.
173 :     $TraceLevel = shift @categoryData;
174 :     # Presume category-based tracing until we learn otherwise.
175 :     $AllTrace = 0;
176 :     # Build the category hash. Note that if we find a "*", we turn on non-category
177 : parrello 1.33 # tracing. We must also clear away any pre-existing data.
178 : parrello 1.34 %Categories = ( main => 1 );
179 : parrello 1.12 for my $category (@categoryData) {
180 :     if ($category eq '*') {
181 :     $AllTrace = 1;
182 :     } else {
183 : parrello 1.13 $Categories{lc $category} = 1;
184 : parrello 1.12 }
185 :     }
186 :     # Now we need to process the destination information. The most important special
187 :     # cases are the single ">", which requires we clear the file first, and the
188 :     # "+" prefix which indicates a double echo.
189 :     if ($target =~ m/^\+?>>?/) {
190 :     if ($target =~ m/^\+/) {
191 :     $TeeFlag = 1;
192 :     $target = substr($target, 1);
193 :     }
194 :     if ($target =~ m/^>[^>]/) {
195 :     open TRACEFILE, $target;
196 :     print TRACEFILE Now() . " Tracing initialized.\n";
197 :     close TRACEFILE;
198 :     $Destination = ">$target";
199 :     } else {
200 :     $Destination = $target;
201 :     }
202 :     } else {
203 :     $Destination = uc($target);
204 :     }
205 :     # Increment the setup counter.
206 :     $SetupCount++;
207 : parrello 1.11 }
208 :    
209 : parrello 1.31 =head3 StandardSetup
210 :    
211 :     C<< my ($options, @parameters) = StandardSetup(\@categories, \%options, @ARGV); >>
212 :    
213 :     This method performs standard command-line parsing and tracing setup. The return
214 :     values are a hash of the command-line options and a list of the positional
215 :     parameters. Tracing is automatically set up and the command-line options are
216 :     validated.
217 :    
218 :     This is a complex method that does a lot of grunt work. The parameters can
219 :     be more easily understood, however, once they are examined individually.
220 :    
221 :     The I<categories> parameter is the most obtuse. It is a reference to a list of
222 :     special-purpose tracing categories. Most tracing categories are PERL package
223 :     names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
224 :     B<ERDB>, and B<SproutLoad> packages, you would specify the categories
225 :    
226 :     ["Sprout", "SproutLoad", "ERDB"]
227 :    
228 :     This would cause trace messages in the specified three packages to appear in
229 :     the output. There are threer special tracing categories that are automatically
230 :     handled by this method. In other words, if you used L</TSetup> you would need
231 :     to include these categories manually, but if you use this method they are turned
232 :     on automatically.
233 :    
234 :     =over 4
235 :    
236 :     =item FIG
237 :    
238 :     Turns on trace messages inside the B<FIG> package.
239 :    
240 :     =item SQL
241 :    
242 :     Traces SQL commands and activity.
243 :    
244 :     =item Tracer
245 :    
246 :     Traces error messages and call stacks.
247 :    
248 :     =back
249 :    
250 :     C<SQL> is only turned on if the C<-sql> option is specified in the command line.
251 :     The trace level is specified using the C<-trace> command-line option. For example,
252 :     the following command line for C<TransactFeatures> turns on SQL tracing and runs
253 :     all tracing at level 3.
254 :    
255 :     TransactFeatures -trace=3 -sql register ../xacts IDs.tbl
256 :    
257 :     Standard tracing is output to the standard output and echoed to the file
258 :     C<trace.log> in the FIG temporary directory.
259 :    
260 :     The default trace level is 3. This dumps out all SQL commands if SQL tracing
261 :     is turned on and tends to produce one flurry of messages per genome. To get all
262 :     messages, specify a trace level of 4. For generally quiet output, use 2.
263 :    
264 :     The I<options> parameter is a reference to a hash containing the command-line
265 :     options and their default values. Command-line options may be in the form of switches
266 :     or keywords. In the case of a switch, the option value is 1 if it is specified and
267 :     0 if it is not specified. In the case of a keyword, the value is separated from the
268 :     option name by an equal sign. You can see this last in the command-line example above.
269 :    
270 :     An example at this point would help. Consider, for example, the command-line utility
271 :     C<TransactFeatures>. It accepts a list of positional parameters plus the options
272 :     C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
273 :     the following code.
274 :    
275 :     my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
276 :     { trace => 3, sql => 0,
277 :     safe => 0, noAlias => 0,
278 :     start => ' ', tblFiles => 0},
279 :     @ARGV);
280 :    
281 :    
282 :     The call to C<ParseCommand> specifies the default values for the options and
283 :     stores the actual options in a hash that is returned as C<$options>. The
284 :     positional parameters are returned in C<@parameters>.
285 :    
286 :     The following is a sample command line for C<TransactFeatures>.
287 :    
288 :     TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
289 :    
290 :     In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
291 :     parameters, and would find themselves in I<@parameters> after executing the
292 :     above code fragment. The tracing would be set to level 2, and the categories
293 :     would be C<FIG>, C<Tracer>, and <DocUtils>. C<FIG> and C<Tracer> are standard,
294 :     and C<DocUtils> was included because it came in within the first parameter
295 :     to this method. The I<$options> hash would be
296 :    
297 :     { trace => 2, sql => 0, safe => 0,
298 :     noAlias => 1, start => ' ', tblFiles => 0 }
299 :    
300 :     Use of C<StandardSetup> in this way provides a simple way of performing
301 :     standard tracing setup and command-line parsing. Note that the caller is
302 :     not even aware of the command-line switches C<-trace> and C<-sql>, which
303 :     are used by this method to control the tracing. If additional tracing features
304 :     need to be added in the future, they can be processed by this method without
305 :     upsetting the command-line utilities.
306 :    
307 :     The parameters to this method are as follows.
308 :    
309 :     =over 4
310 :    
311 :     =item categories
312 :    
313 :     Reference to a list of tracing category names. These should be names of
314 :     packages whose internal workings will need to be debugged to get the
315 :     command working.
316 :    
317 :     =item options
318 :    
319 :     Reference to a hash containing the legal options for the current command mapped
320 :     to their default values. The use can override the defaults by specifying the
321 :     options as command-line switches prefixed by a hyphen. Tracing-related options
322 :     may be added to this hash.
323 :    
324 :     =item ARGV
325 :    
326 :     List of command line parameters, including the option switches, which must
327 :     precede the positional parameters and be prefixed by a hyphen.
328 :    
329 :     =item RETURN
330 :    
331 :     Returns a list. The first element of the list is the reference to a hash that
332 :     maps the command-line option switches to their values. These will either be the
333 :     default values or overrides specified on the command line. The remaining
334 :     elements of the list are the position parameters, in order.
335 :    
336 :     =back
337 :    
338 :     =cut
339 :    
340 :     sub StandardSetup {
341 :     # Get the parameters.
342 :     my ($categories, $options, @argv) = @_;
343 :     # Add the tracing options.
344 :     $options->{trace} = 3;
345 :     $options->{sql} = 0;
346 :     # Parse the command line.
347 :     my ($retOptions, @retParameters) = ParseCommand($options, @argv);
348 :     # Now we want to set up tracing. First, we need to know if SQL is to
349 :     # be traced.
350 :     my @cats = @{$categories};
351 :     if ($retOptions->{sql}) {
352 :     push @cats, "SQL";
353 :     }
354 :     # Add the default categories.
355 :     push @cats, "Tracer", "FIG";
356 :     # Next, we create the category string by prefixing the trace level
357 :     # and joining the categories.
358 :     my $cats = join(" ", $options->{trace}, @cats);
359 :     # Now set up the tracing.
360 :     TSetup($cats, "+>$FIG_Config::temp/trace.log");
361 :     # Return the parsed parameters.
362 :     return ($retOptions, @retParameters);
363 :     }
364 :    
365 : parrello 1.11 =head3 Setups
366 :    
367 :     C<< my $count = Tracer::Setups(); >>
368 :    
369 :     Return the number of times L</TSetup> has been called.
370 :    
371 :     This method allows for the creation of conditional tracing setups where, for example, we
372 :     may want to set up tracing if nobody else has done it before us.
373 :    
374 :     =cut
375 :    
376 :     sub Setups {
377 : parrello 1.12 return $SetupCount;
378 : olson 1.1 }
379 :    
380 : parrello 1.10 =head3 Open
381 :    
382 :     C<< my $handle = Open($fileHandle, $fileSpec, $message); >>
383 :    
384 : parrello 1.11 Open a file.
385 : parrello 1.10
386 :     The I<$fileSpec> is essentially the second argument of the PERL C<open>
387 :     function. The mode is specified using Unix-like shell information. So, for
388 :     example,
389 :    
390 : parrello 1.12 Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
391 : parrello 1.10
392 :     would open for output appended to the specified file, and
393 :    
394 : parrello 1.12 Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
395 : parrello 1.10
396 :     would open a pipe that sorts the records written and removes duplicates. Note
397 : parrello 1.11 the use of file handle syntax in the Open call. To use anonymous file handles,
398 :     code as follows.
399 : parrello 1.10
400 : parrello 1.12 my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
401 : parrello 1.10
402 : parrello 1.11 The I<$message> parameter is used if the open fails. If it is set to C<0>, then
403 :     the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
404 :     failed open will throw an exception and the third parameter will be used to construct
405 :     an error message. If the parameter is omitted, a standard message is constructed
406 :     using the file spec.
407 : parrello 1.10
408 : parrello 1.12 Could not open "/usr/spool/news/twitlog"
409 : parrello 1.10
410 :     Note that the mode characters are automatically cleaned from the file name.
411 :     The actual error message from the file system will be captured and appended to the
412 :     message in any case.
413 :    
414 : parrello 1.12 Could not open "/usr/spool/news/twitlog": file not found.
415 : parrello 1.10
416 :     In some versions of PERL the only error message we get is a number, which
417 :     corresponds to the C++ C<errno> value.
418 :    
419 : parrello 1.12 Could not open "/usr/spool/news/twitlog": 6.
420 : parrello 1.10
421 :     =over 4
422 :    
423 :     =item fileHandle
424 :    
425 :     File handle. If this parameter is C<undef>, a file handle will be generated
426 :     and returned as the value of this method.
427 :    
428 :     =item fileSpec
429 :    
430 :     File name and mode, as per the PERL C<open> function.
431 :    
432 :     =item message (optional)
433 :    
434 :     Error message to use if the open fails. If omitted, a standard error message
435 :     will be generated. In either case, the error information from the file system
436 : parrello 1.11 is appended to the message. To specify a conditional open that does not throw
437 :     an error if it fails, use C<0>.
438 : parrello 1.10
439 :     =item RETURN
440 :    
441 : parrello 1.11 Returns the name of the file handle assigned to the file, or C<undef> if the
442 :     open failed.
443 : parrello 1.10
444 :     =back
445 :    
446 :     =cut
447 :    
448 :     sub Open {
449 : parrello 1.12 # Get the parameters.
450 :     my ($fileHandle, $fileSpec, $message) = @_;
451 :     # Attempt to open the file.
452 :     my $rv = open $fileHandle, $fileSpec;
453 :     # If the open failed, generate an error message.
454 :     if (! $rv) {
455 :     # Save the system error message.
456 :     my $sysMessage = $!;
457 :     # See if we need a default message.
458 :     if (!$message) {
459 :     # Clean any obvious mode characters and leading spaces from the
460 :     # filename.
461 :     my ($fileName) = FindNamePart($fileSpec);
462 :     $message = "Could not open \"$fileName\"";
463 :     }
464 :     # Terminate with an error using the supplied message and the
465 :     # error message from the file system.
466 :     Confess("$message: $!");
467 :     }
468 :     # Return the file handle.
469 :     return $fileHandle;
470 : parrello 1.10 }
471 :    
472 : parrello 1.11 =head3 FindNamePart
473 :    
474 :     C<< my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec); >>
475 :    
476 :     Extract the portion of a file specification that contains the file name.
477 :    
478 :     A file specification is the string passed to an C<open> call. It specifies the file
479 :     mode and name. In a truly complex situation, it can specify a pipe sequence. This
480 :     method assumes that the file name is whatever follows the first angle bracket
481 :     sequence. So, for example, in the following strings the file name is
482 :     C</usr/fig/myfile.txt>.
483 :    
484 :     >>/usr/fig/myfile.txt
485 :     </usr/fig/myfile.txt
486 :     | sort -u > /usr/fig/myfile.txt
487 :    
488 :     If the method cannot find a file name using its normal methods, it will return the
489 :     whole incoming string.
490 :    
491 :     =over 4
492 :    
493 :     =item fileSpec
494 :    
495 :     File specification string from which the file name is to be extracted.
496 :    
497 :     =item RETURN
498 :    
499 :     Returns a three-element list. The first element contains the file name portion of
500 :     the specified string, or the whole string if a file name cannot be found via normal
501 :     methods. The second element contains the start position of the file name portion and
502 :     the third element contains the length.
503 :    
504 :     =back
505 :    
506 :     =cut
507 :     #: Return Type $;
508 :     sub FindNamePart {
509 :     # Get the parameters.
510 :     my ($fileSpec) = @_;
511 : parrello 1.12 # Default to the whole input string.
512 :     my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
513 : parrello 1.11 # Parse out the file name if we can.
514 : parrello 1.12 if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
515 :     $retVal = $2;
516 :     $len = length $retVal;
517 :     $pos = (length $fileSpec) - (length $3) - $len;
518 :     }
519 : parrello 1.11 # Return the result.
520 :     return ($retVal, $pos, $len);
521 :     }
522 :    
523 :     =head3 OpenDir
524 :    
525 : parrello 1.31 C<< my @files = OpenDir($dirName, $filtered, $flag); >>
526 : parrello 1.11
527 :     Open a directory and return all the file names. This function essentially performs
528 :     the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
529 : parrello 1.31 set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),
530 : parrello 1.33 or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be
531 :     filtered out of the return list. If the directory does not open and I<$flag> is not
532 :     set, an exception is thrown. So, for example,
533 : parrello 1.11
534 : parrello 1.12 my @files = OpenDir("/Volumes/fig/contigs", 1);
535 : parrello 1.29
536 : parrello 1.11 is effectively the same as
537 :    
538 : parrello 1.12 opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
539 : parrello 1.33 my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);
540 : parrello 1.11
541 :     Similarly, the following code
542 :    
543 : parrello 1.31 my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);
544 : parrello 1.29
545 : parrello 1.11 Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
546 : parrello 1.31 automatically returns an empty list if the directory fails to open.
547 : parrello 1.11
548 :     =over 4
549 :    
550 :     =item dirName
551 :    
552 :     Name of the directory to open.
553 :    
554 :     =item filtered
555 :    
556 :     TRUE if files whose names begin with a period (C<.>) should be automatically removed
557 :     from the list, else FALSE.
558 :    
559 : parrello 1.31 =item flag
560 :    
561 :     TRUE if a failure to open is okay, else FALSE
562 :    
563 : parrello 1.11 =back
564 :    
565 :     =cut
566 :     #: Return Type @;
567 :     sub OpenDir {
568 :     # Get the parameters.
569 : parrello 1.31 my ($dirName, $filtered, $flag) = @_;
570 : parrello 1.11 # Declare the return variable.
571 : parrello 1.31 my @retVal = ();
572 : parrello 1.12 # Open the directory.
573 :     if (opendir(my $dirHandle, $dirName)) {
574 :     # The directory opened successfully. Get the appropriate list according to the
575 :     # strictures of the filter parameter.
576 :     if ($filtered) {
577 : parrello 1.33 @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;
578 : parrello 1.12 } else {
579 :     @retVal = readdir $dirHandle;
580 :     }
581 : parrello 1.31 } elsif (! $flag) {
582 :     # Here the directory would not open and it's considered an error.
583 : parrello 1.12 Confess("Could not open directory $dirName.");
584 :     }
585 : parrello 1.11 # Return the result.
586 :     return @retVal;
587 :     }
588 :    
589 : parrello 1.6 =head3 SetLevel
590 :    
591 :     C<< Tracer::SetLevel($newLevel); >>
592 :    
593 :     Modify the trace level. A higher trace level will cause more messages to appear.
594 :    
595 :     =over 4
596 :    
597 :     =item newLevel
598 :    
599 :     Proposed new trace level.
600 :    
601 :     =back
602 :    
603 :     =cut
604 :    
605 :     sub SetLevel {
606 :     $TraceLevel = $_[0];
607 :     }
608 :    
609 : olson 1.1 =head3 Now
610 :    
611 :     C<< my $string = Tracer::Now(); >>
612 :    
613 :     Return a displayable time stamp containing the local time.
614 :    
615 :     =cut
616 :    
617 :     sub Now {
618 : parrello 1.12 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
619 :     my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
620 :     _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
621 :     return $retVal;
622 : olson 1.1 }
623 :    
624 :     # Pad a number to 2 digits.
625 :     sub _p2 {
626 : parrello 1.12 my ($value) = @_;
627 :     $value = "0$value" if ($value < 10);
628 :     return $value;
629 : olson 1.1 }
630 :    
631 :     =head3 LogErrors
632 :    
633 :     C<< Tracer::LogErrors($fileName); >>
634 :    
635 :     Route the standard error output to a log file.
636 :    
637 :     =over 4
638 :    
639 :     =item fileName
640 :    
641 :     Name of the file to receive the error output.
642 :    
643 :     =back
644 :    
645 :     =cut
646 :    
647 :     sub LogErrors {
648 : parrello 1.12 # Get the file name.
649 :     my ($fileName) = @_;
650 :     # Open the file as the standard error output.
651 :     open STDERR, '>', $fileName;
652 : olson 1.1 }
653 :    
654 : parrello 1.5 =head3 ReadOptions
655 :    
656 :     C<< my %options = Tracer::ReadOptions($fileName); >>
657 :    
658 :     Read a set of options from a file. Each option is encoded in a line of text that has the
659 :     format
660 :    
661 :     I<optionName>C<=>I<optionValue>C<; >I<comment>
662 :    
663 :     The option name must consist entirely of letters, digits, and the punctuation characters
664 : parrello 1.9 C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
665 :     character is a semi-colon will be ignored. The return hash will map each option name to
666 : parrello 1.5 the corresponding option value.
667 :    
668 :     =over 4
669 :    
670 :     =item fileName
671 :    
672 :     Name of the file containing the option data.
673 :    
674 :     =item RETURN
675 :    
676 :     Returns a hash mapping the option names specified in the file to their corresponding option
677 :     value.
678 :    
679 :     =back
680 :    
681 :     =cut
682 :    
683 :     sub ReadOptions {
684 : parrello 1.12 # Get the parameters.
685 :     my ($fileName) = @_;
686 :     # Open the file.
687 :     (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
688 :     # Count the number of records read.
689 :     my ($records, $comments) = 0;
690 :     # Create the return hash.
691 :     my %retVal = ();
692 :     # Loop through the file, accumulating key-value pairs.
693 :     while (my $line = <CONFIGFILE>) {
694 :     # Denote we've read a line.
695 :     $records++;
696 :     # Determine the line type.
697 :     if ($line =~ /^\s*[\n\r]/) {
698 :     # A blank line is a comment.
699 :     $comments++;
700 :     } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
701 :     # Here we have an option assignment.
702 :     retVal{$1} = $2;
703 :     } elsif ($line =~ /^\s*;/) {
704 :     # Here we have a text comment.
705 :     $comments++;
706 :     } else {
707 :     # Here we have an invalid line.
708 :     Trace("Invalid option statement in record $records.") if T(0);
709 :     }
710 :     }
711 :     # Return the hash created.
712 :     return %retVal;
713 : parrello 1.5 }
714 :    
715 : olson 1.1 =head3 GetOptions
716 :    
717 :     C<< Tracer::GetOptions(\%defaults, \%options); >>
718 :    
719 :     Merge a specified set of options into a table of defaults. This method takes two hash references
720 :     as input and uses the data from the second to update the first. If the second does not exist,
721 :     there will be no effect. An error will be thrown if one of the entries in the second hash does not
722 :     exist in the first.
723 :    
724 :     Consider the following example.
725 :    
726 :     C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>
727 :    
728 :     In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
729 :     B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
730 :     B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
731 :     the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
732 :     will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
733 :    
734 :     C<< {databaseType => 'Oracle'} >>
735 :    
736 :     an error will occur because the B<databaseType> option does not exist.
737 :    
738 :     =over 4
739 :    
740 :     =item defaults
741 :    
742 :     Table of default option values.
743 :    
744 :     =item options
745 :    
746 :     Table of overrides, if any.
747 :    
748 :     =item RETURN
749 :    
750 :     Returns a reference to the default table passed in as the first parameter.
751 :    
752 :     =back
753 :    
754 :     =cut
755 :    
756 :     sub GetOptions {
757 : parrello 1.12 # Get the parameters.
758 :     my ($defaults, $options) = @_;
759 :     # Check for overrides.
760 :     if ($options) {
761 :     # Loop through the overrides.
762 :     while (my ($option, $setting) = each %{$options}) {
763 :     # Insure this override exists.
764 :     if (!exists $defaults->{$option}) {
765 :     croak "Unrecognized option $option encountered.";
766 :     } else {
767 :     # Apply the override.
768 :     $defaults->{$option} = $setting;
769 :     }
770 :     }
771 :     }
772 :     # Return the merged table.
773 :     return $defaults;
774 : olson 1.1 }
775 :    
776 :     =head3 MergeOptions
777 :    
778 :     C<< Tracer::MergeOptions(\%table, \%defaults); >>
779 :    
780 :     Merge default values into a hash table. This method looks at the key-value pairs in the
781 :     second (default) hash, and if a matching key is not found in the first hash, the default
782 :     pair is copied in. The process is similar to L</GetOptions>, but there is no error-
783 :     checking and no return value.
784 :    
785 :     =over 4
786 :    
787 :     =item table
788 :    
789 :     Hash table to be updated with the default values.
790 :    
791 :     =item defaults
792 :    
793 :     Default values to be merged into the first hash table if they are not already present.
794 :    
795 :     =back
796 :    
797 :     =cut
798 :    
799 :     sub MergeOptions {
800 : parrello 1.12 # Get the parameters.
801 :     my ($table, $defaults) = @_;
802 :     # Loop through the defaults.
803 :     while (my ($key, $value) = each %{$defaults}) {
804 :     if (!exists $table->{$key}) {
805 :     $table->{$key} = $value;
806 :     }
807 :     }
808 : olson 1.1 }
809 :    
810 :     =head3 Trace
811 :    
812 :     C<< Trace($message); >>
813 :    
814 :     Write a trace message to the target location specified in L</TSetup>. If there has not been
815 :     any prior call to B<TSetup>.
816 :    
817 :     =over 4
818 :    
819 :     =item message
820 :    
821 :     Message to write.
822 :    
823 :     =back
824 :    
825 :     =cut
826 :    
827 :     sub Trace {
828 : parrello 1.12 # Get the parameters.
829 :     my ($message) = @_;
830 :     # Get the timestamp.
831 :     my $timeStamp = Now();
832 :     # Format the message. Note we strip off any line terminators at the end.
833 :     my $formatted = "$timeStamp <$LastCategory>: " . Strip($message);
834 :     # Process according to the destination.
835 :     if ($Destination eq "TEXT") {
836 :     # Write the message to the standard output.
837 :     print "$formatted\n";
838 :     } elsif ($Destination eq "ERROR") {
839 :     # Write the message to the error output.
840 :     print STDERR "$formatted\n";
841 :     } elsif ($Destination eq "QUEUE") {
842 :     # Push the message into the queue.
843 :     push @Queue, "$formatted";
844 :     } elsif ($Destination eq "HTML") {
845 :     # Convert the message to HTML and write it to the standard output.
846 :     my $escapedMessage = CGI::escapeHTML($message);
847 :     print "<p>$formatted</p>\n";
848 : parrello 1.4 } elsif ($Destination eq "WARN") {
849 :     # Emit the message as a warning.
850 :     warn $message;
851 : parrello 1.12 } elsif ($Destination =~ m/^>>/) {
852 :     # Write the trace message to an output file.
853 : parrello 1.14 (open TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
854 : parrello 1.12 print TRACING "$formatted\n";
855 :     close TRACING;
856 :     # If the Tee flag is on, echo it to the standard output.
857 :     if ($TeeFlag) {
858 :     print "$formatted\n";
859 :     }
860 :     }
861 : olson 1.1 }
862 :    
863 :     =head3 T
864 :    
865 : parrello 1.2 C<< my $switch = T($category, $traceLevel); >>
866 : olson 1.1
867 : parrello 1.12 or
868 : parrello 1.2
869 : olson 1.1 C<< my $switch = T($traceLevel); >>
870 :    
871 :     Return TRUE if the trace level is at or above a specified value and the specified category
872 :     is active, else FALSE. If no category is specified, the caller's package name is used.
873 :    
874 :     =over 4
875 :    
876 :     =item category
877 :    
878 :     Category to which the message belongs. If not specified, the caller's package name is
879 :     used.
880 :    
881 :     =item traceLevel
882 :    
883 :     Relevant tracing level.
884 :    
885 :     =item RETURN
886 :    
887 :     TRUE if a message at the specified trace level would appear in the trace, else FALSE.
888 :    
889 :     =back
890 :    
891 :     =cut
892 :    
893 :     sub T {
894 : parrello 1.12 # Declare the return variable.
895 :     my $retVal = 0;
896 :     # Only proceed if tracing is turned on.
897 :     if ($Destination ne "NONE") {
898 :     # Get the parameters.
899 :     my ($category, $traceLevel) = @_;
900 :     if (!defined $traceLevel) {
901 :     # Here we have no category, so we need to get the calling package.
902 :     # The calling package is normally the first parameter. If it is
903 :     # omitted, the first parameter will be the tracelevel. So, the
904 :     # first thing we do is shift the so-called category into the
905 :     # $traceLevel variable where it belongs.
906 :     $traceLevel = $category;
907 :     my ($package, $fileName, $line) = caller;
908 : parrello 1.3 # If there is no calling package, we default to "main".
909 : parrello 1.12 if (!$package) {
910 : parrello 1.3 $category = "main";
911 : parrello 1.12 } else {
912 :     $category = $package;
913 :     }
914 :     }
915 : parrello 1.7 # Save the category name.
916 :     $LastCategory = $category;
917 : parrello 1.13 # Convert it to lower case before we hash it.
918 :     $category = lc $category;
919 : parrello 1.12 # Use the category and tracelevel to compute the result.
920 :     $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));
921 : parrello 1.3 }
922 : parrello 1.12 # Return the computed result.
923 : parrello 1.3 return $retVal;
924 : olson 1.1 }
925 :    
926 :     =head3 ParseCommand
927 :    
928 :     C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>
929 :    
930 :     Parse a command line consisting of a list of parameters. The initial parameters may be option
931 : parrello 1.2 specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
932 :     off and merged into a table of default options. The remainder of the command line is
933 : olson 1.1 returned as a list of positional arguments. For example, consider the following invocation.
934 :    
935 :     C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>
936 :    
937 :     In this case, the list @words will be treated as a command line. There are two options available,
938 :     B<errors> and B<logFile>. If @words has the following format
939 :    
940 :     C<< -logFile=error.log apple orange rutabaga >>
941 :    
942 :     then at the end of the invocation, C<$options> will be
943 :    
944 :     C<< { errors => 0, logFile => 'error.log' } >>
945 :    
946 :     and C<@arguments> will contain
947 :    
948 :     C<< apple orange rutabaga >>
949 :    
950 : parrello 1.2 The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
951 : olson 1.1 support for quote characters.
952 :    
953 :     =over 4
954 :    
955 :     =item optionTable
956 :    
957 :     Table of default options.
958 :    
959 :     =item inputList
960 :    
961 :     List of words on the command line.
962 :    
963 :     =item RETURN
964 :    
965 :     Returns a reference to the option table and a list of the positional arguments.
966 :    
967 :     =back
968 :    
969 :     =cut
970 :    
971 :     sub ParseCommand {
972 : parrello 1.12 # Get the parameters.
973 :     my ($optionTable, @inputList) = @_;
974 :     # Process any options in the input list.
975 :     my %overrides = ();
976 :     while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {
977 :     # Get the current option.
978 :     my $arg = shift @inputList;
979 :     # Pull out the option name.
980 :     $arg =~ /^-([^=]*)/g;
981 :     my $name = $1;
982 :     # Check for an option value.
983 :     if ($arg =~ /\G=(.*)$/g) {
984 :     # Here we have a value for the option.
985 :     $overrides{$name} = UnEscape($1);
986 :     } else {
987 :     # Here there is no value, so we use 1.
988 :     $overrides{$name} = 1;
989 :     }
990 :     }
991 :     # Merge the options into the defaults.
992 :     GetOptions($optionTable, \%overrides);
993 :     # Translate the remaining parameters.
994 :     my @retVal = ();
995 :     for my $inputParm (@inputList) {
996 :     push @retVal, UnEscape($inputParm);
997 :     }
998 :     # Return the results.
999 :     return ($optionTable, @retVal);
1000 : olson 1.1 }
1001 :    
1002 : parrello 1.9 =head3 Escape
1003 :    
1004 :     C<< my $codedString = Tracer::Escape($realString); >>
1005 :    
1006 : parrello 1.25 Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines
1007 : parrello 1.28 replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
1008 :     result is to reverse the effect of L</UnEscape>.
1009 : parrello 1.9
1010 :     =over 4
1011 :    
1012 :     =item realString
1013 :    
1014 :     String to escape.
1015 :    
1016 :     =item RETURN
1017 :    
1018 :     Escaped equivalent of the real string.
1019 :    
1020 :     =back
1021 :    
1022 :     =cut
1023 :    
1024 :     sub Escape {
1025 : parrello 1.12 # Get the parameter.
1026 :     my ($realString) = @_;
1027 :     # Initialize the return variable.
1028 :     my $retVal = "";
1029 :     # Loop through the parameter string, looking for sequences to escape.
1030 :     while (length $realString > 0) {
1031 :     # Look for the first sequence to escape.
1032 : parrello 1.27 if ($realString =~ /^(.*?)([\n\t\r\\])/) {
1033 : parrello 1.12 # Here we found it. The text preceding the sequence is in $1. The sequence
1034 :     # itself is in $2. First, move the clear text to the return variable.
1035 :     $retVal .= $1;
1036 : parrello 1.14 # Strip the processed section off the real string.
1037 :     $realString = substr $realString, (length $2) + (length $1);
1038 : parrello 1.28 # Get the matched character.
1039 : parrello 1.12 my $char = $2;
1040 : parrello 1.28 # If we have a CR, we are done.
1041 :     if ($char ne "\r") {
1042 :     # It's not a CR, so encode the escape sequence.
1043 :     $char =~ tr/\t\n/tn/;
1044 :     $retVal .= "\\" . $char;
1045 :     }
1046 : parrello 1.12 } else {
1047 :     # Here there are no more escape sequences. The rest of the string is
1048 :     # transferred unmodified.
1049 :     $retVal .= $realString;
1050 :     $realString = "";
1051 :     }
1052 :     }
1053 :     # Return the result.
1054 :     return $retVal;
1055 : parrello 1.9 }
1056 :    
1057 : olson 1.1 =head3 UnEscape
1058 :    
1059 :     C<< my $realString = Tracer::UnEscape($codedString); >>
1060 :    
1061 : parrello 1.25 Replace escape sequences with their actual equivalents. C<\t> will be replaced by
1062 : parrello 1.28 a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
1063 :     be deleted.
1064 : olson 1.1
1065 :     =over 4
1066 :    
1067 :     =item codedString
1068 :    
1069 :     String to un-escape.
1070 :    
1071 :     =item RETURN
1072 :    
1073 :     Returns a copy of the original string with the escape sequences converted to their actual
1074 :     values.
1075 :    
1076 :     =back
1077 :    
1078 :     =cut
1079 :    
1080 :     sub UnEscape {
1081 : parrello 1.12 # Get the parameter.
1082 :     my ($codedString) = @_;
1083 :     # Initialize the return variable.
1084 :     my $retVal = "";
1085 :     # Only proceed if the incoming string is nonempty.
1086 :     if (defined $codedString) {
1087 :     # Loop through the parameter string, looking for escape sequences. We can't do
1088 : parrello 1.25 # translating because it causes problems with the escaped slash. ("\\t" becomes
1089 :     # "\<tab>" no matter what we do.)
1090 : parrello 1.12 while (length $codedString > 0) {
1091 :     # Look for the first escape sequence.
1092 : parrello 1.27 if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
1093 : parrello 1.12 # Here we found it. The text preceding the sequence is in $1. The sequence
1094 :     # itself is in $2. First, move the clear text to the return variable.
1095 :     $retVal .= $1;
1096 :     $codedString = substr $codedString, (2 + length $1);
1097 : parrello 1.28 # Get the escape value.
1098 : parrello 1.12 my $char = $2;
1099 : parrello 1.28 # If we have a "\r", we are done.
1100 :     if ($char ne 'r') {
1101 :     # Here it's not an 'r', so we convert it.
1102 :     $char =~ tr/\\tn/\\\t\n/;
1103 :     $retVal .= $char;
1104 :     }
1105 : parrello 1.12 } else {
1106 :     # Here there are no more escape sequences. The rest of the string is
1107 :     # transferred unmodified.
1108 :     $retVal .= $codedString;
1109 :     $codedString = "";
1110 :     }
1111 :     }
1112 :     }
1113 :     # Return the result.
1114 :     return $retVal;
1115 : olson 1.1 }
1116 :    
1117 :     =head3 ParseRecord
1118 :    
1119 :     C<< my @fields = Tracer::ParseRecord($line); >>
1120 :    
1121 :     Parse a tab-delimited data line. The data line is split into field values. Embedded tab
1122 :     and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
1123 :     These will automatically be converted.
1124 :    
1125 :     =over 4
1126 :    
1127 :     =item line
1128 :    
1129 :     Line of data containing the tab-delimited fields.
1130 :    
1131 :     =item RETURN
1132 :    
1133 :     Returns a list of the fields found in the data line.
1134 :    
1135 :     =back
1136 :    
1137 :     =cut
1138 :    
1139 :     sub ParseRecord {
1140 : parrello 1.12 # Get the parameter.
1141 :     my ($line) = @_;
1142 :     # Remove the trailing new-line, if any.
1143 :     chomp $line;
1144 :     # Split the line read into pieces using the tab character.
1145 :     my @retVal = split /\t/, $line;
1146 :     # Trim and fix the escapes in each piece.
1147 :     for my $value (@retVal) {
1148 :     # Trim leading whitespace.
1149 :     $value =~ s/^\s+//;
1150 :     # Trim trailing whitespace.
1151 :     $value =~ s/\s+$//;
1152 :     # Delete the carriage returns.
1153 :     $value =~ s/\r//g;
1154 :     # Convert the escapes into their real values.
1155 :     $value =~ s/\\t/"\t"/ge;
1156 :     $value =~ s/\\n/"\n"/ge;
1157 :     }
1158 :     # Return the result.
1159 :     return @retVal;
1160 : olson 1.1 }
1161 :    
1162 :     =head3 Merge
1163 :    
1164 :     C<< my @mergedList = Tracer::Merge(@inputList); >>
1165 :    
1166 :     Sort a list of strings and remove duplicates.
1167 :    
1168 :     =over 4
1169 :    
1170 :     =item inputList
1171 :    
1172 :     List of scalars to sort and merge.
1173 :    
1174 :     =item RETURN
1175 :    
1176 :     Returns a list containing the same elements sorted in ascending order with duplicates
1177 :     removed.
1178 :    
1179 :     =back
1180 :    
1181 :     =cut
1182 :    
1183 :     sub Merge {
1184 : parrello 1.12 # Get the input list in sort order.
1185 :     my @inputList = sort @_;
1186 :     # Only proceed if the list has at least two elements.
1187 :     if (@inputList > 1) {
1188 :     # Now we want to move through the list splicing out duplicates.
1189 :     my $i = 0;
1190 :     while ($i < @inputList) {
1191 :     # Get the current entry.
1192 :     my $thisEntry = $inputList[$i];
1193 :     # Find out how many elements duplicate the current entry.
1194 :     my $j = $i + 1;
1195 :     my $dup1 = $i + 1;
1196 :     while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
1197 :     # If the number is nonzero, splice out the duplicates found.
1198 :     if ($j > $dup1) {
1199 :     splice @inputList, $dup1, $j - $dup1;
1200 :     }
1201 :     # Now the element at position $dup1 is different from the element before it
1202 :     # at position $i. We push $i forward one position and start again.
1203 :     $i++;
1204 :     }
1205 :     }
1206 :     # Return the merged list.
1207 :     return @inputList;
1208 : olson 1.1 }
1209 :    
1210 :     =head3 GetFile
1211 :    
1212 : parrello 1.6 C<< my @fileContents = Tracer::GetFile($fileName); >>
1213 : olson 1.1
1214 :     Return the entire contents of a file.
1215 :    
1216 :     =over 4
1217 :    
1218 :     =item fileName
1219 :    
1220 :     Name of the file to read.
1221 :    
1222 :     =item RETURN
1223 :    
1224 : parrello 1.6 In a list context, returns the entire file as a list with the line terminators removed.
1225 :     In a scalar context, returns the entire file as a string.
1226 : olson 1.1
1227 :     =back
1228 :    
1229 :     =cut
1230 :    
1231 :     sub GetFile {
1232 : parrello 1.12 # Get the parameters.
1233 :     my ($fileName) = @_;
1234 :     # Declare the return variable.
1235 :     my @retVal = ();
1236 :     # Open the file for input.
1237 :     my $ok = open INPUTFILE, "<$fileName";
1238 :     if (!$ok) {
1239 :     # If we had an error, trace it. We will automatically return a null value.
1240 : parrello 1.16 Trace("Could not open \"$fileName\" for input: $!") if T(0);
1241 : parrello 1.12 } else {
1242 :     # Read the whole file into the return variable, stripping off any terminator
1243 : parrello 1.6 # characters.
1244 :     my $lineCount = 0;
1245 : parrello 1.12 while (my $line = <INPUTFILE>) {
1246 : parrello 1.6 $lineCount++;
1247 : parrello 1.9 $line = Strip($line);
1248 : parrello 1.12 push @retVal, $line;
1249 :     }
1250 :     # Close it.
1251 :     close INPUTFILE;
1252 : parrello 1.6 my $actualLines = @retVal;
1253 : parrello 1.12 }
1254 :     # Return the file's contents in the desired format.
1255 : parrello 1.9 if (wantarray) {
1256 : parrello 1.12 return @retVal;
1257 : parrello 1.6 } else {
1258 :     return join "\n", @retVal;
1259 :     }
1260 : olson 1.1 }
1261 :    
1262 :     =head3 QTrace
1263 :    
1264 :     C<< my $data = QTrace($format); >>
1265 :    
1266 :     Return the queued trace data in the specified format.
1267 :    
1268 :     =over 4
1269 :    
1270 :     =item format
1271 :    
1272 :     C<html> to format the data as an HTML list, C<text> to format it as straight text.
1273 :    
1274 :     =back
1275 :    
1276 :     =cut
1277 :    
1278 :     sub QTrace {
1279 : parrello 1.12 # Get the parameter.
1280 :     my ($format) = @_;
1281 :     # Create the return variable.
1282 :     my $retVal = "";
1283 : parrello 1.14 # Only proceed if there is an actual queue.
1284 :     if (@Queue) {
1285 :     # Process according to the format.
1286 :     if ($format =~ m/^HTML$/i) {
1287 :     # Convert the queue into an HTML list.
1288 :     $retVal = "<ul>\n";
1289 :     for my $line (@Queue) {
1290 :     my $escapedLine = CGI::escapeHTML($line);
1291 :     $retVal .= "<li>$escapedLine</li>\n";
1292 :     }
1293 :     $retVal .= "</ul>\n";
1294 :     } elsif ($format =~ m/^TEXT$/i) {
1295 :     # Convert the queue into a list of text lines.
1296 :     $retVal = join("\n", @Queue) . "\n";
1297 :     }
1298 :     # Clear the queue.
1299 :     @Queue = ();
1300 : parrello 1.12 }
1301 :     # Return the formatted list.
1302 :     return $retVal;
1303 : olson 1.1 }
1304 :    
1305 :     =head3 Confess
1306 :    
1307 :     C<< Confess($message); >>
1308 :    
1309 : parrello 1.22 Trace the call stack and abort the program with the specified message. When used with
1310 : parrello 1.9 the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
1311 : parrello 1.6 So, for example
1312 : olson 1.1
1313 : parrello 1.6 C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
1314 : olson 1.1
1315 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
1316 :    
1317 :     =over 4
1318 :    
1319 :     =item message
1320 :    
1321 :     Message to include in the trace.
1322 :    
1323 :     =back
1324 :    
1325 :     =cut
1326 :    
1327 :     sub Confess {
1328 : parrello 1.12 # Get the parameters.
1329 :     my ($message) = @_;
1330 :     # Trace the call stack.
1331 : parrello 1.22 Cluck($message);
1332 : parrello 1.12 # Abort the program.
1333 :     croak(">>> $message");
1334 : olson 1.1 }
1335 :    
1336 : parrello 1.6 =head3 Assert
1337 :    
1338 :     C<< Assert($condition1, $condition2, ... $conditionN); >>
1339 :    
1340 :     Return TRUE if all the conditions are true. This method can be used in conjunction with
1341 : parrello 1.29 the OR operator and the L</Confess> method as a debugging assert.
1342 : parrello 1.6 So, for example
1343 :    
1344 :     C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
1345 :    
1346 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
1347 :    
1348 :     =cut
1349 :     sub Assert {
1350 :     my $retVal = 1;
1351 :     LOOP: for my $condition (@_) {
1352 :     if (! $condition) {
1353 :     $retVal = 0;
1354 :     last LOOP;
1355 :     }
1356 :     }
1357 :     return $retVal;
1358 :     }
1359 :    
1360 : olson 1.1 =head3 Cluck
1361 :    
1362 :     C<< Cluck($message); >>
1363 :    
1364 :     Trace the call stack. Note that for best results, you should qualify the call with a
1365 :     trace condition. For example,
1366 :    
1367 :     C<< Cluck("Starting record parse.") if T(3); >>
1368 :    
1369 :     will only trace the stack if the trace level for the package is 3 or more.
1370 :    
1371 :     =over 4
1372 :    
1373 :     =item message
1374 :    
1375 :     Message to include in the trace.
1376 :    
1377 :     =back
1378 :    
1379 :     =cut
1380 :    
1381 :     sub Cluck {
1382 : parrello 1.12 # Get the parameters.
1383 :     my ($message) = @_;
1384 : parrello 1.5 # Trace what's happening.
1385 :     Trace("Stack trace for event: $message");
1386 : parrello 1.12 my $confession = longmess($message);
1387 :     # Convert the confession to a series of trace messages. Note we skip any
1388 : parrello 1.5 # messages relating to calls into Tracer.
1389 : parrello 1.12 for my $line (split /\s*\n/, $confession) {
1390 :     Trace($line) if ($line !~ /Tracer\.pm/);
1391 :     }
1392 : olson 1.1 }
1393 :    
1394 : parrello 1.5 =head3 Min
1395 :    
1396 :     C<< my $min = Min($value1, $value2, ... $valueN); >>
1397 :    
1398 :     Return the minimum argument. The arguments are treated as numbers.
1399 :    
1400 :     =over 4
1401 :    
1402 :     =item $value1, $value2, ... $valueN
1403 :    
1404 :     List of numbers to compare.
1405 :    
1406 :     =item RETURN
1407 :    
1408 :     Returns the lowest number in the list.
1409 :    
1410 :     =back
1411 :    
1412 :     =cut
1413 :    
1414 :     sub Min {
1415 : parrello 1.12 # Get the parameters. Note that we prime the return value with the first parameter.
1416 :     my ($retVal, @values) = @_;
1417 :     # Loop through the remaining parameters, looking for the lowest.
1418 :     for my $value (@values) {
1419 :     if ($value < $retVal) {
1420 :     $retVal = $value;
1421 :     }
1422 :     }
1423 :     # Return the minimum found.
1424 :     return $retVal;
1425 : parrello 1.5 }
1426 :    
1427 :     =head3 Max
1428 :    
1429 :     C<< my $max = Max($value1, $value2, ... $valueN); >>
1430 :    
1431 :     Return the maximum argument. The arguments are treated as numbers.
1432 :    
1433 :     =over 4
1434 :    
1435 :     =item $value1, $value2, ... $valueN
1436 :    
1437 :     List of numbers to compare.
1438 :    
1439 :     =item RETURN
1440 :    
1441 :     Returns the highest number in the list.
1442 :    
1443 :     =back
1444 :    
1445 :     =cut
1446 :    
1447 :     sub Max {
1448 : parrello 1.12 # Get the parameters. Note that we prime the return value with the first parameter.
1449 :     my ($retVal, @values) = @_;
1450 :     # Loop through the remaining parameters, looking for the highest.
1451 :     for my $value (@values) {
1452 :     if ($value > $retVal) {
1453 :     $retVal = $value;
1454 :     }
1455 :     }
1456 :     # Return the maximum found.
1457 :     return $retVal;
1458 : parrello 1.5 }
1459 :    
1460 :     =head3 AddToListMap
1461 :    
1462 :     C<< Tracer::AddToListMap(\%hash, $key, $value); >>
1463 :    
1464 :     Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list
1465 :     is created for the key. Otherwise, the new value is pushed onto the list.
1466 :    
1467 :     =over 4
1468 :    
1469 :     =item hash
1470 :    
1471 :     Reference to the target hash.
1472 :    
1473 :     =item key
1474 :    
1475 :     Key for which the value is to be added.
1476 :    
1477 :     =item value
1478 :    
1479 :     Value to add to the key's value list.
1480 :    
1481 :     =back
1482 :    
1483 :     =cut
1484 :    
1485 :     sub AddToListMap {
1486 :     # Get the parameters.
1487 :     my ($hash, $key, $value) = @_;
1488 :     # Process according to whether or not the key already has a value.
1489 :     if (! exists $hash->{$key}) {
1490 :     $hash->{$key} = [$value];
1491 :     } else {
1492 :     push @{$hash->{$key}}, $value;
1493 :     }
1494 :     }
1495 : olson 1.1
1496 : parrello 1.7 =head3 DebugMode
1497 :    
1498 :     C<< if (Tracer::DebugMode) { ...code... } >>
1499 :    
1500 : parrello 1.22 Return TRUE if debug mode has been turned on, else output an error
1501 :     page and return FALSE.
1502 : parrello 1.7
1503 :     Certain CGI scripts are too dangerous to exist in the production
1504 :     environment. This method provides a simple way to prevent them
1505 : parrello 1.21 from working unless they are explicitly turned on by creating a password
1506 :     cookie via the B<SetPassword> script. If debugging mode
1507 : parrello 1.22 is not turned on, an error web page will be output directing the
1508 :     user to enter in the correct password.
1509 : parrello 1.7
1510 :     =cut
1511 :    
1512 :     sub DebugMode {
1513 : parrello 1.12 # Declare the return variable.
1514 : parrello 1.21 my $retVal = 0;
1515 : parrello 1.12 # Check the debug configuration.
1516 : parrello 1.21 my $password = CGI::cookie("DebugMode");
1517 :     my $encrypted = Digest::MD5::md5_hex($password);
1518 :     if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {
1519 : parrello 1.12 $retVal = 1;
1520 :     } else {
1521 :     # Here debug mode is off, so we generate an error page.
1522 : parrello 1.9 my $pageString = PageBuilder::Build("<Html/ErrorPage.html", {}, "Html");
1523 : parrello 1.12 print $pageString;
1524 :     }
1525 :     # Return the determination indicator.
1526 : parrello 1.18 return $retVal;
1527 : parrello 1.9 }
1528 :    
1529 :     =head3 Strip
1530 :    
1531 :     C<< my $string = Tracer::Strip($line); >>
1532 :    
1533 :     Strip all line terminators off a string. This is necessary when dealing with files
1534 :     that may have been transferred back and forth several times among different
1535 :     operating environments.
1536 :    
1537 :     =over 4
1538 :    
1539 :     =item line
1540 :    
1541 :     Line of text to be stripped.
1542 :    
1543 :     =item RETURN
1544 :    
1545 :     The same line of text with all the line-ending characters chopped from the end.
1546 :    
1547 :     =back
1548 :    
1549 :     =cut
1550 :    
1551 :     sub Strip {
1552 : parrello 1.12 # Get a copy of the parameter string.
1553 :     my ($string) = @_;
1554 : parrello 1.29 my $retVal = (defined $string ? $string : "");
1555 : parrello 1.9 # Strip the line terminator characters.
1556 :     $retVal =~ s/(\r|\n)+$//g;
1557 : parrello 1.12 # Return the result.
1558 :     return $retVal;
1559 : parrello 1.9 }
1560 :    
1561 :     =head3 Pad
1562 :    
1563 :     C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>
1564 :    
1565 :     Pad a string to a specified length. The pad character will be a
1566 :     space, and the padding will be on the right side unless specified
1567 :     in the third parameter.
1568 :    
1569 :     =over 4
1570 :    
1571 :     =item string
1572 :    
1573 :     String to be padded.
1574 :    
1575 :     =item len
1576 :    
1577 :     Desired length of the padded string.
1578 :    
1579 :     =item left (optional)
1580 :    
1581 :     TRUE if the string is to be left-padded; otherwise it will be padded on the right.
1582 :    
1583 :     =item padChar (optional)
1584 :    
1585 : parrello 1.22 Character to use for padding. The default is a space.
1586 :    
1587 : parrello 1.9 =item RETURN
1588 :    
1589 : parrello 1.22 Returns a copy of the original string with the pad character added to the
1590 :     specified end so that it achieves the desired length.
1591 : parrello 1.9
1592 :     =back
1593 :    
1594 :     =cut
1595 :    
1596 :     sub Pad {
1597 : parrello 1.12 # Get the parameters.
1598 :     my ($string, $len, $left, $padChar) = @_;
1599 :     # Compute the padding character.
1600 :     if (! defined $padChar) {
1601 :     $padChar = " ";
1602 :     }
1603 :     # Compute the number of spaces needed.
1604 :     my $needed = $len - length $string;
1605 :     # Copy the string into the return variable.
1606 :     my $retVal = $string;
1607 :     # Only proceed if padding is needed.
1608 :     if ($needed > 0) {
1609 :     # Create the pad string.
1610 :     my $pad = $padChar x $needed;
1611 :     # Affix it to the return value.
1612 :     if ($left) {
1613 :     $retVal = $pad . $retVal;
1614 :     } else {
1615 :     $retVal .= $pad;
1616 :     }
1617 :     }
1618 :     # Return the result.
1619 :     return $retVal;
1620 : parrello 1.7 }
1621 :    
1622 : parrello 1.29 =head3 EOF
1623 :    
1624 :     This is a constant that is lexically greater than any useful string.
1625 :    
1626 :     =cut
1627 :    
1628 :     sub EOF {
1629 :     return "\xFF\xFF\xFF\xFF\xFF";
1630 :     }
1631 :    
1632 : parrello 1.15 =head3 TICK
1633 :    
1634 :     C<< my @results = TICK($commandString); >>
1635 :    
1636 :     Perform a back-tick operation on a command. If this is a Windows environment, any leading
1637 :     dot-slash (C<./> will be removed. So, for example, if you were doing
1638 :    
1639 :     `./protein.cgi`
1640 :    
1641 :     from inside a CGI script, it would work fine in Unix, but would issue an error message
1642 :     in Windows complaining that C<'.'> is not a valid command. If instead you code
1643 :    
1644 :     TICK("./protein.cgi")
1645 :    
1646 :     it will work correctly in both environments.
1647 :    
1648 :     =over 4
1649 :    
1650 :     =item commandString
1651 :    
1652 :     The command string to pass to the system.
1653 :    
1654 :     =item RETURN
1655 :    
1656 :     Returns the standard output from the specified command, as a list.
1657 :    
1658 :     =back
1659 :    
1660 :     =cut
1661 :     #: Return Type @;
1662 :     sub TICK {
1663 :     # Get the parameters.
1664 :     my ($commandString) = @_;
1665 :     # Chop off the dot-slash if this is Windows.
1666 :     if ($FIG_Config::win_mode) {
1667 :     $commandString =~ s!^\./!!;
1668 :     }
1669 :     # Activate the command and return the result.
1670 :     return `$commandString`;
1671 :     }
1672 :    
1673 : redwards 1.8 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3