| 1 | package Devel::REPL::Plugin::SOOT; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use Devel::REPL::Plugin; | ||
| 5 | use namespace::clean -except => [ 'meta' ]; | ||
| 6 | use Fcntl qw(:flock :seek); | ||
| 7 | |||
| 8 | has 'history_file_handle' => ( | ||
| 9 | isa => 'FileHandle', is => 'rw', required => 1, lazy => 1, | ||
| 10 | default => sub { $_[0]->open_history_file() } | ||
| 11 | ); | ||
| 12 | |||
| 13 | # HISTLEN should probably be in a config file to stop people accidentally | ||
| 14 | # truncating their history if they start the program and forget to set | ||
| 15 | # PERLREPL_HISTLEN | ||
| 16 | our $HistLen = $ENV{SOOT_HISTLEN} || 1000; | ||
| 17 | |||
| 18 | our $REPL; | ||
| 19 | |||
| 20 | around 'run' => sub { | ||
| 21 | my $orig=shift; | ||
| 22 | my ($self, @args)=@_; | ||
| 23 | my $hist_file = $self->get_history_file; | ||
| 24 | $self->term->stifle_history($HistLen); | ||
| 25 | -f($hist_file) && $self->term->ReadHistory($hist_file); | ||
| 26 | $self->term->Attribs->{do_expand}=1; | ||
| 27 | $REPL = $self if not defined $REPL; | ||
| 28 | $self->$orig(@args); | ||
| 29 | $REPL = undef; | ||
| 30 | $self->term->WriteHistory($hist_file) || | ||
| 31 | $self->print("warning: failed to write history file $hist_file"); | ||
| 32 | }; | ||
| 33 | |||
| 34 | use vars '%SIG'; | ||
| 35 | SCOPE: { | ||
| 36 | my %sig = %SIG; | ||
| 37 | $SIG{INT} = sub { | ||
| 38 | if (defined $REPL) { | ||
| 39 | $REPL->term->WriteHistory($REPL->get_history_file); | ||
| 40 | } | ||
| 41 | return $sig{INT}->(@_) if ref($sig{INT}); | ||
| 42 | }; | ||
| 43 | $SIG{TERM} = sub { | ||
| 44 | if (defined $REPL) { | ||
| 45 | $REPL->term->WriteHistory($REPL->get_history_file); | ||
| 46 | } | ||
| 47 | return $sig{TERM}->(@_) if ref($sig{INT}); | ||
| 48 | }; | ||
| 49 | } | ||
| 50 | |||
| 51 | sub get_history_file { | ||
| 52 | my $self = shift; | ||
| 53 | my $filename = '.soot_hist'; | ||
| 54 | my $histfile; | ||
| 55 | if (-f $filename) { | ||
| 56 | $histfile = $filename; | ||
| 57 | } | ||
| 58 | else { | ||
| 59 | foreach my $path ((map {$ENV{$_}} qw(HOME HOMEDIR USERDIR)), '~') { | ||
| 60 | if (defined $path and -f File::Spec->catfile($path, $filename)) { | ||
| 61 | $histfile = File::Spec->catfile($path, $filename); | ||
| 62 | last; | ||
| 63 | } | ||
| 64 | } | ||
| 65 | } | ||
| 66 | if (defined $histfile) { | ||
| 67 | return $histfile; | ||
| 68 | } else { | ||
| 69 | return $filename; | ||
| 70 | } | ||
| 71 | } | ||
| 72 | |||
| 73 | |||
| 74 | 1; |