1 package namespace::clean;
2 # ABSTRACT: Keep imports and functions out of your namespace
7 use vars qw( $STORAGE_VAR );
8 use Package::Stash 0.22;
9 use B::Hooks::EndOfScope 0.07;
11 $STORAGE_VAR = '__NAMESPACE_CLEAN_STORAGE';
19 use Carp qw(croak); # 'croak' will be removed
21 sub bar { 23 } # 'bar' will be removed
23 # remove all previously defined functions
26 sub baz { bar() } # 'baz' still defined, 'bar' still bound
28 # begin to collection function names from here again
31 sub quux { baz() } # 'quux' will be removed
33 # remove all functions defined after the 'no' unimport
36 # Will print: 'No', 'No', 'Yes' and 'No'
37 print +(__PACKAGE__->can('croak') ? 'Yes' : 'No'), "\n";
38 print +(__PACKAGE__->can('bar') ? 'Yes' : 'No'), "\n";
39 print +(__PACKAGE__->can('baz') ? 'Yes' : 'No'), "\n";
40 print +(__PACKAGE__->can('quux') ? 'Yes' : 'No'), "\n";
46 =head2 Keeping packages clean
48 When you define a function, or import one, into a Perl package, it will
49 naturally also be available as a method. This does not per se cause
50 problems, but it can complicate subclassing and, for example, plugin
51 classes that are included via multiple inheritance by loading them as
54 The C<namespace::clean> pragma will remove all previously declared or
55 imported symbols at the end of the current package's compile cycle.
56 Functions called in the package itself will still be bound by their
57 name, but they won't show up as methods on your class or instances.
59 By unimporting via C<no> you can tell C<namespace::clean> to start
60 collecting functions for the next C<use namespace::clean;> specification.
62 You can use the C<-except> flag to tell C<namespace::clean> that you
63 don't want it to remove a certain function or method. A common use would
64 be a module exporting an C<import> method along with some functions:
66 use ModuleExportingImport;
67 use namespace::clean -except => [qw( import )];
69 If you just want to C<-except> a single sub, you can pass it directly.
70 For more than one value you have to use an array reference.
72 =head2 Explicitely removing functions when your scope is compiled
74 It is also possible to explicitely tell C<namespace::clean> what packages
75 to remove when the surrounding scope has finished compiling. Here is an
81 # blessed NOT available
84 use Scalar::Util qw( blessed );
85 use namespace::clean qw( blessed );
91 # blessed NOT available
95 When using C<namespace::clean> together with L<Moose> you want to keep
96 the installed C<meta> method. So your classes should look like:
100 use namespace::clean -except => 'meta';
103 Same goes for L<Moose::Role>.
105 =head2 Cleaning other packages
107 You can tell C<namespace::clean> that you want to clean up another package
108 instead of the one importing. To do this you have to pass in the C<-cleanee>
111 package My::MooseX::namespace::clean;
114 use namespace::clean (); # no cleanup, just load
117 namespace::clean->import(
118 -cleanee => scalar(caller),
123 If you don't care about C<namespace::clean>s discover-and-C<-except> logic, and
124 just want to remove subroutines, try L</clean_subroutines>.
126 =method clean_subroutines
128 This exposes the actual subroutine-removal logic.
130 namespace::clean->clean_subroutines($cleanee, qw( subA subB ));
132 will remove C<subA> and C<subB> from C<$cleanee>. Note that this will remove the
133 subroutines B<immediately> and not wait for scope end. If you want to have this
134 effect at a specific time (e.g. C<namespace::clean> acts on scope compile end)
135 it is your responsibility to make sure it runs at that time.
139 my $sub_utils_loaded;
140 my $DebuggerRename = sub {
141 my ($f, $sub, $cleanee_stash, $deleted_stash) = @_;
143 if (! defined $sub_utils_loaded ) {
144 $sub_utils_loaded = do {
146 eval { require Sub::Name; Sub::Name->VERSION($sn_ver) }
147 or die "Sub::Name $sn_ver required when running under -d or equivalent: $@";
150 eval { require Sub::Identify; Sub::Identify->VERSION($si_ver) }
151 or die "Sub::Identify $si_ver required when running under -d or equivalent: $@";
157 if ( Sub::Identify::sub_fullname($sub) eq ($cleanee_stash->name . "::$f") ) {
158 my $new_fq = $deleted_stash->name . "::$f";
159 Sub::Name::subname($new_fq, $sub);
160 $deleted_stash->add_symbol("&$f", $sub);
164 my $RemoveSubs = sub {
167 my $cleanee_stash = Package::Stash->new($cleanee);
173 # ignore already removed symbols
174 next SYMBOL if $store->{exclude}{ $f };
176 my $sub = $cleanee_stash->get_symbol("&$f")
179 if ($^P and ref(\$cleanee_stash->namespace->{$f}) eq 'GLOB') {
180 # convince the Perl debugger to work
181 # it assumes that sub_fullname($sub) can always be used to find the CV again
182 # since we are deleting the glob where the subroutine was originally
183 # defined, that assumption no longer holds, so we need to move it
184 # elsewhere and point the CV's name to the new glob.
189 $deleted_stash ||= Package::Stash->new("namespace::clean::deleted::$cleanee"),
195 my $def = $cleanee_stash->get_symbol($name);
196 defined($def) ? [$name, $def] : ()
199 $cleanee_stash->remove_glob($f);
201 $cleanee_stash->add_symbol(@$_) for @symbols;
205 sub clean_subroutines {
206 my ($nc, $cleanee, @subs) = @_;
207 $RemoveSubs->($cleanee, {}, @subs);
212 Makes a snapshot of the current defined functions and installs a
213 L<B::Hooks::EndOfScope> hook in the current scope to invoke the cleanups.
218 my ($pragma, @args) = @_;
220 my (%args, $is_explicit);
225 if ($args[0] =~ /^\-/) {
226 my $key = shift @args;
227 my $value = shift @args;
228 $args{ $key } = $value;
236 my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
239 $RemoveSubs->($cleanee, {}, @args);
244 # calling class, all current functions and our storage
245 my $functions = $pragma->get_functions($cleanee);
246 my $store = $pragma->get_class_store($cleanee);
247 my $stash = Package::Stash->new($cleanee);
249 # except parameter can be array ref or single value
250 my %except = map {( $_ => 1 )} (
252 ? ( ref $args{ -except } eq 'ARRAY' ? @{ $args{ -except } } : $args{ -except } )
256 # register symbols for removal, if they have a CODE entry
257 for my $f (keys %$functions) {
258 next if $except{ $f };
259 next unless $stash->has_symbol("&$f");
260 $store->{remove}{ $f } = 1;
263 # register EOF handler on first call to import
264 unless ($store->{handler_is_installed}) {
266 $RemoveSubs->($cleanee, $store, keys %{ $store->{remove} });
268 $store->{handler_is_installed} = 1;
277 This method will be called when you do a
281 It will start a new section of code that defines functions to clean up.
286 my ($pragma, %args) = @_;
288 # the calling class, the current functions and our storage
289 my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
290 my $functions = $pragma->get_functions($cleanee);
291 my $store = $pragma->get_class_store($cleanee);
293 # register all unknown previous functions as excluded
294 for my $f (keys %$functions) {
295 next if $store->{remove}{ $f }
296 or $store->{exclude}{ $f };
297 $store->{exclude}{ $f } = 1;
303 =method get_class_store
305 This returns a reference to a hash in a passed package containing
306 information about function names included and excluded from removal.
310 sub get_class_store {
311 my ($pragma, $class) = @_;
312 my $stash = Package::Stash->new($class);
313 my $var = "%$STORAGE_VAR";
314 $stash->add_symbol($var, {})
315 unless $stash->has_symbol($var);
316 return $stash->get_symbol($var);
319 =method get_functions
321 Takes a class as argument and returns all currently defined functions
322 in it as a hash reference with the function name as key and a typeglob
323 reference to the symbol as value.
328 my ($pragma, $class) = @_;
330 my $stash = Package::Stash->new($class);
332 map { $_ => $stash->get_symbol("&$_") }
333 $stash->list_all_symbols('CODE')
337 =head1 IMPLEMENTATION DETAILS
339 This module works through the effect that a
341 delete $SomePackage::{foo};
343 will remove the C<foo> symbol from C<$SomePackage> for run time lookups
344 (e.g., method calls) but will leave the entry alive to be called by
345 already resolved names in the package itself. C<namespace::clean> will
346 restore and therefor in effect keep all glob slots that aren't C<CODE>.
348 A test file has been added to the perl core to ensure that this behaviour
349 will be stable in future releases.
351 Just for completeness sake, if you want to remove the symbol completely,
352 use C<undef> instead.
356 L<B::Hooks::EndOfScope>
360 Many thanks to Matt S Trout for the inspiration on the whole idea.
365 'Danger! Laws of Thermodynamics may not apply.'