EnsEMBL/Utils/ConfParser.pm untested

filter: Statementstmt 0.0% 0 / 187 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 31 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 318 CC 33 SCAR 40.8
CC
33
Cov
0%
parse_options
182.0
create_commandline_options
72.0
param
30.0
CRAP 59.1
1 =head1 LICENSE
2  
3 See the NOTICE file distributed with this work for additional information
4 regarding copyright ownership.
5  
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9  
10 http://www.apache.org/licenses/LICENSE-2.0
11  
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17  
18 =cut
19  
20  
21 =head1 CONTACT
22  
23 Please email comments or questions to the public Ensembl
24 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
25  
26 Questions may also be sent to the Ensembl help desk at
27 <http://www.ensembl.org/Help/Contact>.
28  
29 =cut
30  
31 =head1 NAME
32  
33 Bio::EnsEMBL::Utils::ConfParser - configuration parser for perl scripts
34  
35 =head1 SYNOPSIS
36  
37 my $conf = new Bio::EnsEMBL::Utils::ConfParser(
38 -SERVERROOT => "/path/to/ensembl",
39 -DEFAULT_CONF => "my.default.conf"
40 );
41  
42 # parse options from configuration file and commandline
43 $conf->parse_options(
44 'mandatory_string_opt=s' => 1,
45 'optional_numeric_opt=n' => 0,
46 );
47  
48 # get a paramter value
49 my $val = $conf->param('manadatory_string_op');
50  
51 =head1 DESCRIPTION
52  
53 This module parses a configuration file and the commandline options
54 passed to a script (the latter superseed the former). Configuration
55 files contain ini-file style name-value pairs, and the commandline
56 options are passed to Getopt::Long for parsing.
57  
58 The parameter values are consequently accessible via the param()
59 method. You can also create a commandline string of all current
60 parameters and their values to pass to another script.
61  
62 =cut
63  
64 package Bio::EnsEMBL::Utils::ConfParser;
65 $Bio::EnsEMBL::Utils::ConfParser::VERSION = '114.0.0_50'; # TRIAL
66 $Bio::EnsEMBL::Utils::ConfParser::VERSION = '114.0.050';
67 use strict;
68 use warnings;
69 no warnings 'uninitialized';
70  
71 use Getopt::Long;
72 use Text::Wrap;
73 use Cwd qw(abs_path);
74 use Pod::Usage qw(pod2usage);
75 use Bio::EnsEMBL::Utils::Argument qw(rearrange);
76 use Bio::EnsEMBL::Utils::Exception qw(throw warning);
77 use Bio::EnsEMBL::Utils::ScriptUtils qw(user_proceed);
78  
79  
80 =head2 new
81  
82 Arg [SERVERROOT] :
83 String $serverroot - root directory of your ensembl code
84 Arg [DEFAULT_CONF] :
85 String $default_conf - default configuration file
86 Example : my $conf = new Bio::EnsEMBL::Utils::ConfParser(
87 -SERVERROOT => '/path/to/ensembl',
88 -DEFAULT_CONF => 'my.default.conf'
89 );
90 Description : object constructor
91 Return type : Bio::EnsEMBL::Utils::ConfParser object
92 Exceptions : thrown if no serverroot is provided
93 Caller : general
94 Status : At Risk
95 : under development
96  
97 =cut
98  
99 sub new {
100 my $caller = shift;
101 my $class = ref($caller) || $caller;
102  
103 my ($serverroot, $default_conf) =
104 rearrange([qw(SERVERROOT DEFAULT_CONF)], @_);
105  
106 throw("You must supply a serverroot.") unless ($serverroot);
107  
108 my $self = {};
109 bless ($self, $class);
110  
111 $self->serverroot($serverroot);
112 $self->default_conf($default_conf || "$ENV{HOME}/.ensembl_script.conf");
113  
114 return $self;
115 }
116  
117  
118 =head2 parse_options
119  
120 Arg[1..n] : pairs of option definitions and mandatory flag (see below for
121 details)
122 Example : $conf->parse_options(
123 'mandatory_string_opt=s' => 1,
124 'optional_numeric_opt=n' => 0,
125 );
126 Description : This method reads options from an (optional) configuration file
127 and parses the commandline options supplied by the user.
128 Commandline options will superseed config file settings. The
129 string "$SERVERROOT" in the configuration entries will be
130 replaced by the appropriate value.
131  
132 The arguments passed to this method are pairs of a Getopt::Long
133 style option definition (in fact it will be passed to
134 GetOptions() directly) and a flag indicating whether this
135 option is mandatory (1) or optional (0).
136  
137 In addition to these user-defined options, a set of common
138 options is always parsed. See _common_options() for details.
139
140 If you run your script with --interactive the user will be
141 asked to confirm the parameters after parsing.
142
143 All parameters will then be accessible via $self->param('name').
144 Return type : true on success
145 Exceptions : thrown if configuration file can't be opened
146 thrown on missing mandatory parameters
147 Caller : general
148 Status : At Risk
149 : under development
150  
151 =cut
152  
153 sub parse_options {
154 my ($self, @params) = @_;
155  
156 # add common options to user supplied list
157 push @params, $self->_common_options;
158  
159 # read common commandline options
160 my %h;
161 my %params = @params;
162  
163 Getopt::Long::Configure('pass_through');
164 &GetOptions(\%h, keys %params);
165  
166 # reads config file
167 my $conffile = $h{'conffile'} || $self->default_conf;
168 $conffile = abs_path($conffile);
169  
170 if (-e $conffile) {
171 open(my $fh, '<', $conffile) or throw(
172 "Unable to open configuration file $conffile for reading: $!");
173  
174 my $serverroot = $self->serverroot;
175 my $last;
176  
177 while (my $line = <$fh>) {
178 chomp $line;
179
180 # remove leading and trailing whitespace
181 $line =~ s/^\s*//;
182 $line =~ s/\s*$//;
183  
184 # join with next line if terminated with backslash (this is to allow
185 # multiline configuration settings
186 $line = $last . $line;
187 if ($line =~ /\\$/) {
188 $line =~ s/\\$//;
189 $last = $line;
190 next;
191 } else {
192 $last = undef;
193 }
194  
195 # remove comments
196 $line =~ s/^[#;].*//;
197 $line =~ s/\s+[;].*$//;
198  
199 # read options into internal parameter datastructure
200 next unless ($line =~ /(\w\S*)\s*=\s*(.*)/);
201 my $name = $1;
202 my $val = $2;
203  
204 # strip optional quotes from parameter values
205 $val =~ s/^["'](.*)["']/$1/;
206  
207 # replace $SERVERROOT with value
208 if ($val =~ /\$SERVERROOT/) {
209 $val =~ s/\$SERVERROOT/$serverroot/g;
210 $val = abs_path($val);
211 }
212 $self->param($name, $val);
213 }
214 close($fh);
215  
216 $self->param('conffile', $conffile);
217 }
218  
219 # override configured parameter with commandline options
220 map { $self->param($_, $h{$_}) } keys %h;
221  
222 # check for required params, convert comma to list, maintain an ordered
223 # list of parameters and list of 'flag' type params
224 my @missing = ();
225 my $i = 0;
226  
227 foreach my $param (@params) {
228 next if ($i++ % 2);
229  
230 my $required = $params{$param};
231 my ($list, $flag);
232 $list = 1 if ($param =~ /\@$/);
233 $flag = 1 if ($param =~ /!$/);
234 $param =~ s/(^\w+).*/$1/;
235
236 $self->comma_to_list($param) if ($list);
237  
238 push @missing, $param if ($required and !$self->param($param));
239 push @{ $self->{'_ordered_params'} }, $param;
240 $self->{'_flag_params'}->{$param} = 1 if ($flag);
241 }
242
243 if (@missing) {
244 throw("Missing parameters: @missing.\nYou must specify them on the commandline or in your conffile.\n");
245 }
246  
247 # error handling and --help
248 pod2usage(1) if ($self->param('help'));
249  
250 # ask user to confirm parameters to proceed
251 $self->confirm_params;
252  
253 return(1);
254 }
255  
256  
257 #
258 # Commonly used options. These are parsed by default even if they are not
259 # passed to parse_options() explicitely.
260 #
261 sub _common_options {
262 my $self = shift;
263 return (
264 'conffile|conf=s' => 0,
265 'logfile|log=s' => 0,
266 'logauto!' => 0,
267 'logautobase=s' => 0,
268 'logautoid=s' => 0,
269 'logpath=s' => 0,
270 'logappend|log_append|log-append!' => 0,
271 'loglevel=s' => 0,
272 'is_component|is-component!' => 0,
273 'interactive|i!' => 0,
274 'dry_run|dry-run|dry|n!' => 0,
275 'help|h|?' => 0,
276 );
277 }
278  
279  
280 =head2 confirm_params
281  
282 Example : $conf->confirm_params;
283 Description : If the script is run with the --interactive switch, this method
284 prints a table of all parameters and their values and asks user
285 to confirm if he wants to proceed.
286 Return type : true on success
287 Exceptions : none
288 Caller : parse_options()
289 Status : At Risk
290 : under development
291  
292 =cut
293  
294 sub confirm_params {
295 my $self = shift;
296  
297 if ($self->param('interactive')) {
298 # print parameter table
299 print "Running script with these parameters:\n\n";
300 print $self->list_param_values;
301  
302 # ask user if he wants to proceed
303 exit unless user_proceed("Continue?", 1, 'n');
304 }
305
306 return(1);
307 }
308  
309  
310 =head2 param
311  
312 Arg[1] : Parameter name
313 Arg[2..n] : (optional) List of values to set
314 Example : # getter
315 my $dbname = $conf->param('dbname');
316  
317 # setter
318 $conf->param('port', 3306);
319 $conf->param('chromosomes', 1, 6, 'X');
320 Description : Getter/setter for parameters. Accepts single-value params and
321 list params.
322 Return type : Scalar value for single-value parameters, array of values for
323 list parameters
324 Exceptions : thrown if no parameter name is supplied
325 Caller : general
326 Status : At Risk
327 : under development
328  
329 =cut
330  
331 sub param {
332 my $self = shift;
333 my $name = shift or throw("You must supply a parameter name");
334  
335 # setter
336 if (@_) {
337 if (scalar(@_) == 1) {
338 # single value
339 $self->{'_param'}->{$name} = shift;
340 } else {
341 # list of values
342 undef $self->{'_param'}->{$name};
343 @{ $self->{'_param'}->{$name} } = @_;
344 }
345 }
346  
347 # getter
348 if (ref($self->{'_param'}->{$name}) eq 'ARRAY') {
349 # list parameter
350 return @{ $self->{'_param'}->{$name} };
351 } elsif (defined($self->{'_param'}->{$name})) {
352 # single-value parameter
353 return $self->{'_param'}->{$name};
354 } else {
355 return undef;
356 }
357 }
358  
359  
360 =head2 is_true
361  
362 Arg[1] : Parameter name
363 Example : unless ($conf->is_true('upload')) {
364 print "Won't upload data.\n";
365 next;
366 }
367 Description : Checks whether a param value is set to 'true', which is defined
368 here as TRUE (in the Perl sense) but not the string 'no'.
369 Return type : Boolean
370 Exceptions : thrown if no parameter name is supplied
371 Caller : general
372 Status : At Risk
373 : under development
374  
375 =cut
376  
377 sub is_true {
378 my $self = shift;
379 my $name = shift or throw("You must supply a parameter name");
380  
381 my $param = $self->param($name);
382  
383 if ($param and !($param =~ /^no$/i)) {
384 return(1);
385 } else {
386 return(0);
387 }
388 }
389  
390  
391 =head2 list_params
392  
393 Example : print "Current parameter names:\n";
394 foreach my $param (@{ $conf->list_params }) {
395 print " $param\n";
396 }
397 Description : Returns a list of the currently available parameter names. The
398 list will be in the same order as option definitions were
399 passed to the new() method.
400 Return type : Arrayref of parameter names
401 Exceptions : none
402 Caller : list_param_values(), create_commandline_options()
403 Status : At Risk
404 : under development
405  
406 =cut
407  
408 sub list_params {
409 my $self = shift;
410 return $self->{'_ordered_params'} || [];
411 }
412  
413  
414 =head2 list_param_values
415  
416 Example : print LOG $conf->list_param_values;
417 Description : prints a table of the parameters used in the script
418 Return type : String - the table to print
419 Exceptions : none
420 Caller : general
421 Status : At Risk
422 : under development
423  
424 =cut
425  
426 sub list_param_values {
427 my $self = shift;
428  
429 $Text::Wrap::colums = 72;
430  
431 my $txt = sprintf " %-20s%-40s\n", qw(PARAMETER VALUE);
432 $txt .= " " . "-"x70 . "\n";
433  
434 foreach my $key (@{ $self->list_params }) {
435 my $val;
436 if (defined($self->param($key))) {
437 $txt .= Text::Wrap::wrap(sprintf(' %-19s ', $key), ' 'x24,
438 join(", ", $self->param($key)))."\n";
439 }
440 }
441  
442 $txt .= "\n";
443  
444 return $txt;
445 }
446  
447  
448 =head2 create_commandline_options
449  
450 Arg[1..n] : param/value pairs which should be added to or override the
451 currently defined parameters
452 Example : $conf->create_commandline_options(
453 'dbname' => 'homo_sapiens_vega_33_35e',
454 'interactive' => 0
455 );
456 Description : Creates a commandline options string of all current paramters
457 that can be passed to another script.
458 Return type : String - commandline options string
459 Exceptions : none
460 Caller : general
461 Status : At Risk
462 : under development
463  
464 =cut
465  
466 sub create_commandline_options {
467 my ($self, %replace) = @_;
468  
469 my %param_hash;
470  
471 # deal with list values
472 foreach my $param (@{ $self->list_params }) {
473 my ($first, @rest) = $self->param($param);
474 next unless (defined($first));
475  
476 if (@rest) {
477 $first = join(",", $first, @rest);
478 }
479 $param_hash{$param} = $first;
480 }
481  
482 # replace values
483 foreach my $key (keys %replace) {
484 $param_hash{$key} = $replace{$key};
485 }
486  
487 # create the commandline options string
488 my $options_string;
489 foreach my $param (keys %param_hash) {
490  
491 my $val = $param_hash{$param};
492  
493 # deal with 'flag' type params correctly
494 if ($self->{'_flag_params'}->{$param}) {
495 # change 'myparam' to 'nomyparam' if no value set
496 $param = 'no'.$param unless ($val);
497  
498 # unset value (this is how flags behave)
499 $val = undef;
500 } else {
501 # don't add the param if it's not a flag param and no value is set
502 next unless (defined($val));
503  
504 # quote the value if it contains blanks
505 if ($val =~ /\s+/) {
506 # use an appropriate quoting style
507 ($val =~ /'/) ? ($val = qq("$val")) : ($val = qq('$val'));
508 }
509 }
510
511 $options_string .= sprintf(qq(--%s %s ), $param, $val);
512 }
513  
514 return $options_string;
515 }
516  
517  
518 =head2 comma_to_list
519  
520 Arg[1..n] : list of parameter names to parse
521 Example : $conf->comma_to_list('chromosomes');
522 Description : Transparently converts comma-separated lists into arrays (to
523 allow different styles of commandline options, see perldoc
524 Getopt::Long for details). Parameters are converted in place
525 (accessible through $self->param('name')).
526 Return type : true on success
527 Exceptions : none
528 Caller : general
529 Status : At Risk
530 : under development
531  
532 =cut
533  
534 sub comma_to_list {
535 my $self = shift;
536
537 foreach my $param (@_) {
538 $self->param($param, split (/,/, join (',', $self->param($param))));
539 }
540
541 return(1);
542 }
543  
544  
545 =head2 list_or_file
546  
547 Arg[1] : Name of parameter to parse
548 Example : $conf->list_or_file('gene');
549 Description : Determines whether a parameter holds a list or it is a filename
550 to read the list entries from.
551 Return type : true on success
552 Exceptions : thrown if list file can't be opened
553 Caller : general
554 Status : At Risk
555 : under development
556  
557 =cut
558  
559 sub list_or_file {
560 my ($self, $param) = @_;
561
562 my @vals = $self->param($param);
563 return unless (@vals);
564  
565 my $firstval = $vals[0];
566
567 if (scalar(@vals) == 1 && -e $firstval) {
568 # we didn't get a list of values, but a file to read values from
569 @vals = ();
570
571 open(my $fh, '<', $firstval) or throw("Cannot open $firstval for reading: $!");
572
573 while(<$fh>){
574 chomp;
575 push(@vals, $_);
576 }
577
578 close($fh);
579
580 $self->param($param, @vals);
581 }
582
583 $self->comma_to_list($param);
584
585 return(1);
586 }
587  
588  
589 =head2 serverroot
590  
591 Arg[1] : (optional) String - root directory of your ensembl checkout
592 Example : my $serverroot = $conf->serverroot;
593 Description : Getter/setter for the root directory of your ensembl checkout.
594 Return type : String
595 Exceptions : none
596 Caller : new(), general
597 Status : At Risk
598 : under development
599  
600 =cut
601  
602 sub serverroot {
603 my $self = shift;
604 $self->{'_serverroot'} = shift if (@_);
605 return $self->{'_serverroot'};
606 }
607  
608  
609 =head2 default_conf
610  
611 Arg[1] : (optional) String - default configuration file
612 Example : $conf->default_conf('my.default.conf');
613 Description : Getter/setter for the default configuration file.
614 Return type : String
615 Exceptions : none
616 Caller : new(), general
617 Status : At Risk
618 : under development
619  
620 =cut
621  
622 sub default_conf {
623 my $self = shift;
624 $self->{'_default_conf'} = shift if (@_);
625 return $self->{'_default_conf'};
626 }
627  
628  
629 1;
630