blib/lib/Test/NoShadow.pm

filter: Statementstmt 97.9% 144 / 147 Branchbran 82.0% 41 / 50 Conditioncond 71.4% 25 / 35 MC/DCmcdc 54.5% 12 / 22 Subroutinesub 100% 14 / 14 Podpod 100% 3 / 3 totaltotal 88.1% 239 / 271 CC 43 SCAR 22.9
CC
43
Cov
91%
lib_ok
17.6
__ANON__
10.3
shadowed_ok
10.0
CRAP 9.9
↑ Summary
1 package Test::NoShadow;
2  
3 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 5 ▶use parent 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 our @ISA = qw(Exporter);
8  
9 5 ▶use Cwd qw(abs_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use File::Find;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 5 ▶use Test::Builder;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 5 our @EXPORT_OK = qw(shadowed_ok lib_ok find_shadows);
15 5 our %EXPORT_TAGS = (all => \@EXPORT_OK);
16  
17 5 our $TEST = Test::Builder->new();
18  
19 =head1 NAME
20  
21 Test::NoShadow - Fail CI when two distributions provide the same Perl package, or when t/ exercises a copy other than the one under test
22  
23 =head1 VERSION
24  
25 Version 0.001.0
26  
27 =cut
28  
29 5 our $VERSION = '0.001.0';
30  
31 5 my @SKIP_DIRS = qw(.git .github .svn CVS blib _build cover_db node_modules .pc);
32  
33 =head1 SYNOPSIS
34  
35 # In your CI, over a directory of checkouts:
36 use Test::More;
37 use Test::NoShadow qw(shadowed_ok lib_ok find_shadows);
38  
39 shadowed_ok('/home/njh'); # fails if any Perl package is provided by two checkouts
40  
41 # In a distribution's own t/, after using its modules:
42 use My::Module;
43 lib_ok('My::Module'); # fails if My::Module came from anywhere but this distribution
44  
45 # Or inspect the data yourself:
46 my $shadows = find_shadows('/home/njh');
47 foreach my $package (sort keys %$shadows) {
48 diag("$package: @{ $shadows->{$package} }");
49 }
50  
51 =head1 DESCRIPTION
52  
53 C<Test::NoShadow> fails your test suite when two distributions provide the same
54 Perl package, and when a distribution's tests exercise a copy other than the
55 one under test (an older installed copy, or a vendored copy in C<t/>).
56  
57 It was written to police a workspace of many checkouts: pairs such as
58 C<Schema::Validator> in both C<schema-validator> and C<Schema-Validator>,
59 or a vendored C<VWF::*> inside another distribution, ship identical package
60 names, so C<use> can silently load the wrong code.
61  
62 No other CPAN module checks for the multi-checkout variant; the closest
63 relative, L<Test::CleanNamespaces>, works on installed distributions only.
64  
65 Two checks are provided:
66  
67 =over 4
68  
69 =item * L</"shadowed_ok"> - a directory of checkouts (or the installed C<@INC>)
70 must not contain a Perl package in more than one place
71  
72 =item * L</"lib_ok"> - each named module must have been loaded from the
73 distribution's own C<lib/> or C<blib/lib>
74  
75 =back
76  
77 =head1 FUNCTIONS/METHODS
78  
79 =head2 shadowed_ok [@dirs, [ \%options ]]
80  
81 Scans each directory (recursively) for C<.pm> files and extracts the package
82 names they declare. Passes if no Perl package is declared in more than one
83 file; otherwise fails, with a diagnostic naming both providers.
84  
85 With no directories given, C<@INC> is scanned - for example:
86  
87 prove -Ilib t/shadow.t
88  
89 The following options are recognised in the optional hash reference:
90  
91 =over 4
92  
93 =item * C<ignore> - array reference of regexps. Each is matched against
94 both the C<"provider/package"> pair and the file's path; if either matches,
95 the file is excluded, e.g. C<< { ignore => [qr{^WWW-Scrape-BillionGraves/}, qr{/t/lib/}] } >>.
96 The file's path is also matched with backslashes converted to forward
97 slashes, so patterns such as C<qr{/t/lib/}> work on Windows as well
98  
99 =back
100  
101 Each top-level directory beneath the scanned directory is treated as a
102 "provider" (in this workspace, a checkout); files directly beneath the
103 scanned directory are labelled with their own file name. To check a single
104 checkout for vendored copies, pass the checkout itself: its top-level
105 directory (usually C<lib>) becomes the provider, and copies under C<t/> are
106 reported alongside copies under C<lib>.
107  
108 Returns true on success, false on failure.
109  
110 =head2 lib_ok @modules, [ \%options ]
111  
112 For use in the distribution's own tests, after the modules have been
113 C<use>d. Passes if each named module was loaded from this distribution's
114 F<lib> or F<blib/lib>; fails if a module was loaded from anywhere else
115 (a shadowing copy installed in C<@INC>), or was not loaded at all.
116  
117 One test is run per module.
118  
119 The following options are recognised:
120  
121 =over 4
122  
123 =item * C<dir> - the root of the distribution, default F<.>
124  
125 =item * C<lib> - array reference of library directories beneath C<dir>
126 that count as "the copy under test", default C<[qw(lib blib/lib)]>
127  
128 =back
129  
130 Returns true if all modules passed.
131  
132 =head2 find_shadows $dir, [ \%options ]
133  
134 The non-TAP interface: returns a hash reference mapping each shadowed
135 package name to a sorted array reference of the files that declare it.
136 Accepts the same options as L</"shadowed_ok">.
137  
138 =cut
139  
140 # Extract the package names declared in a .pm file
141 45 ▶sub _packages_in_file {
Subroutine _packages_in_file: called CC=5 SCAR=16.2
142 45 my ($file) = @_;
143  
144 45 ▶ open(my $fh, '<', $file) or return [];
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or return [] 45 0 45
145 45 my %packages;
146 45 ▶ while (my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 342 45 387
147 # Handles "package Foo::Bar;", "package Foo::Bar 1.23;" and "package Foo::Bar {"
148 342 ▶ if($line =~ /^\s*package\s+([A-Za-z_][A-Za-z0-9_:]*)(?:\s+v?[\d._]+)?\s*[;{]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^\s*package\s+([A-Za-z_][A-Za-z0-9_:]*)(?:\s+v?[\d._]+)?\s*[;{]/) 45 297 342
149 45 ▶ $packages{$1} = 1 unless($1 eq 'main');
Branch: 1 branch
BranchTrueFalseTotal
unless $1 eq "main" 45 0 45
150 }
151 }
152 45 close($fh);
153  
154 45 return [sort keys %packages];
155 }
156  
157 # The "provider" of a file is the first directory beneath the root
158 45 ▶sub _provider_for {
Subroutine _provider_for: called CC=1 SCAR=0.0
159 45 my ($root, $file) = @_;
160  
161 45 my $rel = File::Spec->abs2rel($file, $root);
162 45 my @parts = File::Spec->splitdir($rel);
163  
164 45 return $parts[0];
165 }
166  
167 # Recursively scan a directory for .pm files.
168 # Returns { package => { abspath => provider } }
169 12 ▶sub _scan {
Subroutine _scan: called CC=3 SCAR=11.0
170 12 my ($root, $opts) = @_;
171  
172 12 my $abs = abs_path($root);
173 12 ▶ unless(defined($abs) && -d $abs) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $abs and -d $abs) 1 11 12
Condition66%2/3
defined $abs and -d $abs
!ll&&!rl&&r
1011
MC/DC50%1/2
defined $abs and -d $abs
defined $abs -d $abs
Truth table66%2/3
A and B
A= defined $absB= -d $abs
ABresult
0X0
100
111
174 1 die "Test::NoShadow: $root is not a directory";
175 }
176  
177 11 my %skip = map { $_ => 1 } (@SKIP_DIRS);
178 11 my %found;
179  
180 File::Find::find({
181 133 ▶ wanted => sub {
Subroutine __ANON__: called CC=10 SCAR=23.3
182 133 my $name = $File::Find::name;
183  
184 133 ▶ if(-d $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $name) 88 45 133
185 88 ▶ $File::Find::prune = 1 if($skip{(File::Spec->splitdir($name))[-1]});
Branch: 1 branch
BranchTrueFalseTotal
if $skip{("File::Spec"->splitdir($name))[-1]} 0 88 88
186 88 return;
187 }
188 45 ▶ return unless($name =~ /\.pm$/);
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\.pm$/ 0 45 45
189  
190 45 my $provider = _provider_for($abs, $name);
191 45 ▶ my $file = abs_path($name) || $name;
Condition33%1/3
abs_path($name) || $name
l!l&&r!l&&!r
4500
MC/DC0%0/2
abs_path($name) || $name
abs_path($name) $name
Truth table33%1/3
A || B
A= abs_path($name)B= $name
ABresult
1X1
011
000
192 # Match ignore patterns against the path with backslashes as
193 # slashes too, so qr{/t/lib/} works on Windows
194 45 (my $fwd = $file) =~ s{\\}{/}g;
195  
196 45 foreach my $package (@{_packages_in_file($name)}) {
197 45 ▶ if($opts->{'ignore'} && grep { "$provider/$package" =~ $_ || $file =~ $_ || $fwd =~ $_ } @{$opts->{'ignore'}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"ignore"} and grep {("$provider/$package") =~ /$_/ or $file =~ /$_/ or $fwd =~ /$_/;} @{$$opts{"ignore"};}) 6 39 45
Condition88%8/9
$opts->{"ignore"} and grep {("$provider/$package") =~ /$_/ or $file =~ /$_/ or $fwd =~ /$_/;} @{$$opts{"ignore"};}
!ll&&!rl&&r
3186
("$provider/$package") =~ /$_/ || $file =~ /$_/ || $fwd =~ /$_/
l!l&&r!l&&!r
6022
("$provider/$package") =~ /$_/ or $file =~ /$_/
l!l&&r!l&&!r
5122
MC/DC100%2/2
$opts->{"ignore"} and grep {("$provider/$package") =~ /$_/ or $file =~ /$_/ or $fwd =~ /$_/;} @{$$opts{"ignore"};}
$opts->{"ignore"} grep {("$provider/$package") =~ /$_/ or $file =~ /$_/ or $fwd =~ /$_/;} @{$$opts{"ignore"};}
MC/DC66%2/3
("$provider/$package") =~ /$_/ || $file =~ /$_/ || $fwd =~ /$_/
("$provider/$package") =~ /$_/ $file =~ /$_/ $fwd =~ /$_/
Truth table100%3/3
A and B
A= $opts->{"ignore"}B= grep {("$provider/$package") =~ /$_/ or $file =~ /$_/ or $fwd =~ /$_/;} @{$$opts{"ignore"};}
ABresult
0X0
100
111
Truth table75%3/4
A or B || C
A= ("$provider/$package") =~ /$_/B= $file =~ /$_/C= $fwd =~ /$_/
ABCresult
1XX1
01X1
0011
0000
198 6 next;
199 }
200 39 $found{$package}{$file} = $provider;
201 }
202 },
203 11 no_chdir => 1,
204 }, $abs);
205  
206 11 return \%found;
207 }
208  
209 6 ▶sub find_shadows {
Subroutine find_shadows: called CC=3 SCAR=11.0
Pod documented
210 6 my ($dir, @args) = @_;
211  
212 6 ▶ unless(defined($dir)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $dir) 0 6 6
213 0 die 'Test::NoShadow: find_shadows needs a directory to scan';
214 }
215  
216 6 my %opts;
217 6 ▶ if(ref($args[0]) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args[0] eq "HASH") 1 5 6
218 1 %opts = %{$args[0]};
219 }
220  
221 6 my $found = _scan($dir, \%opts);
222  
223 return {
224 6 map { $_ => [sort keys %{$found->{$_}}] }
225 5 (grep { scalar(keys %{$found->{$_}}) > 1 } (keys %$found))
226 };
227 }
228  
229 5 ▶sub shadowed_ok {
Subroutine shadowed_ok: called CC=10 SCAR=23.1
Pod documented
230 5 my @args = @_;
231 5 my %opts;
232 5 ▶ if(@args && ref($args[-1]) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (@args and ref $args[-1] eq "HASH") 1 4 5
Condition100%3/3
@args and ref $args[-1] eq "HASH"
!ll&&!rl&&r
221
MC/DC100%2/2
@args and ref $args[-1] eq "HASH"
@args ref $args[-1] eq "HASH"
Truth table100%3/3
A and B
A= @argsB= ref $args[-1] eq "HASH"
ABresult
0X0
100
111
233 1 %opts = %{pop(@args)};
234 }
235  
236 5 ▶ my @roots = @args ? @args : (grep { -d $_ } @INC);
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 3 2 5
237  
238 5 ▶ unless(@roots) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@roots) 0 5 5
239 0 $TEST->skip('Test::NoShadow: no directories to scan');
240 0 return 0;
241 }
242  
243 5 my %found; # package => { file => provider }
244 5 foreach my $root (@roots) {
245 6 my $scanned = _scan($root, \%opts);
246 6 ▶ while (my ($package, $files) = each %$scanned) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$scanned) 12 6 18
247 12 ▶ while (my ($file, $provider) = each %$files) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$files) 15 12 27
248 15 $found{$package}{$file} = $provider;
249 }
250 }
251 }
252  
253 5 my @shadowed = grep { scalar(keys %{$found{$_}}) > 1 } (keys %found);
254  
255 5 ▶ unless(@shadowed) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@shadowed) 3 2 5
256 3 $TEST->ok(1, 'No shadowed Perl packages');
257 3 return 1;
258 }
259  
260 2 my @messages;
261 2 foreach my $package (sort @shadowed) {
262 3 my $count = scalar(keys %{$found{$package}});
263 3 push @messages, "$package is provided by $count files:";
264 3 push @messages, map { "\t$found{$package}{$_}: $_" } (sort keys %{$found{$package}});
265 }
266  
267 2 $TEST->ok(0, scalar(@shadowed) . ' shadowed Perl package(s) found');
268 2 $TEST->diag(join("\n", @messages));
269  
270 2 return 0;
271 }
272  
273 5 ▶sub lib_ok {
Subroutine lib_ok: called CC=17 SCAR=28.7
Pod documented
274 5 my @modules = @_;
275 5 my %opts;
276 5 ▶ if(@modules && ref($modules[-1]) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (@modules and ref $modules[-1] eq "HASH") 1 4 5
Condition100%3/3
@modules and ref $modules[-1] eq "HASH"
!ll&&!rl&&r
131
MC/DC100%2/2
@modules and ref $modules[-1] eq "HASH"
@modules ref $modules[-1] eq "HASH"
Truth table100%3/3
A and B
A= @modulesB= ref $modules[-1] eq "HASH"
ABresult
0X0
100
111
277 1 %opts = %{pop(@modules)};
278 }
279  
280 5 ▶ unless(@modules) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@modules) 1 4 5
281 1 $TEST->ok(0, 'lib_ok was given modules to check');
282 1 $TEST->diag('lib_ok: no modules specified');
283 1 return 0;
284 }
285  
286 4 ▶ my $dir = abs_path(exists($opts{'dir'}) ? $opts{'dir'} : '.');
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'dir'} ? : 0 4 4
287 # abs_path returns undef for directories that do not exist (blib/lib is
288 # absent when tests are run from the source tree rather than from a
289 # built distribution), so fall back to a normalised absolute path
290 my @libs = map {
291 9 ▶ my $path = File::Spec->catdir(defined($dir) ? $dir : File::Spec->curdir(), $_);
Branch: 1 branch
BranchTrueFalseTotal
defined $dir ? : 9 0 9
292 9 ▶ abs_path($path) || File::Spec->rel2abs($path);
Condition33%1/3
abs_path($path) || 'File::Spec'->rel2abs($path)
l!l&&r!l&&!r
900
MC/DC0%0/2
abs_path($path) || 'File::Spec'->rel2abs($path)
abs_path($path) 'File::Spec'->rel2abs($path)
Truth table33%1/3
A || B
A= abs_path($path)B= 'File::Spec'->rel2abs($path)
ABresult
1X1
011
000
293 4 ▶ } (@{$opts{'lib'} || [qw(lib blib/lib)]});
Condition100%2/2
$opts{'lib'} || ['lib', 'blib/lib']
l!l
13
MC/DC100%1/1
$opts{'lib'} || ['lib', 'blib/lib']
$opts{'lib'}
Truth table100%2/2
A
A= $opts{'lib'}
Aresult
11
00
294  
295 4 my $return = 1;
296 4 foreach my $module (@modules) {
297 # %INC is keyed by file path, not by package name
298 4 (my $path = $module) =~ s/::/\//g;
299 4 ▶ my $file = $INC{"$path.pm"} || $INC{$module};
Condition66%2/3
$INC{"$path.pm"} || $INC{$module}
l!l&&r!l&&!r
301
MC/DC50%1/2
$INC{"$path.pm"} || $INC{$module}
$INC{"$path.pm"} $INC{$module}
Truth table66%2/3
A || B
A= $INC{"$path.pm"}B= $INC{$module}
ABresult
1X1
011
000
300  
301 4 ▶ unless(defined($file)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $file) 1 3 4
302 1 $TEST->ok(0, "$module was loaded from this distribution's lib");
303 1 $TEST->diag("$module has not been loaded; use it before calling lib_ok");
304 1 $return = 0;
305 1 next;
306 }
307  
308 3 ▶ my $abs = abs_path($file) || File::Spec->rel2abs($file);
Condition33%1/3
abs_path($file) || 'File::Spec'->rel2abs($file)
l!l&&r!l&&!r
300
MC/DC0%0/2
abs_path($file) || 'File::Spec'->rel2abs($file)
abs_path($file) 'File::Spec'->rel2abs($file)
Truth table33%1/3
A || B
A= abs_path($file)B= 'File::Spec'->rel2abs($file)
ABresult
1X1
011
000
309 3 my $ok = 0;
310 3 foreach my $lib (@libs) {
311 7 ▶ next unless(defined($lib));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lib 0 7 7
312 7 my $rel = File::Spec->abs2rel($abs, $lib);
313 7 ▶ if($rel !~ /^\.\.(?:\/|\\|$)/ && !File::Spec->file_name_is_absolute($rel)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rel =~ m[^\.\.(?:/|\\|$)] or "File::Spec"->file_name_is_absolute($rel)) 1 6 7
Condition66%2/3
$rel =~ m[^\.\.(?:/|\\|$)] or "File::Spec"->file_name_is_absolute($rel)
l!l&&r!l&&!r
601
MC/DC50%1/2
$rel =~ m[^\.\.(?:/|\\|$)] or "File::Spec"->file_name_is_absolute($rel)
$rel =~ m[^\.\.(?:/|\\|$)] "File::Spec"->file_name_is_absolute($rel)
Truth table66%2/3
A or B
A= $rel =~ m[^\.\.(?:/|\\|$)]B= "File::Spec"->file_name_is_absolute($rel)
ABresult
1X1
011
000
314 1 $ok = 1;
315 1 last;
316 }
317 }
318  
319 3 ▶ if($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 1 2 3
320 1 $TEST->ok(1, "$module was loaded from this distribution's lib ($abs)");
321 }
322 else {
323 2 $TEST->ok(0, "$module was loaded from this distribution's lib");
324 2 $TEST->diag("$module was loaded from $abs, not from " . join(' or ', @libs) . ' - is a shadowing copy installed?');
325 2 $return = 0;
326 }
327 }
328  
329 4 return $return;
330 }
331  
332 5 1;
333  
334 __END__
↑ Summary