blib/lib/Test/CPAN/Health/Distribution.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Test/CPAN/Health/Config.pm ↑ Summary blib/lib/Test/CPAN/Health/Report.pm »
1 package Test::CPAN::Health::Distribution;
2  
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 use Carp qw(croak carp);
8 use File::Find::Rule;
9 use File::Spec;
10 use Readonly;
11 use Params::Validate::Strict qw(validate_strict);
12  
13 our $VERSION = '0.1.0';
14  
15 Readonly::Scalar my $METACPAN_API => 'https://fastapi.metacpan.org/v1';
16  
17 =head1 NAME
18  
19 Test::CPAN::Health::Distribution - Represents a CPAN distribution under analysis
20  
21 =head1 SYNOPSIS
22  
23 use Test::CPAN::Health::Distribution;
24  
25 # From a local unpacked path
26 my $dist = Test::CPAN::Health::Distribution->new(path => '/tmp/LWP-UserAgent-6.77');
27  
28 # From a CPAN distribution name (downloads and unpacks)
29 my $dist = Test::CPAN::Health::Distribution->from_cpan('LWP-UserAgent');
30  
31 # From a module name (resolves dist via MetaCPAN, then downloads)
32 my $dist = Test::CPAN::Health::Distribution->from_module('LWP::UserAgent');
33  
34 printf "%s %s by %s\n", $dist->name, $dist->version, $dist->author;
35 my @pm_files = @{ $dist->pm_files };
36  
37 =head1 DESCRIPTION
38  
39 Abstracts the distribution being analysed. All checks receive a
40 Distribution object, which provides uniform access to the filesystem,
41 metadata, and derived file lists regardless of whether the distribution
42 came from a local path or was downloaded from CPAN.
43  
44 All file-list methods return absolute paths.
45  
46 =head1 LIMITATIONS
47  
48 =over 4
49  
50 =item * C<from_cpan> and C<from_module> require network access and
51 C<Archive::Tar> to unpack tarballs. The download is cached in a
52 temporary directory that is cleaned up at object destruction.
53  
54 =item * C<meta> searches in order: META.json, META.yml, MYMETA.json, MYMETA.yml.
55 MYMETA files are generated by C<perl Makefile.PL> and serve as a fallback
56 for local checkouts. Canonical META files are produced by C<make distdir>
57 (MakeMaker) or C<dzil build> (Dist::Zilla) and must be committed separately.
58 Returns C<undef> only when none of these files are present.
59  
60 =item * C<file_path> does not sanitise C<@parts> for path-traversal sequences
61 (e.g. C<../>). It is the caller's responsibility to supply trusted path
62 components. Do not pass user-supplied strings to C<file_path> without prior
63 validation.
64  
65 =item * C<all_source_files> returns the union of C<pm_files> and C<pl_files>
66 at the time of the first call; the result is cached. Files added to the
67 distribution tree afterwards are not visible.
68  
69 =back
70  
71 =cut
72  
73 sub new {
74 my ($class, %args) = @_;
75  
76 %args = %{ validate_strict(
77 schema => {
78 path => { type => 'string', min => 1 },
79 },
80 input => \%args,
81 ) };
82  
83 croak "Distribution path '$args{path}' does not exist"
84 unless -d $args{path};
85  
86 my $self = bless {
87 _path => File::Spec->rel2abs($args{path}),
88 _meta => undef,
89 _pm_files => undef,
90 _t_files => undef,
91 _pl_files => undef,
92 _all_source_files => undef, # cached union of pm_files and pl_files
93 _name => undef,
94 _version_loaded => 0, # true once version() has been computed
95 _version => undef,
96 _author_loaded => 0, # true once author() has been computed
97 _author => undef,
98 _tmp_dir => undef, # set by factory methods; owned for cleanup
99 }, $class;
100  
101 return $self;
102 }
103  
104 =head2 from_cpan
105  
106 =head3 PURPOSE
107  
108 Factory method: resolve a CPAN distribution name to the latest release,
109 download the tarball via MetaCPAN, unpack it to a temp directory, and
110 return a Distribution instance pointing at the unpacked tree.
111  
112 =head3 API SPECIFICATION
113  
114 =head4 INPUT
115  
116 dist_name Scalar required e.g. 'LWP-UserAgent'
117  
118 =head4 OUTPUT
119  
120 L<Test::CPAN::Health::Distribution> object.
121  
122 =head3 MESSAGES
123  
124 Code | Severity | Message | Resolution
125 ------+----------+------------------------------------+---------------------
126 DST01 | FATAL | Cannot resolve dist from MetaCPAN | Check dist name and network
127 DST02 | FATAL | Download failed | Check CPAN mirror availability
128 DST03 | FATAL | Unpack failed | Check Archive::Tar installation
129  
130 =head3 FORMAL SPECIFICATION
131  
132 -- Z schema (placeholder) --
133 FromCpanOp
134 dist_name? : String
135 dist! : Distribution
136 -------------------------------------------------------
137 dist_name? /= ""
138 dist!.name = resolve(dist_name?)
139 exists(dist!.path) /\ is_dir(dist!.path)
140  
141 =head3 SIDE EFFECTS
142  
143 Downloads a tarball from CPAN. Creates and owns a temporary directory
144 that is removed when the returned object is destroyed.
145  
146 =head3 USAGE EXAMPLE
147  
148 my $dist = Test::CPAN::Health::Distribution->from_cpan('LWP-UserAgent');
149  
150 =cut
151  
152 sub from_cpan {
153 my ($class, $dist_name) = @_;
154  
155 croak 'dist_name is required' unless defined $dist_name && length $dist_name;
156  
157 # Strategy:
158 # 1. Hit MetaCPAN /release/{dist_name} to get download_url and author.
159 # 2. Fetch the tarball with HTTP::Tiny.
160 # 3. Unpack with Archive::Tar into a File::Temp::tempdir.
161 # 4. Construct and return a Distribution with _tmp_dir set for cleanup.
162  
163 require HTTP::Tiny;
164 require JSON::MaybeXS;
165 require Archive::Tar;
166 require File::Temp;
167  
168 my $ua = HTTP::Tiny->new(timeout => 30);
169 my $url = "$METACPAN_API/release/$dist_name";
170 my $res = $ua->get($url);
171  
172 croak "Cannot resolve '$dist_name' from MetaCPAN (HTTP $res->{status})"
173 unless $res->{success};
174  
175 my $data = JSON::MaybeXS::decode_json($res->{content});
176 my $download_url = $data->{download_url}
177 or croak "MetaCPAN returned no download_url for '$dist_name'";
178  
179 my $tarball_res = $ua->get($download_url);
180 croak "Download failed for '$download_url' (HTTP $tarball_res->{status})"
181 unless $tarball_res->{success};
182  
183 my $tmp_dir = File::Temp::tempdir(CLEANUP => 0); # we manage cleanup
184  
185 my $tar = Archive::Tar->new;
186 $tar->read(\$tarball_res->{content}, 1); # 1 = compressed
187 $tar->extract_archive($tmp_dir)
188 or croak "Unpack failed: " . Archive::Tar->error;
189  
190 # The tarball unpacks to a single top-level directory (Dist-Name-X.Y).
191 my ($unpack_dir) = glob "$tmp_dir/*";
192 croak "Unexpected tarball structure in '$tmp_dir'" unless defined $unpack_dir && -d $unpack_dir;
193  
194 my $self = $class->new(path => $unpack_dir);
195 $self->{_tmp_dir} = $tmp_dir;
196  
197 return $self;
198 }
199  
200 =head2 from_module
201  
202 =head3 PURPOSE
203  
204 Factory method: resolve a module name (C<Foo::Bar>) to its containing
205 distribution via MetaCPAN, then delegate to C<from_cpan>.
206  
207 =head3 API SPECIFICATION
208  
209 =head4 INPUT
210  
211 module_name Scalar required e.g. 'LWP::UserAgent'
212  
213 =head4 OUTPUT
214  
215 L<Test::CPAN::Health::Distribution> object.
216  
217 =head3 MESSAGES
218  
219 Code | Severity | Message | Resolution
220 ------+----------+------------------------------------+---------------------
221 DST04 | FATAL | Cannot resolve module from MetaCPAN | Check module name and network
222  
223 =head3 FORMAL SPECIFICATION
224  
225 -- Z schema (placeholder) --
226 FromModuleOp
227 module_name? : String
228 dist_name! : String
229 -------------------------------------------------------
230 dist_name! = metacpan_resolve(module_name?)
231  
232 =head3 SIDE EFFECTS
233  
234 As C<from_cpan>.
235  
236 =head3 USAGE EXAMPLE
237  
238 my $dist = Test::CPAN::Health::Distribution->from_module('LWP::UserAgent');
239  
240 =cut
241  
242 sub from_module {
243 my ($class, $module_name) = @_;
244  
245 croak 'module_name is required' unless defined $module_name && length $module_name;
246  
247 require HTTP::Tiny;
248 require JSON::MaybeXS;
249  
250 my $ua = HTTP::Tiny->new(timeout => 30);
251 my $url = "$METACPAN_API/module/$module_name";
252 my $res = $ua->get($url);
253  
254 croak "Cannot resolve module '$module_name' from MetaCPAN (HTTP $res->{status})"
255 unless $res->{success};
256  
257 my $data = JSON::MaybeXS::decode_json($res->{content});
258 my $dist_name = $data->{distribution}
259 or croak "MetaCPAN returned no distribution for module '$module_name'";
260  
261 return $class->from_cpan($dist_name);
262 }
263  
264 # ---------------------------------------------------------------------------
265 # Accessors -- all lazy, computed once and cached
266 # ---------------------------------------------------------------------------
267  
268 =head2 path
269  
270 =head3 PURPOSE
271  
272 Returns the absolute filesystem path to the root of the unpacked distribution.
273  
274 =head3 API SPECIFICATION
275  
276 =head4 INPUT
277  
278 None.
279  
280 =head4 OUTPUT
281  
282 Absolute scalar path string.
283  
284 =head3 MESSAGES
285  
286 Code | Severity | Message | Resolution
287 ------+----------+------------------------------------+---------------------
288 | | |
289  
290 =head3 FORMAL SPECIFICATION
291  
292 -- Z schema (placeholder) --
293 path : String
294 -------------------------------------------------------
295 is_absolute(path) /\ is_dir(path)
296  
297 =head3 SIDE EFFECTS
298  
299 None.
300  
301 =head3 USAGE EXAMPLE
302  
303 print $dist->path;
304  
305 =cut
306  
307 sub path { my ($self) = @_; return $self->{_path} }
308  
309 =head2 meta
310  
311 =head3 PURPOSE
312  
313 Returns a L<CPAN::Meta> object parsed from the best available META file.
314 The search order is: META.json, META.yml, MYMETA.json, MYMETA.yml.
315 META files are authoritative (shipped with the dist); MYMETA files are
316 generated by C<perl Makefile.PL> and used as a fallback for local
317 checkouts where C<perl Makefile.PL> has been run but no canonical META
318 file has been committed. Returns C<undef> if no
319 META file of any kind is found.
320  
321 =head3 API SPECIFICATION
322  
323 =head4 INPUT
324  
325 None.
326  
327 =head4 OUTPUT
328  
329 L<CPAN::Meta> object or C<undef>.
330  
331 =head3 MESSAGES
332  
333 Code | Severity | Message | Resolution
334 ------+----------+--------------------------------------+---------------------
335 DST05 | WARNING | Cannot parse <file>: <reason> | Fix or regenerate the META file
336  
337 =head3 FORMAL SPECIFICATION
338  
339 -- Z schema (placeholder) --
340 meta : CPAN::Meta | undefined
341  
342 =head3 SIDE EFFECTS
343  
344 None (reads META file on first call, caches result).
345  
346 =head3 USAGE EXAMPLE
347  
348 my $meta = $dist->meta or warn "No META file";
349 print $meta->name;
350  
351 =cut
352  
353 sub meta {
354 my ($self) = @_;
355  
356 return $self->{_meta} if defined $self->{_meta};
357  
358 require CPAN::Meta;
359  
360 for my $basename (qw(META.json META.yml MYMETA.json MYMETA.yml)) {
361 my $file = File::Spec->catfile($self->{_path}, $basename);
362 next unless -f $file;
363 eval { $self->{_meta} = CPAN::Meta->load_file($file); 1 }
364 or carp "Cannot parse $basename: $@";
365 last if $self->{_meta};
366 }
367  
368 return $self->{_meta};
369 }
370  
371 =head2 name
372  
373 Returns the distribution name from META (e.g. C<LWP-UserAgent>), or a
374 best-guess derived from the path basename if META is absent.
375  
376 =cut
377  
378 sub name {
379 my ($self) = @_;
380  
381 unless (defined $self->{_name}) {
382 my $meta = $self->meta;
383 my $meta_name = $meta ? $meta->name : undef;
384 $self->{_name} = (defined $meta_name && length $meta_name) ? $meta_name : do {
385 my $base = (File::Spec->splitpath($self->{_path}))[2];
386 $base =~ s/ - [0-9] [0-9._]* $ //x;
387 $base;
388 };
389 }
390  
391 return $self->{_name};
392 }
393  
394 =head2 version
395  
396 Returns the distribution version string from META, or C<undef> if not
397 determinable. The result is cached after the first call; a dist whose
398 META lacks a version field always returns C<undef> without re-parsing.
399  
400 =cut
401  
402 sub version {
403 my ($self) = @_;
404  
405 # Use a loaded-flag rather than defined() so that undef (a legitimate
406 # result when META has no version) is itself cached and not recomputed.
407 unless ($self->{_version_loaded}) {
408 my $meta = $self->meta;
409 $self->{_version} = $meta ? $meta->version : undef;
410 $self->{_version_loaded} = 1;
411 }
412  
413 return $self->{_version};
414 }
415  
416 =head2 author
417  
418 Returns the first author string from META, or C<undef>. Cached after
419 the first call.
420  
421 =cut
422  
423 sub author {
424 my ($self) = @_;
425  
426 # Loaded-flag pattern for the same reason as version() above.
427 unless ($self->{_author_loaded}) {
428 my $meta = $self->meta;
429 if ($meta) {
430 my @authors = $meta->author;
431 $self->{_author} = $authors[0];
432 }
433 $self->{_author_loaded} = 1;
434 }
435  
436 return $self->{_author};
437 }
438  
439 =head2 pm_files
440  
441 Returns an arrayref of absolute paths to all C<.pm> files under C<lib/>.
442  
443 =cut
444  
445 sub pm_files {
446 my ($self) = @_;
447  
448 $self->{_pm_files} //= [
449 File::Find::Rule->file->name('*.pm')
450 ->in(File::Spec->catdir($self->{_path}, 'lib'))
451 ];
452  
453 return $self->{_pm_files};
454 }
455  
456 =head2 t_files
457  
458 Returns an arrayref of absolute paths to all C<.t> files under C<t/>.
459  
460 =cut
461  
462 sub t_files {
463 my ($self) = @_;
464  
465 $self->{_t_files} //= [
466 File::Find::Rule->file->name('*.t')
467 ->in(File::Spec->catdir($self->{_path}, 't'))
468 ];
469  
470 return $self->{_t_files};
471 }
472  
473 =head2 pl_files
474  
475 Returns an arrayref of absolute paths to all C<.pl> files and files under C<bin/> or C<script/>.
476  
477 =cut
478  
479 sub pl_files {
480 my ($self) = @_;
481  
482 unless (defined $self->{_pl_files}) {
483 my @files = File::Find::Rule->file->name('*.pl')->in($self->{_path});
484 for my $dir (qw(bin script)) {
485 my $full = File::Spec->catdir($self->{_path}, $dir);
486 push @files, File::Find::Rule->file->in($full) if -d $full;
487 }
488 $self->{_pl_files} = \@files;
489 }
490  
491 return $self->{_pl_files};
492 }
493  
494 =head2 all_source_files
495  
496 Convenience: returns the union of C<pm_files> and C<pl_files> as a single
497 arrayref. The result is cached after the first call.
498  
499 =cut
500  
501 sub all_source_files {
502 my ($self) = @_;
503  
504 # Cache the union to avoid rescanning directories on repeated calls.
505 $self->{_all_source_files} //= [ @{$self->pm_files}, @{$self->pl_files} ];
506  
507 return $self->{_all_source_files};
508 }
509  
510 =head2 has_dir
511  
512 Returns true if the given subdirectory exists within the distribution root.
513 Accepts a single directory name or a list of alternatives.
514  
515 =cut
516  
517 sub has_dir {
518 my ($self, @names) = @_;
519  
520 for my $name (@names) {
521 return 1 if -d File::Spec->catdir($self->{_path}, $name);
522 }
523  
524 return 0;
525 }
526  
527 =head2 file_path
528  
529 Returns the absolute path to a named file within the distribution root, or
530 C<undef> if it does not exist.
531  
532 =cut
533  
534 sub file_path {
535 my ($self, @parts) = @_;
536  
537 my $abs = File::Spec->catfile($self->{_path}, @parts);
538  
539 return -e $abs ? $abs : undef;
540 }
541  
542 sub DESTROY {
543 my ($self) = @_;
544  
545 # Clean up temp directories created by factory methods.
546 if (defined $self->{_tmp_dir} && -d $self->{_tmp_dir}) {
547 require File::Path;
548 File::Path::remove_tree($self->{_tmp_dir});
549 }
550  
551 return;
552 }
553  
554 =head1 AUTHOR
555  
556 Nigel Horne, C<< <njh at nigelhorne.com> >>
557  
558 =head1 LICENSE AND COPYRIGHT
559  
560 Copyright (C) 2025-2026 Nigel Horne.
561  
562 This program is free software; you can redistribute it and/or modify it
563 under the terms of the GNU General Public License as published by the Free
564 Software Foundation; either version 2 of the License, or (at your option)
565 any later version.
566  
567 =cut
568  
569 1;
« blib/lib/Test/CPAN/Health/Config.pm ↑ Summary blib/lib/Test/CPAN/Health/Report.pm »