Commit | Line | Data |
1716b200 |
1 | use strict; |
2 | use warnings; |
80f0324c |
3 | package Devel::REPL::Plugin::Packages; |
9cfc1536 |
4 | use Devel::REPL::Plugin; |
5 | |
aa8b7647 |
6 | use namespace::autoclean; |
80f0324c |
7 | |
28e93f31 |
8 | our $PKG_SAVE; |
80f0324c |
9 | |
10 | has 'current_package' => ( |
11 | isa => 'Str', |
12 | is => 'rw', |
ae5e19ec |
13 | default => 'Devel::REPL::Plugin::Packages::DefaultScratchpad', |
80f0324c |
14 | lazy => 1 |
15 | ); |
16 | |
ae5e19ec |
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) |
46407908 |
31 | $line .= ' |
32 | ; BEGIN { $Devel::REPL::Plugin::Packages::PKG_SAVE = __PACKAGE__; }'; |
ae5e19ec |
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 |
7c7c35c1 |
39 | $self->current_package($PKG_SAVE) if defined $PKG_SAVE; |
ae5e19ec |
40 | }; |
41 | |
80f0324c |
42 | around 'eval' => sub { |
ae5e19ec |
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); |
80f0324c |
48 | }; |
49 | |
ae5e19ec |
50 | package Devel::REPL::Plugin::Packages::DefaultScratchpad; |
80f0324c |
51 | |
ae5e19ec |
52 | # declare empty scratchpad package for cleanliness |
53 | |
54 | 1; |
cfd1094b |
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 | |