| 1 | package Test2::API::Stack; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | our $VERSION = '1.302073'; | ||
| 6 | |||
| 7 | |||
| 8 | use Test2::Hub(); | ||
| 9 | |||
| 10 | use Carp qw/confess/; | ||
| 11 | |||
| 12 | sub new { | ||
| 13 | my $class = shift; | ||
| 14 | return bless [], $class; | ||
| 15 | } | ||
| 16 | |||
| 17 | sub new_hub { | ||
| 18 | my $self = shift; | ||
| 19 | my %params = @_; | ||
| 20 | |||
| 21 | my $class = delete $params{class} || 'Test2::Hub'; | ||
| 22 | |||
| 23 | my $hub = $class->new(%params); | ||
| 24 | |||
| 25 | if (@$self) { | ||
| 26 | $hub->inherit($self->[-1], %params); | ||
| 27 | } | ||
| 28 | else { | ||
| 29 | require Test2::API; | ||
| 30 | $hub->format(Test2::API::test2_formatter()->new) | ||
| 31 | unless $hub->format || exists($params{formatter}); | ||
| 32 | |||
| 33 | my $ipc = Test2::API::test2_ipc(); | ||
| 34 | if ($ipc && !$hub->ipc && !exists($params{ipc})) { | ||
| 35 | $hub->set_ipc($ipc); | ||
| 36 | $ipc->add_hub($hub->hid); | ||
| 37 | } | ||
| 38 | } | ||
| 39 | |||
| 40 | push @$self => $hub; | ||
| 41 | |||
| 42 | $hub; | ||
| 43 | } | ||
| 44 | |||
| 45 | sub top { | ||
| 46 | my $self = shift; | ||
| 47 | return $self->new_hub unless @$self; | ||
| 48 | return $self->[-1]; | ||
| 49 | } | ||
| 50 | |||
| 51 | sub peek { | ||
| 52 | my $self = shift; | ||
| 53 | return @$self ? $self->[-1] : undef; | ||
| 54 | } | ||
| 55 | |||
| 56 | sub cull { | ||
| 57 | my $self = shift; | ||
| 58 | $_->cull for reverse @$self; | ||
| 59 | } | ||
| 60 | |||
| 61 | sub all { | ||
| 62 | my $self = shift; | ||
| 63 | return @$self; | ||
| 64 | } | ||
| 65 | |||
| 66 | sub clear { | ||
| 67 | my $self = shift; | ||
| 68 | @$self = (); | ||
| 69 | } | ||
| 70 | |||
| 71 | # Do these last without keywords in order to prevent them from getting used | ||
| 72 | # when we want the real push/pop. | ||
| 73 | |||
| 74 | { | ||
| 75 | no warnings 'once'; | ||
| 76 | |||
| 77 | *push = sub { | ||
| 78 | my $self = shift; | ||
| 79 | my ($hub) = @_; | ||
| 80 | $hub->inherit($self->[-1]) if @$self; | ||
| 81 | push @$self => $hub; | ||
| 82 | }; | ||
| 83 | |||
| 84 | *pop = sub { | ||
| 85 | my $self = shift; | ||
| 86 | my ($hub) = @_; | ||
| 87 | confess "No hubs on the stack" | ||
| 88 | unless @$self; | ||
| 89 | confess "You cannot pop the root hub" | ||
| 90 | if 1 == @$self; | ||
| 91 | confess "Hub stack mismatch, attempted to pop incorrect hub" | ||
| 92 | unless $self->[-1] == $hub; | ||
| 93 | pop @$self; | ||
| 94 | }; | ||
| 95 | } | ||
| 96 | |||
| 97 | 1; | ||
| 98 | |||
| 99 | __END__ |