Code-TidyAll

 view release on metacpan or  search on metacpan

lib/Code/TidyAll/Role/RunsCommand.pm  view on Meta::CPAN

package Code::TidyAll::Role::RunsCommand;

use strict;
use warnings;

use IPC::Run3       qw(run3);
use List::SomeUtils qw(any);
use Specio::Library::Builtins;
use Specio::Library::Numeric;
use Text::ParseWords qw(shellwords);
use Try::Tiny;

use Moo::Role;

our $VERSION = '0.85';

has ok_exit_codes => (
    is      => 'ro',
    isa     => t( 'ArrayRef', of => t('PositiveOrZeroInt') ),
    default => sub { [0] },
);

# We will end up getting $self->argv from the Plugin base class.

sub _run_or_die {
    my $self = shift;
    my @argv = @_;

    my $output;
    my @cmd = ( shellwords( $self->cmd ), shellwords( $self->argv ), @argv );
    try {
        local $?;
        run3( \@cmd, \undef, \$output, \$output );
        my $code = $? >> 8;
        if ( $self->_is_bad_exit_code($code) ) {
            my $signal = $? & 127;
            my $msg    = "exited with $code";
            $msg .= " - received signal $signal" if $signal;
            $msg .= " - output was:\n$output"    if defined $output and length $output;
            die "$msg\n";
        }
    }
    catch {
        die sprintf(
            "Running [%s] failed\n    %s",
            ( join q{ }, @cmd ),
            $_,
        );
    };

    return $output;
}

sub _is_bad_exit_code {
    my $self = shift;
    my $code = shift;

    return !( any { $code == $_ } @{ $self->ok_exit_codes } );
}

1;

# ABSTRACT: A role for plugins which run external commands

__END__

=pod

=encoding UTF-8

=head1 NAME



( run in 1.216 second using v1.01-cache-2.11-cpan-39bf76dae61 )