App-Base
view release on metacpan or search on metacpan
lib/App/Base/Script/Common.pm view on Meta::CPAN
my $self = shift;
state $cache;
my $class = ref($self) || $self;
$cache->{$class} //=
[map { App::Base::Script::Option->new($_) } @{$self->options}, @{$self->base_options}];
return $cache->{$class};
}
=head2 base_options
The options provided for every classes which implements App::Base::Script::Common.
See BUILT-IN OPTIONS
=cut
sub base_options {
return [{
name => 'help',
documentation => 'Show this help information',
},
];
}
=head2 switch_name_width
Computes the maximum width of any of the switch (option) names.
=cut
sub switch_name_width {
my $self = shift;
return max(map { length($_->display_name) } @{$self->all_options});
}
=head2 switches
Generates the switch table output of the usage statement.
=cut
sub switches {
my $self = shift;
my $col_width = $ENV{COLUMNS} || 76;
my $max_option_length = $self->switch_name_width;
my $sw = '[' x ($max_option_length + 2);
my $doc = '[' x ($col_width - $max_option_length - 1);
my @lines = map { form {break => break_wrap}, "$sw $doc", '--' . $_->display_name, $_->show_documentation; }
(sort { $a->name cmp $b->name } (@{$self->all_options}));
return join('', @lines);
}
=head2 cli_template
The template usage form that should be shown to the user in the usage
statement when --help or an invalid invocation is provided.
Defaults to "(program name) [options]", which is pretty standard Unix.
=cut
sub cli_template {
return "$0 [options] "; # Override this if your script has a more complex command-line
# invocation template such as "$0[options] company_id [list1 [, list2 [, ...]]] "
}
=head2 usage
Outputs a statement explaining the usage of the script, then exits.
=cut
sub usage {
my $self = shift;
my $col_width = $ENV{COLUMNS} || 76;
my $format = '[' x $col_width;
my $message = join('', "\n", form({break => break_wrap}, $format, ["Usage: " . $self->cli_template, split(/[\r\n]/, $self->documentation)]));
$message .= "\nOptions:\n\n";
$message .= $self->switches . "\n\n";
print STDERR $message;
exit(1);
}
=head2 getOption
Returns the value of a specified option. For example, getOption('help') returns
1 or 0 depending on whether the --help option was specified. For option types
which are non-boolean (see App::Base::Script::Option) the return value is the actual
string/integer/float provided on the common line - or undef if none was provided.
=cut
sub getOption {
my $self = shift;
my $option = shift;
if (exists($self->_option_values->{$option})) {
return $self->_option_values->{$option};
} else {
die "Unknown option $option";
}
}
=head2 run
Runs the script, returning the return value of __run
=cut
( run in 0.697 second using v1.01-cache-2.11-cpan-39bf76dae61 )