package System::Introspector::Probe::FileHandles;
use Moo;

use System::Introspector::Util qw(
    handle_from_command
    transform_exceptions
);

has lsof_command => (is => 'ro', default => sub { 'lsof' });

sub gather {
    my ($self) = @_;
    return transform_exceptions {
        my $pipe = $self->_open_lsof_pipe;
        my @handles;
        while (defined( my $line = <$pipe> )) {
            chomp $line;
            my @fields = split m{\0}, $line;
            push @handles, { map {
                m{^(.)(.*)$};
                ($1, $2);
            } @fields };
        }
        return { handles => \@handles };
    };
}

sub _open_lsof_pipe {
    my ($self) = @_;
    my $lsof = $self->lsof_command;
    return handle_from_command "$lsof -F0";
}

1;

__END__

=head1 NAME

System::Introspector::FileHandles - Gather opened filehandles

=head1 DESCRIPTION

Uses C<lsof> to build a list of open filehandles.

=head1 SEE ALSO

=over

=item L<System::Introspector>

=back

=cut

