Files
sl/SRC/sl/Commands.pm

160 lines
2.9 KiB
Perl

package SL::Commands;
use strict;
use warnings;
use parent 'SL';
sub new {
my( $class, $commands ) = @_;
return( bless( $commands, $class ) );
}
sub commandhelp {
my $self = shift;
my $command = shift;
my $optcount = 0;
if ( ! $self->{$command} ) {
SL->error( 2, "help(): Invalid command '$command'" );
}
my $options = $self->{$command}{'options'};
my $help = $self->{$command}{'help'};
print "$0 $command";
foreach ( @{$self->{$command}{'options'}} ) {
if ( $_ =~ /^(<|\[[A-Z])/ ) {
print " $_";
}
elsif ( substr( $_, 0, 1 ) eq '[' ) {
$optcount++;
}
}
if ( $optcount ) {
print ' [OPTIONS]';
}
print "\n\n$self->{$command}{'brief'}\n";
for ( my $i = 0; $i <= $#{$options}; $i++ ) {
my $charcnt = 0;
printf( "\n %-32s", $options->[$i] );
foreach ( split( ' ', $help->[$i] ) ) {
$charcnt += length( $_ ) + 1;
if ( $charcnt >= 34 ) {
$charcnt = 0;
print "\n" . ( ' ' x 34 ) . "$_ ";
}
else {
print "$_ ";
}
}
print "\n";
}
}
sub help {
my ( $self, $opts ) = @_;
my $cnt = 0;
print "Usage: $0 <COMMAND> <ARGS>\n\n"
. "sl is the Snaplinux package management utility\n\n"
. "COMMANDS\n\n";
if ( $opts->{'all'} ) {
foreach my $command ( sort( keys( %$self ) ) ) {
if ( $cnt ) {
print "\n";
}
$self->commandhelp( $command );
$cnt++;
}
}
else {
foreach my $command ( sort( keys( %$self ) ) ) {
print " $command \t\t\t$self->{$command}{'brief'}\n"
}
}
print "\nTo view more information for commands run:\n"
. "sl <COMMAND> -h|--help\n";
}
sub parseopts {
my ( $self, $command ) = @_;
my $opts = {};
if ( ! $command ) {
SL->error( 0, "parseopts(): Missing COMMAND" );
$self->help();
exit( 2 );
}
elsif ( ! $self->{$command} ) {
SL->error( 0, "parseopts(): '$command': Invalid COMMAND" );
$self->help();
exit( 2 );
}
foreach ( my $i = $#ARGV; $i >= 0; $i-- ) {
if ( $ARGV[$i] =~ /^\-([a-z]{2,})/ ) {
my @chars = split( '', $1 );
splice( @ARGV, $i, 1 );
foreach ( @chars ) {
push( @ARGV, "-$_" );
$i = $#ARGV;
}
}
if ( substr( $ARGV[$i], 0, 1 ) eq '-' &&
! grep( $_ =~ /(\[$ARGV[$i],|\[\-[a-z],$ARGV[$i]( |\]))/,
@{$self->{$command}{'options'}} ) ) {
SL->error( 2, "$ARGV[$i]: invalid argument" );
}
}
foreach ( @{$self->{$command}{'options'}} ) {
my( $short, $long, $arg2 ) = '';
my $tmpopts = {};
if ( $_ =~ /^\[(\-[a-z]),(\-\-([a-z]+))( (\S+)\]|\])/ ) {
$short = $1 || SL->error( 1, "Malformed short arg"
. " definition" );
$long = $2 || SL->error( 1, "Malformed long arg"
. " definition" );
$arg2 = $5 || '';
$tmpopts = SL->pullarg( {
short => $short,
long => $long,
arg2 => $arg2
} );
if ( ref( $tmpopts ) ) {
foreach my $key ( %$tmpopts ) {
$opts->{$key} = $tmpopts->{$key};
}
}
else {
$opts->{$3} = $tmpopts;
}
}
}
return( $opts );
}
1;