3 See the NOTICE file distributed with
this work
for additional information
4 regarding copyright ownership.
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
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.
23 Please email comments or questions to the
public Ensembl
24 developers list at <http:
26 Questions may also be sent to the Ensembl help desk at
38 -SERVERROOT =>
"/path/to/ensembl",
39 -DEFAULT_CONF =>
"my.default.conf"
42 # parse options from configuration file and commandline
44 'mandatory_string_opt=s' => 1,
45 'optional_numeric_opt=n' => 0,
48 # get a paramter value
49 my $val = $conf->param(
'manadatory_string_op');
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.
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.
68 no warnings 'uninitialized';
73 use Pod::Usage qw(pod2usage);
82 String $serverroot - root directory of your ensembl code
84 String $default_conf - default configuration file
86 -SERVERROOT => '/path/to/ensembl',
87 -DEFAULT_CONF => 'my.default.conf'
89 Description :
object constructor
91 Exceptions : thrown if no serverroot is provided
100 my $class = ref($caller) || $caller;
102 my ($serverroot, $default_conf) =
103 rearrange([qw(SERVERROOT DEFAULT_CONF)], @_);
105 throw(
"You must supply a serverroot.") unless ($serverroot);
108 bless ($self, $class);
110 $self->serverroot($serverroot);
111 $self->default_conf($default_conf ||
"$ENV{HOME}/.ensembl_script.conf");
119 Arg[1..n] : pairs of option definitions and mandatory flag (see below
for
121 Example : $conf->parse_options(
122 'mandatory_string_opt=s' => 1,
123 'optional_numeric_opt=n' => 0,
125 Description : This method reads options from an (optional) configuration file
126 and parses the commandline options supplied by the user.
127 Commandline options will superseed config file settings. The
128 string "$SERVERROOT" in the configuration entries will be
129 replaced by the appropriate value.
131 The arguments passed to
this method are pairs of a Getopt::Long
132 style option definition (in fact it will be passed to
133 GetOptions() directly) and a flag indicating whether
this
134 option is mandatory (1) or optional (0).
136 In addition to these user-defined options, a set of common
137 options is always parsed. See _common_options() for details.
139 If you
run your script with --interactive the user will be
140 asked to
confirm the parameters after parsing.
142 All parameters will then be accessible via $self->param('name').
143 Return type : true on success
144 Exceptions : thrown if configuration file can't be opened
145 thrown on missing mandatory parameters
153 my ($self, @params) = @_;
155 # add common options to user supplied list
156 push @params, $self->_common_options;
158 # read common commandline options
160 my %params = @params;
162 Getopt::Long::Configure(
'pass_through');
163 &GetOptions(\%h, keys %params);
166 my $conffile = $h{
'conffile'} || $self->default_conf;
167 $conffile = abs_path($conffile);
170 open(my $fh,
'<', $conffile) or
throw(
171 "Unable to open configuration file $conffile for reading: $!");
173 my $serverroot = $self->serverroot;
176 while (my $line = <$fh>) {
179 # remove leading and trailing whitespace
183 # join with next line if terminated with backslash (this is to allow
184 # multiline configuration settings
185 $line = $last . $line;
186 if ($line =~ /\\$/) {
198 # read options into internal parameter datastructure
199 next unless ($line =~ /(\w\S*)\s*=\s*(.*)/);
203 # strip optional quotes from parameter values
204 $val =~ s/^[
"'](.*)["']/$1/;
206 # replace $SERVERROOT with value
207 if ($val =~ /\$SERVERROOT/) {
208 $val =~ s/\$SERVERROOT/$serverroot/g;
209 $val = abs_path($val);
211 $self->param($name, $val);
215 $self->param('conffile
', $conffile);
218 # override configured parameter with commandline options
219 map { $self->param($_, $h{$_}) } keys %h;
221 # check for required params, convert comma to list, maintain an ordered
222 # list of parameters and list of 'flag
' type params
226 foreach my $param (@params) {
229 my $required = $params{$param};
231 $list = 1 if ($param =~ /\@$/);
232 $flag = 1 if ($param =~ /!$/);
233 $param =~ s/(^\w+).*/$1/;
235 $self->comma_to_list($param) if ($list);
237 push @missing, $param if ($required and !$self->param($param));
238 push @{ $self->{'_ordered_params
'} }, $param;
239 $self->{'_flag_params
'}->{$param} = 1 if ($flag);
243 throw("Missing parameters: @missing.\nYou must specify them on the commandline or in your conffile.\n");
246 # error handling and --help
247 pod2usage(1) if ($self->param('help
'));
249 # ask user to confirm parameters to proceed
250 $self->confirm_params;
257 # Commonly used options. These are parsed by default even if they are not
258 # passed to parse_options() explicitely.
260 sub _common_options {
263 'conffile|conf=s
' => 0,
264 'logfile|log=s
' => 0,
266 'logautobase=s
' => 0,
269 'logappend|log_append|log-append!
' => 0,
271 'is_component|is-component!
' => 0,
272 'interactive|i!
' => 0,
273 'dry_run|dry-
run|dry|n!
' => 0,
279 =head2 confirm_params
281 Example : $conf->confirm_params;
282 Description : If the script is run with the --interactive switch, this method
283 prints a table of all parameters and their values and asks user
284 to confirm if he wants to proceed.
285 Return type : true on success
287 Caller : parse_options()
296 if ($self->param('interactive
')) {
297 # print parameter table
298 print "Running script with these parameters:\n\n";
299 print $self->list_param_values;
301 # ask user if he wants to proceed
302 exit unless user_proceed("Continue?", 1, 'n
');
311 Arg[1] : Parameter name
312 Arg[2..n] : (optional) List of values to set
314 my $dbname = $conf->param('dbname
');
317 $conf->param('port
', 3306);
318 $conf->param('chromosomes
', 1, 6, 'X
');
319 Description : Getter/setter for parameters. Accepts single-value params and
321 Return type : Scalar value for single-value parameters, array of values for
323 Exceptions : thrown if no parameter name is supplied
332 my $name = shift or throw("You must supply a parameter name");
336 if (scalar(@_) == 1) {
338 $self->{'_param
'}->{$name} = shift;
341 undef $self->{'_param
'}->{$name};
342 @{ $self->{'_param
'}->{$name} } = @_;
347 if (ref($self->{'_param
'}->{$name}) eq 'ARRAY
') {
349 return @{ $self->{'_param
'}->{$name} };
350 } elsif (defined($self->{'_param
'}->{$name})) {
351 # single-value parameter
352 return $self->{'_param
'}->{$name};
361 Arg[1] : Parameter name
362 Example : unless ($conf->is_true('upload
')) {
363 print "Won't upload data.\n
";
366 Description : Checks whether a param value is set to 'true', which is defined
367 here as TRUE (in the Perl sense) but not the string 'no'.
368 Return type : Boolean
369 Exceptions : thrown if no parameter name is supplied
378 my $name = shift or throw("You must supply a parameter name
");
380 my $param = $self->param($name);
382 if ($param and !($param =~ /^no$/i)) {
392 Example : print "Current parameter names:\n
";
393 foreach my $param (@{ $conf->list_params }) {
396 Description : Returns a list of the currently available parameter names. The
397 list will be in the same order as option definitions were
398 passed to the new() method.
399 Return type : Arrayref of parameter names
401 Caller : list_param_values(), create_commandline_options()
409 return $self->{'_ordered_params'} || [];
413 =head2 list_param_values
415 Example : print LOG $conf->list_param_values;
416 Description : prints a table of the parameters used in the script
417 Return type : String - the table to print
425 sub list_param_values {
428 $Text::Wrap::colums = 72;
430 my $txt = sprintf " %-20s%-40s\n
", qw(PARAMETER VALUE);
431 $txt .= " " . "-
"x70 . "\n
";
433 foreach my $key (@{ $self->list_params }) {
435 if (defined($self->param($key))) {
436 $txt .= Text::Wrap::wrap(sprintf(' %-19s ', $key), ' 'x24,
437 join(",
", $self->param($key)))."\n
";
447 =head2 create_commandline_options
449 Arg[1..n] : param/value pairs which should be added to or override the
450 currently defined parameters
451 Example : $conf->create_commandline_options(
452 'dbname' => 'homo_sapiens_vega_33_35e',
455 Description : Creates a commandline options string of all current paramters
456 that can be passed to another script.
457 Return type : String - commandline options string
465 sub create_commandline_options {
466 my ($self, %replace) = @_;
470 # deal with list values
471 foreach my $param (@{ $self->list_params }) {
472 my ($first, @rest) = $self->param($param);
473 next unless (defined($first));
476 $first = join(",
", $first, @rest);
478 $param_hash{$param} = $first;
482 foreach my $key (keys %replace) {
483 $param_hash{$key} = $replace{$key};
486 # create the commandline options string
488 foreach my $param (keys %param_hash) {
490 my $val = $param_hash{$param};
492 # deal with 'flag' type params correctly
493 if ($self->{'_flag_params'}->{$param}) {
494 # change 'myparam' to 'nomyparam' if no value set
495 $param = 'no'.$param unless ($val);
497 # unset value (this is how flags behave)
500 # don't add the param if it's not a flag param and no value is set
501 next unless (defined($val));
503 # quote the value if it contains blanks
505 # use an appropriate quoting style
506 ($val =~ /'/) ? ($val = qq("$val
")) : ($val = qq('$val'));
510 $options_string .= sprintf(qq(--%s %s ), $param, $val);
513 return $options_string;
519 Arg[1..n] : list of parameter names to parse
520 Example : $conf->comma_to_list('chromosomes');
521 Description : Transparently converts comma-separated lists into arrays (to
522 allow different styles of commandline options, see perldoc
523 Getopt::Long for details). Parameters are converted in place
524 (accessible through $self->param('name')).
525 Return type : true on success
536 foreach my $param (@_) {
537 $self->param($param, split (/,/, join (',', $self->param($param))));
546 Arg[1] : Name of parameter to parse
547 Example : $conf->list_or_file('gene');
548 Description : Determines whether a parameter holds a list or it is a filename
549 to read the list entries from.
550 Return type : true on success
551 Exceptions : thrown if list file can't be opened
559 my ($self, $param) = @_;
561 my @vals = $self->param($param);
562 return unless (@vals);
564 my $firstval = $vals[0];
566 if (scalar(@vals) == 1 && -e $firstval) {
567 # we didn't get a list of values, but a file to read values from
570 open(my $fh, '<', $firstval) or throw("Cannot open $firstval
for reading: $!
");
579 $self->param($param, @vals);
582 $self->comma_to_list($param);
590 Arg[1] : (optional) String - root directory of your ensembl checkout
591 Example : my $serverroot = $conf->serverroot;
592 Description : Getter/setter for the root directory of your ensembl checkout.
595 Caller : new(), general
603 $self->{'_serverroot'} = shift if (@_);
604 return $self->{'_serverroot'};
610 Arg[1] : (optional) String - default configuration file
611 Example : $conf->default_conf('my.default.conf');
612 Description : Getter/setter for the default configuration file.
615 Caller : new(), general
623 $self->{'_default_conf'} = shift if (@_);
624 return $self->{'_default_conf'};