blib/lib/Exporter/ConditionalSubs.pm

filter: Statementstmt 69.5% 48 / 69 Branchbran 50.0% 12 / 24 Conditioncond 30.0% 6 / 20 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 90.9% 10 / 11 Podpod n/a totaltotal 57.5% 76 / 132 CC 22 SCAR 39.1
CC
22
Cov
58%
import
72.3
__ANON__
2.0
BEGIN
1.0
CRAP 50.0
↑ Summary
1 package Exporter::ConditionalSubs;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 require Exporter;
7 3 our @ISA = qw( Exporter );
8  
9 3 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 #pod =head1 NAME
12 #pod
13 #pod Exporter::ConditionalSubs - Conditionally export subroutines
14 #pod
15 #pod =head1 VERSION
16 #pod
17 #pod Version 1.01
18 #pod
19 #pod =cut
20  
21 3 our $VERSION = '1.01';
22  
23 #pod =head1 SYNOPSIS
24 #pod
25 #pod Allows subroutines to be conditionally exported. If the condition
26 #pod is satisfied, the subroutine will be exported as usual. But if not,
27 #pod the subroutine will be replaced with a stub that gets optimized away
28 #pod by the compiler. When stubbed out, not even the arguments to the
29 #pod subroutine will get evaluated.
30 #pod
31 #pod This allows for e.g. assertion-like behavior, where subroutine calls
32 #pod can be left in the code but effectively ignored under certain conditions.
33 #pod
34 #pod First create a module that C<ISA> L<Exporter::ConditionalSubs>:
35 #pod
36 #pod package My::Assertions;
37 #pod
38 #pod require Exporter::ConditionalSubs;
39 #pod our @ISA = qw( Exporter::ConditionalSubs );
40 #pod
41 #pod our @EXPORT = ();
42 #pod our @EXPORT_OK = qw( _assert_non_empty );
43 #pod
44 #pod sub _assert_non_empty
45 #pod {
46 #pod carp "Found empty value" unless length(shift // '') > 0;
47 #pod }
48 #pod
49 #pod Then, specify an C<-if> or C<-unless> condition when C<use>ing that module:
50 #pod
51 #pod package My::App;
52 #pod
53 #pod use My::Assertions qw( _assert_non_empty ), -if => $ENV{DEBUG};
54 #pod
55 #pod use My::MoreAssertions -unless => $ENV{RUNTIME} eq 'prod';
56 #pod
57 #pod # Coderefs work too:
58 #pod use My::OtherAssertions -if => sub { ... some logic ... };
59 #pod
60 #pod _assert_non_empty($foo); # this subroutine call might be a no-op
61 #pod
62 #pod
63 #pod This is a subclass of L<Exporter> and works just like it, with the
64 #pod addition of support for the C<-if> and C<-unless> import arguments.
65 #pod
66 #pod =head1 SUBROUTINES
67 #pod
68 #pod =head2 import
69 #pod
70 #pod Works like the L<Exporter> C<import()> function, except that it checks
71 #pod for an optional C<-if> or C<-unless> import arg, followed by either
72 #pod a boolean, or a coderef that returns true/false.
73 #pod
74 #pod If the condition evaluates to true for C<-if>, or false for C<-unless>,
75 #pod then any subs are exported as-is. Otherwise, any subs in C<@EXPORT_OK>
76 #pod are replaced with stubs that get optimized away by the compiler (with
77 #pod one exception - see L</CAVEATS> below).
78 #pod
79 #pod You can specify either C<-if> or C<-unless>, but not both. Croaks if
80 #pod both are specified, or if you specify the same option more than once.
81 #pod
82 #pod =cut
83  
84 sub import
85 {
86 11 ▶ my ($package, @args) = @_;
Subroutine import: called CC=22 SCAR=42.8
87  
88 # By default we are going to export subs as-is and not optimize them away:
89 11 my $should_export_subs = 1;
90  
91 11 my @export_args = ($package);
92  
93 # Copy args until we come across "-if" or "-unless":
94 #
95 11 ▶ while (@args && ($args[0] || '') !~ /^-(?:if|unless)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args and not +($args[0] || "") =~ /^-(?:if|unless)$/) 18 11 29
Condition80%4/5
@args and not +($args[0] || "") =~ /^-(?:if|unless)$/
!ll&&!rl&&r
3818
$args[0] || ''
l!l
260
MC/DC0%0/2
@args and not +($args[0] || "") =~ /^-(?:if|unless)$/
@args $args[0]
Truth table66%2/3
A and not(B)
A= @argsB= $args[0]
ABresult
0X0
110
101
96 18 push @export_args, shift @args;
97 }
98  
99 # If any args remain, it must be because we found "-if" or "-unless".
100 # We expect the next arg to be the condition boolean or coderef:
101 #
102 11 ▶ if (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 8 3 11
103 8 my $thing = shift @args; # i.e. "-if" or "-unless"
104 8 ▶ unless (@args) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@args) 0 8 8
105 0 croak "$package->import failed: " .
106 qq{"$thing" must be followed by boolean or coderef};
107 }
108 8 my $condition = shift @args;
109  
110 # Go ahead and evaluate the condition if it's a coderef:
111 8 ▶ $condition = $condition->() if ref($condition) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $condition eq "CODE" 4 4 8
112  
113 # We might decide against importing subs, depending on the condition:
114 8 ▶ $should_export_subs = $thing eq '-if' ? $condition : !$condition;
Branch: 1 branch
BranchTrueFalseTotal
$thing eq '-if' ? : 4 4 8
115  
116 # Copy any remaining args:
117 #
118 8 ▶ while (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 0 8 8
119 0 ▶ if ($args[0] && $args[0] =~ /^-(?:if|unless)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args[0] and $args[0] =~ /^-(?:if|unless)$/) 0 0 0
Condition0%0/3
$args[0] and $args[0] =~ /^-(?:if|unless)$/
!ll&&!rl&&r
000
MC/DC0%0/2
$args[0] and $args[0] =~ /^-(?:if|unless)$/
$args[0] $args[0] =~ /^-(?:if|unless)$/
Truth table0%0/3
A and B
A= $args[0]B= $args[0] =~ /^-(?:if|unless)$/
ABresult
0X0
100
111
120 0 croak "$package->import failed: " .
121 qq{Cannot use "$args[0]" after "$thing"};
122 }
123 0 push @export_args, shift @args;
124 }
125 }
126  
127 # Pulling in B::CallChecker and/or B::Generate to optimize away
128 # the exported symbols can break test coverage metrics generated
129 # by Devel::Cover. We probably want to check coverage on the actual
130 # exports anyway, so if Devel::Cover is in play assume we *should*
131 # export everything:
132 #
133 # (took this conditional logic directly from Devel::Cover)
134 #
135 $should_export_subs = 1 if (
136 $INC{'Devel/Cover.pm'} ||
137 ($ENV{HARNESS_PERL_SWITCHES} || "") =~ /Devel::Cover/ ||
138 11 ▶ ($ENV{PERL5OPT} || "") =~ /Devel::Cover/
Branch: 1 branch
BranchTrueFalseTotal
if $INC{"Devel/Cover.pm"} or ($ENV{"HARNESS_PERL_SWITCHES"} || "") =~ /Devel::Cover/ or ($ENV{"PERL5OPT"} || "") =~ /Devel::Cover/ 0 0 0
Condition20%2/10
$INC{"Devel/Cover.pm"} or ($ENV{"HARNESS_PERL_SWITCHES"} || "") =~ /Devel::Cover/ or ($ENV{"PERL5OPT"} || "") =~ /Devel::Cover/
l!l&&r!l&&!r
1100
$INC{"Devel/Cover.pm"} or ($ENV{"HARNESS_PERL_SWITCHES"} || "") =~ /Devel::Cover/
l!l&&r!l&&!r
1100
$ENV{'HARNESS_PERL_SWITCHES'} || ''
l!l
00
$ENV{'PERL5OPT'} || ''
l!l
00
MC/DC0%0/3
$INC{"Devel/Cover.pm"} or ($ENV{"HARNESS_PERL_SWITCHES"} || "") =~ /Devel::Cover/ or ($ENV{"PERL5OPT"} || "") =~ /Devel::Cover/
$INC{"Devel/Cover.pm"} $ENV{'HARNESS_PERL_SWITCHES'} $ENV{'PERL5OPT'}
Truth table25%1/4
A or B or C
A= $INC{"Devel/Cover.pm"}B= $ENV{'HARNESS_PERL_SWITCHES'}C= $ENV{'PERL5OPT'}
ABCresult
1XX1
01X1
0011
0000
139 );
140  
141 # If the "if" condition is false, or the "unless" condition is true,
142 # replace any exportable subs with something that will get optimized away:
143 #
144 11 my %their_original_coderefs;
145 11 ▶ unless ($should_export_subs) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($should_export_subs) 0 11 11
146  
147 3 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
148 0 my $stash = *{ $package . "::" };
149  
150 0 ▶ my @their_export_oks = @{ ($stash->{EXPORT_OK} || []) };
Branch: 1 branch
BranchTrueFalseTotal
$stash->{"EXPORT_OK"} or [] 0 0 0
151 0 for my $export_name (@their_export_oks) {
152  
153 0 my $globref = $stash->{$export_name};
154 0 ▶ if ($globref && *$globref{CODE}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($globref and *$globref{"CODE"}) 0 0 0
Condition0%0/2
$globref and *$globref{"CODE"}
!ll
00
MC/DC0%0/1
$globref and *$globref{"CODE"}
$globref
Truth table0%0/2
A
A= $globref
Aresult
00
11
155  
156 0 my $symbol = $package . "::" . $export_name;
157  
158 # Save a copy of the original code:
159 0 $their_original_coderefs{$symbol} = \&$symbol;
160  
161 0 require B::CallChecker;
162 0 require B::Generate;
163  
164 # Replace the sub being imported with a void prototype sub
165 # that gets optimized away:
166 #
167 {
168 3 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.2
169 3 ▶ no warnings 'prototype';
Subroutine BEGIN: called CC=1 SCAR=0.0
170  
171 0 *$symbol = sub () {0};
172  
173 #---------------------------------------------------------
174 #
175 # This section lifted almost as-is from Debug::Show v0.0
176 #
177 # https://metacpan.org/pod/Debug::Show
178 #
179 # Thanks to Zefram
180 #
181 B::CallChecker::cv_set_call_checker(
182 \&$symbol,
183 sub ($$$) {
184 0 ▶ my($entersubop, undef, undef) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
185 # B::Generate doesn't offer a way to explicitly free ops.
186 # We ought to be able to implicitly free $entersubop via
187 # constant folding, by something like
188 #
189 # return B::LOGOP->new("and", 0,
190 # B::SVOP->new("const", 0, !1),
191 # $entersubop);
192 #
193 # but empirically that causes memory corruption and it's
194 # not clear why. For the time being, leak $entersubop.
195 0 return B::SVOP->new("const", 0, !1);
196 },
197 0 \!1
198 );
199 #
200 #---------------------------------------------------------
201 }
202 }
203 }
204 }
205  
206 # Let Export handle everything else as usual:
207 11 $package->export_to_level(1, @export_args);
208  
209 # Restore coderefs in the original package with their saved version:
210 #
211 11 ▶ while (my ($symbol, $coderef) = each %their_original_coderefs) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %their_original_coderefs) 0 11 11
212 3 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
213 3 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
214 3 ▶ no warnings 'prototype';
Subroutine BEGIN: called CC=1 SCAR=0.0
215 0 *$symbol = $coderef;
216 }
217 }
218  
219 #pod =head1 CAVEATS
220 #pod
221 #pod This module uses L<B::CallChecker> and L<B::Generate> under the covers
222 #pod to optimize away the exported subroutines. Loading one or the other
223 #pod of those modules can potentially break test coverage metrics generated
224 #pod by L<Devel::Cover> in mysterious ways.
225 #pod
226 #pod To avoid this problem, subroutines are never optimized away
227 #pod if L<Devel::Cover> is in use, and are always exported as-is
228 #pod regardless of any C<-if> or C<-unless> conditions. (You probably
229 #pod want L<Devel::Cover> to assess the coverage of your real exported
230 #pod subroutines in any case.)
231 #pod
232 #pod =head1 SEE ALSO
233 #pod
234 #pod L<Exporter>
235 #pod
236 #pod L<B::CallChecker>
237 #pod
238 #pod L<B::Generate>
239 #pod
240 #pod =head1 AUTHOR
241 #pod
242 #pod Larry Leszczynski, C<< <larryl at cpan.org> >>
243 #pod
244 #pod =head1 BUGS
245 #pod
246 #pod Please report any bugs or feature requests at:
247 #pod L<https://github.com/GrantStreetGroup/Exporter-ConditionalSubs>
248 #pod
249 #pod =head1 SUPPORT
250 #pod
251 #pod You can find documentation for this module with the perldoc command.
252 #pod
253 #pod perldoc Exporter::ConditionalSubs
254 #pod
255 #pod You can also look for information at:
256 #pod
257 #pod =over 4
258 #pod
259 #pod =item * GitHub
260 #pod
261 #pod L<https://github.com/GrantStreetGroup/Exporter-ConditionalSubs>
262 #pod
263 #pod =item * MetaCPAN
264 #pod
265 #pod L<https://metacpan.org/pod/Exporter::ConditionalSubs>
266 #pod
267 #pod =item * AnnoCPAN, Annotated CPAN documentation
268 #pod
269 #pod L<http://annocpan.org/dist/Exporter-ConditionalSubs>
270 #pod
271 #pod =item * CPAN Ratings
272 #pod
273 #pod L<http://cpanratings.perl.org/d/Exporter-ConditionalSubs>
274 #pod
275 #pod =back
276 #pod
277 #pod =head1 AUTHOR
278 #pod
279 #pod Larry Leszczynski, C<< <larryl at cpan.org> >>
280 #pod
281 #pod =head1 ACKNOWLEDGEMENTS
282 #pod
283 #pod Thanks to Grant Street Group L<http://www.grantstreet.com> for funding
284 #pod development of this code.
285 #pod
286 #pod Thanks to Tom Christiansen (C<< <tchrist@perl.com> >>) for help with the
287 #pod symbol table hackery.
288 #pod
289 #pod Thanks to Zefram (C<< <zefram@fysh.org> >>) for the pointer to his
290 #pod L<Debug::Show> hackery.
291 #pod
292 #pod =head1 LICENSE AND COPYRIGHT
293 #pod
294 #pod Copyright 2015 Grant Street Group
295 #pod
296 #pod This program is free software; you can redistribute it and/or modify it
297 #pod under the terms of the the Artistic License (2.0). You may obtain a
298 #pod copy of the full license at:
299 #pod
300 #pod L<http://www.perlfoundation.org/artistic_license_2_0>
301 #pod
302 #pod Any use, modification, and distribution of the Standard or Modified
303 #pod Versions is governed by this Artistic License. By using, modifying or
304 #pod distributing the Package, you accept this license. Do not use, modify,
305 #pod or distribute the Package, if you do not accept this license.
306 #pod
307 #pod If your Modified Version has been derived from a Modified Version made
308 #pod by someone other than you, you are nevertheless required to ensure that
309 #pod your Modified Version complies with the requirements of this license.
310 #pod
311 #pod This license does not grant you the right to use any trademark, service
312 #pod mark, tradename, or logo of the Copyright Holder.
313 #pod
314 #pod This license includes the non-exclusive, worldwide, free-of-charge
315 #pod patent license to make, have made, use, offer to sell, sell, import and
316 #pod otherwise transfer the Package with respect to any patent claims
317 #pod licensable by the Copyright Holder that are necessarily infringed by the
318 #pod Package. If you institute patent litigation (including a cross-claim or
319 #pod counterclaim) against any party alleging that the Package constitutes
320 #pod direct or contributory patent infringement, then this Artistic License
321 #pod to you shall terminate on the date that such litigation is filed.
322 #pod
323 #pod Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
324 #pod AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
325 #pod THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
326 #pod PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
327 #pod YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
328 #pod CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
329 #pod CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
330 #pod EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
331 #pod
332 #pod =cut
333  
334 3 1;
335  
336 __END__
↑ Summary