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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3