lib/CrashTest/StackFilter.pm
author Vincent Tondellier <tonton+hg@team1664.org>
Fri, 08 Aug 2014 00:05:39 +0200
changeset 39 009bc678f0ef
parent 37 013953be0f3b
child 42 604ffca3aec1
permissions -rw-r--r--
Remove debug code

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

package CrashTest::StackFilter;
use Mojo::Base -base;
use Mojo::Loader;

has [ qw/config app filters/ ];

sub new {
    my $self = shift->SUPER::new(@_);

    if(defined($self->config->{StackFilters})) {
        $self->load_modules($self->config->{StackFilters});
    } else {
        $self->find_modules();
    }

    return $self;
}

sub apply {
    my ($self, $thread) = @_;

    foreach my $filter(@{$self->filters}) {
        #say "apply filter $filter";
        $thread = $filter->apply($thread);
    }

    return $thread;
}

sub load_modules {
    my ($self, $modules) = @_;

    my @filters = ();
    my $loader = Mojo::Loader->new;
    for my $module (@$modules) {
        my $e = $loader->load($module);
        die qq{Loading "$module" failed: $e} and next if ref $e;

        #say "loading $module";
        push @filters, $module->new(config => $self->config, app => $self->app);
    }

    $self->filters(\@filters);
}

sub find_modules {
    my ($self) = @_;

    my @modules = ();
    my $loader = Mojo::Loader->new;

    # Find modules in a namespace
    for my $module (@{$loader->search('CrashTest::StackFilters')}) {
        my $e = $loader->load($module);
        warn qq{Loading "$module" failed: $e} and next if ref $e;

        push @modules, [ $module, $module->priority ];
    }

    # sort by prio
    @modules = sort { $b->[1] <=> $a->[1] } @modules;

    # instanciate
    my @filters = map { $_->[0]->new(config => $self->config, app => $self->app) } @modules;

    $self->filters(\@filters);
}

1;