| 1 | package Shell::Amazon::S3::Plugin::History; | ||
| 2 | |||
| 3 | use Moose::Role; | ||
| 4 | use namespace::clean -except => ['meta']; | ||
| 5 | |||
| 6 | has 'history' => ( | ||
| 7 | isa => 'ArrayRef', | ||
| 8 | is => 'rw', | ||
| 9 | required => 1, | ||
| 10 | lazy => 1, | ||
| 11 | default => sub { [] } | ||
| 12 | ); | ||
| 13 | |||
| 14 | sub push_history { | ||
| 15 | my ( $self, $line ) = @_; | ||
| 16 | push( @{ $self->history }, $line ); | ||
| 17 | } | ||
| 18 | |||
| 19 | around 'read' => sub { | ||
| 20 | my $orig = shift; | ||
| 21 | my ( $self, @args ) = @_; | ||
| 22 | my $line = $self->$orig(@args); | ||
| 23 | if ( defined $line ) { | ||
| 24 | if ( $line =~ m/^!(.*)$/ ) { | ||
| 25 | my $call = $1; | ||
| 26 | $line = $self->history_call($call); | ||
| 27 | if ( defined $line ) { | ||
| 28 | $self->print( $line . "\n" ); | ||
| 29 | } | ||
| 30 | else { | ||
| 31 | return "'Unable to find ${call} in history'"; | ||
| 32 | } | ||
| 33 | } | ||
| 34 | if ( $line =~ m/\S/ ) { | ||
| 35 | $self->push_history($line); | ||
| 36 | } | ||
| 37 | } | ||
| 38 | return $line; | ||
| 39 | }; | ||
| 40 | |||
| 41 | sub history_call { | ||
| 42 | my ( $self, $call ) = @_; | ||
| 43 | if ( $call =~ m/^(-?\d+)$/ ) { # handle !1 or !-1 | ||
| 44 | my $idx = $1; | ||
| 45 | $idx-- if ( $idx > 0 ); # !1 gets history element 0 | ||
| 46 | my $line = $self->history->[$idx]; | ||
| 47 | return $line; | ||
| 48 | } | ||
| 49 | my $re = qr/^\Q${call}\E/; | ||
| 50 | foreach my $line ( reverse @{ $self->history } ) { | ||
| 51 | return $line if ( $line =~ $re ); | ||
| 52 | } | ||
| 53 | return; | ||
| 54 | } | ||
| 55 | |||
| 56 | 1; |