make room for $VERSION after package declaration (newer [PkgVersion] requires it)
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / Packages.pm
1 use strict;
2 use warnings;
3 package Devel::REPL::Plugin::Packages;
4
5 use Devel::REPL::Plugin;
6 use namespace::autoclean;
7
8 our $PKG_SAVE;
9
10 has 'current_package' => (
11   isa      => 'Str',
12   is       => 'rw',
13   default  => 'Devel::REPL::Plugin::Packages::DefaultScratchpad',
14   lazy     => 1
15 );
16
17 around 'wrap_as_sub' => sub {
18   my $orig = shift;
19   my ($self, @args) = @_;
20   my $line = $self->$orig(@args);
21   # prepend package def before sub { ... }
22   return q!package !.$self->current_package.qq!;\n${line}!;
23 };
24
25 around 'mangle_line' => sub {
26   my $orig = shift;
27   my ($self, @args) = @_;
28   my $line = $self->$orig(@args);
29   # add a BEGIN block to set the package around at the end of the sub
30   # without mangling the return value (we save it off into a global)
31   $line .= '
32 ; BEGIN { $Devel::REPL::Plugin::Packages::PKG_SAVE = __PACKAGE__; }';
33   return $line;
34 };
35
36 after 'execute' => sub {
37   my ($self) = @_;
38   # if we survived execution successfully, save the new package out the global
39   $self->current_package($PKG_SAVE) if defined $PKG_SAVE;
40 };
41
42 around 'eval' => sub {
43   my $orig = shift;
44   my ($self, @args) = @_;
45   # localise the $PKG_SAVE global in case of nested evals
46   local $PKG_SAVE;
47   return $self->$orig(@args);
48 };
49
50 package Devel::REPL::Plugin::Packages::DefaultScratchpad;
51
52 # declare empty scratchpad package for cleanliness
53
54 1;
55
56 __END__
57
58 =head1 NAME
59
60 Devel::REPL::Plugin::Packages - Keep track of which package the user is in
61
62 =cut
63