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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3