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