Minilla

 view release on metacpan or  search on metacpan

lib/Minilla/CLI.pm  view on Meta::CPAN

package Minilla::CLI;
use strict;
use warnings;
use utf8;
use Getopt::Long;
use IO::Handle;
use Try::Tiny;

use Minilla;
use Minilla::Errors;
use Minilla::Project;
use Minilla::Util qw(find_dir);
use Minilla::Logger;

use Minilla::CLI::New;
use Minilla::CLI::Help;
use Minilla::CLI::Dist;
use Minilla::CLI::Test;
use Minilla::CLI::Release;
use Minilla::CLI::Install;

use Moo;

no Moo;

sub run {
    my ($self, @args) = @_;

    STDOUT->flush or die "Cannot flush standard output: $!";
    open my $stdout, '>&', \*STDOUT
        or die "Cannot save standard output: $!";
    local $Minilla::Logger::SLOG_OUTPUT = $Minilla::Logger::SLOG_OUTPUT || $stdout;
    open STDOUT, '>&', \*STDERR
        or die "Cannot redirect standard output to standard error: $!";

    try {
        $self->_run(@args);
    } catch {
        die $_;
    } finally {
        my $flushed = STDOUT->flush;
        my $flush_error = $!;
        open STDOUT, '>&', $stdout
            or die "Cannot restore standard output: $!";
        die "Cannot flush redirected standard output: $flush_error" unless $flushed;
    };
}

sub _run {
    my ($self, @args) = @_;

    local $Minilla::AUTO_INSTALL = 1;
    local $Minilla::Logger::COLOR = -t STDERR ? 1 : 0;
    local @ARGV = @args;
    my @commands;
    my $version;
    my $p = Getopt::Long::Parser->new(
        config => [ "no_ignore_case", "pass_through" ],
    );
    $p->getoptions(
        "h|help"         => sub { unshift @commands, 'help' },
        "color!"         => \$Minilla::Logger::COLOR,
        "debug!"         => \$Minilla::DEBUG,
        "auto-install!"  => \$Minilla::AUTO_INSTALL,
        'version!'       => \$version,
    );

    if ($version) {
        print "Minilla: $Minilla::VERSION\n";
        exit 0;
    }

    push @commands, @ARGV;

    my $cmd = shift @commands || 'help';
    my $klass = sprintf("Minilla::CLI::%s", ucfirst($cmd));

    ## no critic
    if (eval sprintf("require %s; 1;", $klass)) {
        my $exit_code = 0;
        try {
            $klass->run(@commands);
        } catch {
            if (/Minilla::Error::CommandExit/) {
                $exit_code = 1;
                return;
            }
            errorf("%s\n", $_);
            exit 1;
        };
        return $exit_code;
    } else {
        warnf("Could not find command '%s'\n", $cmd);
        if ($@ !~ /^Can't locate Minilla/) {
            errorf("$@\n");
        }
        exit 2;
    }
}

1;



( run in 0.626 second using v1.01-cache-2.11-cpan-ac8be02dad9 )