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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3