blib/lib/Test/CPAN/Health.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
↑ Summary blib/lib/Test/CPAN/Health/Cache.pm »
1 package Test::CPAN::Health;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 use Carp qw(croak carp);
8 use Object::Configure;
9 use Readonly;
10 use Params::Get;
11 use Params::Validate::Strict qw(validate_strict);
12 use Scalar::Util qw(blessed);
13  
14 our $VERSION = '0.1.0';
15  
16 Readonly::Hash my %DEFAULTS => (
17 format => 'terminal',
18 no_network => 0,
19 no_cover => 0,
20 severity => 3,
21 min_score => 0,
22 );
23  
24 # Canonical ordered list of checks. The Runner loads these in sequence;
25 # later checks may use metadata produced by earlier ones (e.g. ReverseDeps
26 # count is passed as context to SecurityAdvisories to scale its weight).
27 Readonly::Array my @DEFAULT_CHECKS => qw(
28 Test::CPAN::Health::Check::SemVer
29 Test::CPAN::Health::Check::MetaJSON
30 Test::CPAN::Health::Check::Changelog
31 Test::CPAN::Health::Check::DeclaredDeps
32 Test::CPAN::Health::Check::License
33 Test::CPAN::Health::Check::MinPerl
34 Test::CPAN::Health::Check::PODCoverage
35 Test::CPAN::Health::Check::DocQuality
36 Test::CPAN::Health::Check::Examples
37 Test::CPAN::Health::Check::Benchmarks
38 Test::CPAN::Health::Check::Perlcritic
39 Test::CPAN::Health::Check::Complexity
40 Test::CPAN::Health::Check::DuplicateCode
41 Test::CPAN::Health::Check::Deprecations
42 Test::CPAN::Health::Check::TestCoverage
43 Test::CPAN::Health::Check::Kwalitee
44 Test::CPAN::Health::Check::CIConfig
45 Test::CPAN::Health::Check::StaleDeps
46 Test::CPAN::Health::Check::AbandonedDeps
47 Test::CPAN::Health::Check::SecurityAdvisories
48 Test::CPAN::Health::Check::CPANTesters
49 Test::CPAN::Health::Check::ReverseDeps
50 Test::CPAN::Health::Check::VersionSync
51 Test::CPAN::Health::Check::ReadmeSync
52 );
53  
54 Readonly::Hash my %VALID_FORMATS => map { $_ => 1 } qw(terminal json html tap markdown);
55  
56 # Maps the short check id (as returned by ->id) to the full class name.
57 # Used to normalise --check and --skip CLI arguments that use short ids.
58 Readonly::Hash my %CHECK_CLASS_FOR => (
59 sem_ver => 'Test::CPAN::Health::Check::SemVer',
60 meta_json => 'Test::CPAN::Health::Check::MetaJSON',
61 changelog => 'Test::CPAN::Health::Check::Changelog',
62 declared_deps => 'Test::CPAN::Health::Check::DeclaredDeps',
63 license => 'Test::CPAN::Health::Check::License',
64 min_perl => 'Test::CPAN::Health::Check::MinPerl',
65 pod_coverage => 'Test::CPAN::Health::Check::PODCoverage',
66 doc_quality => 'Test::CPAN::Health::Check::DocQuality',
67 examples => 'Test::CPAN::Health::Check::Examples',
68 benchmarks => 'Test::CPAN::Health::Check::Benchmarks',
69 perlcritic => 'Test::CPAN::Health::Check::Perlcritic',
70 complexity => 'Test::CPAN::Health::Check::Complexity',
71 duplicate_code => 'Test::CPAN::Health::Check::DuplicateCode',
72 deprecations => 'Test::CPAN::Health::Check::Deprecations',
73 test_coverage => 'Test::CPAN::Health::Check::TestCoverage',
74 kwalitee => 'Test::CPAN::Health::Check::Kwalitee',
75 ci_config => 'Test::CPAN::Health::Check::CIConfig',
76 stale_deps => 'Test::CPAN::Health::Check::StaleDeps',
77 abandoned_deps => 'Test::CPAN::Health::Check::AbandonedDeps',
78 security_advisories => 'Test::CPAN::Health::Check::SecurityAdvisories',
79 cpan_testers => 'Test::CPAN::Health::Check::CPANTesters',
80 reverse_deps => 'Test::CPAN::Health::Check::ReverseDeps',
81 version_sync => 'Test::CPAN::Health::Check::VersionSync',
82 readme_sync => 'Test::CPAN::Health::Check::ReadmeSync',
83 );
84  
85 =head1 NAME
86  
87 Test::CPAN::Health - Analyse a CPAN distribution and produce a comprehensive health report
88  
89 =head1 VERSION
90  
91 Version 0.1.0
92  
93 =head1 SYNOPSIS
94  
95 B<Command-line (the usual entry point):>
96  
97 # Analyse the current directory
98 cpan-health .
99  
100 # Analyse by CPAN dist name (downloads and unpacks automatically)
101 cpan-health LWP-UserAgent
102  
103 # Analyse by module name
104 cpan-health LWP::UserAgent
105  
106 # JSON output -- useful for editor or CI integration
107 cpan-health --format=json My-Dist
108  
109 # Fail the build if the health score falls below 80
110 cpan-health --min-score=80 --no-cover My-Dist
111  
112 # Skip slow or network-dependent checks
113 cpan-health --no-network --no-cover .
114  
115 # Run only the security and versioning checks
116 cpan-health --check=security_advisories,sem_ver My-Dist
117  
118 # Skip specific checks by id
119 cpan-health --skip=cpan_testers,kwalitee .
120  
121 # TAP output -- pipe into any test harness
122 cpan-health --format=tap My-Dist | prove --stdin
123  
124 # Write the report to a file
125 cpan-health --format=json --output=report.json LWP-UserAgent
126  
127 # Show all available options
128 cpan-health --help
129  
130 B<Perl API (for programmatic use):>
131  
132 use Test::CPAN::Health;
133  
134 # Analyse a local unpacked distribution
135 my $health = Test::CPAN::Health->new(path => '/path/to/My-Dist-1.00');
136 my $report = $health->analyse;
137 $health->report_to($report);
138  
139 # Analyse a distribution by CPAN dist name
140 my $health = Test::CPAN::Health->new(
141 dist => 'LWP-UserAgent',
142 format => 'json',
143 min_score => 80,
144 );
145 my $report = $health->analyse;
146 exit 1 if $report->overall_score < 80;
147  
148 # Analyse by module name, skipping network-dependent checks
149 my $health = Test::CPAN::Health->new(
150 module => 'LWP::UserAgent',
151 no_network => 1,
152 skip => ['Test::CPAN::Health::Check::CPANTesters'],
153 );
154  
155 =head1 DESCRIPTION
156  
157 Test::CPAN::Health is a comprehensive distribution health checker for CPAN
158 modules -- analogous to C<cargo audit> + C<npm audit> + C<go vet> +
159 C<perlcritic> + C<cpants>, all unified into a single scored report.
160  
161 It accepts a distribution as a local path, a CPAN distribution name, or a
162 module name. It runs a configurable battery of checks (POD coverage, CPAN
163 Testers pass rate, kwalitee, CI configuration, META validity, SPDX license,
164 stale and abandoned dependencies, known CVEs, reverse dependency count,
165 documentation quality, examples, benchmarks, semantic versioning, perlcritic
166 violations, code complexity, duplicate code, test coverage, minimum Perl
167 version, and deprecation warnings) and returns a weighted score out of 100.
168  
169 The report can be rendered as coloured terminal output, JSON, HTML, or TAP
170 (allowing cpan-health to run inside a standard test harness).
171  
172 =head1 LIMITATIONS
173  
174 =over 4
175  
176 =item * The C<TestCoverage> check requires C<Devel::Cover> and must run the
177 distribution's own test suite, which is slow and may have side effects.
178  
179 =item * Network-dependent checks (CPANTesters, StaleDeps, AbandonedDeps,
180 SecurityAdvisories, ReverseDeps) require internet access and are subject to
181 upstream API availability and rate limits.
182  
183 =item * The C<DuplicateCode> check uses a token-fingerprint algorithm via
184 C<PPI> and may produce false positives on generated or data-heavy code.
185  
186 =back
187  
188 =cut
189  
190 sub new {
191 my ($class, @args) = @_;
192 my $args = validate_strict(
193 schema => {
194 distribution => { type => 'object', isa => 'Test::CPAN::Health::Distribution', optional => 1 },
195 path => { type => 'string', optional => 1 },
196 module => { type => 'string', optional => 1 },
197 dist => { type => 'string', optional => 1 },
198 format => { type => 'string', optional => 1 },
199 checks => { type => 'arrayref', optional => 1 },
200 skip => { type => 'arrayref', optional => 1 },
201 no_network => { type => 'scalar', optional => 1 },
202 no_cover => { type => 'scalar', optional => 1 },
203 severity => { type => 'integer', min => 1, max => 5, optional => 1 },
204 min_score => { type => 'integer', min => 0, max => 100, optional => 1 },
205 cache_dir => { type => 'string', optional => 1 },
206 ignore_abandoned => { type => 'arrayref', optional => 1 },
207 },
208 input => Params::Get::get_params(undef, \@args) || {}
209 );
210  
211 croak 'One of path, module, dist, or distribution is required'
212 unless $args && ($args->{path} || $args->{module} || $args->{dist} || $args->{distribution});
213  
214 my $format = lc($args->{format} // $DEFAULTS{format});
215 croak "Unknown format '$format'; expected one of: " . join(', ', sort keys %VALID_FORMATS)
216 unless $VALID_FORMATS{$format};
217  
218 $args = Object::Configure::configure($class, $args);
219  
220 return bless {
221 _distribution => $args->{distribution},
222 _runner => undef,
223 _reporter => undef,
224 _cache => undef,
225 _format => $format,
226 _no_network => $args->{no_network} // $DEFAULTS{no_network},
227 _no_cover => $args->{no_cover} // $DEFAULTS{no_cover},
228 _severity => $args->{severity} // $DEFAULTS{severity},
229 _min_score => $args->{min_score} // $DEFAULTS{min_score},
230 _cache_dir => $args->{cache_dir},
231 _checks => [ map { $CHECK_CLASS_FOR{$_} // $_ }
232 @{ $args->{checks} // [@DEFAULT_CHECKS] } ],
233 _skip => { map { ($CHECK_CLASS_FOR{$_} // $_) => 1 }
234 @{ $args->{skip} // [] } },
235 _path => $args->{path},
236 _module => $args->{module},
237 _dist => $args->{dist},
238 _ignore_abandoned => $args->{ignore_abandoned} // [],
239 }, $class;
240 }
241  
242 =head2 analyse
243  
244 Runs all configured checks against the distribution and returns a Report.
245  
246 All components (Distribution, Cache, Runner, Reporter) are initialised
247 lazily on the first call so that construction is always cheap.
248  
249 =head3 API SPECIFICATION
250  
251 =head4 INPUT
252  
253 No arguments. Configuration comes from the constructor.
254  
255 =head4 OUTPUT
256  
257 Returns a L<Test::CPAN::Health::Report> object.
258  
259 =head3 MESSAGES
260  
261 Code | Severity | Message | Resolution
262 ------+----------+------------------------------------+---------------------
263 | | |
264  
265 =head3 FORMAL SPECIFICATION
266  
267 -- Z schema (placeholder) --
268 AnalyseOp
269 Test::CPAN::Health
270 Report'
271 -------------------------------------------------------
272 distribution /= undefined
273 Report' = Runner.run(distribution)
274 overall_score(Report') in 0..100
275  
276 =head3 SIDE EFFECTS
277  
278 May download the distribution from CPAN, run its test suite (if
279 C<TestCoverage> is enabled), and write to the local HTTP cache.
280  
281 =head3 USAGE EXAMPLE
282  
283 my $report = $health->analyse;
284 print 'Score: ', $report->overall_score, "\n";
285  
286 =cut
287  
288 sub analyse {
289 my ($self) = @_;
290  
291 $self->_init_distribution unless $self->{_distribution};
292 $self->_init_cache unless $self->{_cache};
293 $self->_init_runner unless $self->{_runner};
294 $self->_init_reporter unless $self->{_reporter};
295  
296 return $self->{_runner}->run($self->{_distribution});
297 }
298  
299 =head2 list_checks
300  
301 =head3 PURPOSE
302  
303 Return a list of all default check metadata (id, name, weight, category,
304 description) without running any check. Suitable for C<--list-checks> output.
305  
306 =head3 API SPECIFICATION
307  
308 =head4 INPUT
309  
310 None (class method).
311  
312 =head4 OUTPUT
313  
314 Arrayref of hashrefs; each has keys C<id>, C<name>, C<weight>, C<category>,
315 C<description>. Ordered as they would execute.
316  
317 =head3 MESSAGES
318  
319 Code | Severity | Message | Resolution
320 ------+----------+-------------------------------------+---------------------
321 | | |
322  
323 =head3 FORMAL SPECIFICATION
324  
325 Post: result is an arrayref of length = #DEFAULT_CHECKS (skipping unloadable)
326  
327 =head3 SIDE EFFECTS
328  
329 Requires each check class (lazy load).
330  
331 =head3 USAGE EXAMPLE
332  
333 my @checks = @{ Test::CPAN::Health->list_checks };
334 printf "%-20s %s\n", $_->{id}, $_->{name} for @checks;
335  
336 =cut
337  
338 sub list_checks {
339 my @result;
340 for my $class (@DEFAULT_CHECKS) {
341 my $ok = eval {
342 (my $file = "$class.pm") =~ s{ :: }{/}gx;
343 require $file;
344 1;
345 };
346 next unless $ok;
347 my $obj = $class->new;
348 push @result, {
349 id => $obj->id,
350 name => $obj->name,
351 weight => $obj->weight,
352 category => $obj->category,
353 description => $obj->description,
354 };
355 }
356 return \@result;
357 }
358  
359 =head2 report_to
360  
361 Render a Report to the configured output format and return the result
362 as a string. Printing to STDOUT (for terminal/TAP formats) is the
363 responsibility of the caller or the CLI script.
364  
365 =head3 API SPECIFICATION
366  
367 =head4 INPUT
368  
369 report Test::CPAN::Health::Report required
370  
371 =head4 OUTPUT
372  
373 Scalar string containing the rendered report.
374  
375 =head3 MESSAGES
376  
377 Code | Severity | Message | Resolution
378 ------+----------+------------------------------------+---------------------
379 | | |
380  
381 =head3 FORMAL SPECIFICATION
382  
383 -- Z schema (placeholder) --
384 RenderOp
385 reporter : Reporter
386 report : Report
387 output : String
388 -------------------------------------------------------
389 output = reporter.render(report)
390  
391 =head3 SIDE EFFECTS
392  
393 None beyond invoking the reporter.
394  
395 =head3 USAGE EXAMPLE
396  
397 my $text = $health->report_to($report);
398 print $text;
399  
400 =cut
401  
402 sub report_to {
403 my ($self, $report) = @_;
404  
405 croak 'report must be a Test::CPAN::Health::Report'
406 unless blessed($report) && $report->isa('Test::CPAN::Health::Report');
407  
408 $self->_init_reporter unless $self->{_reporter};
409  
410 return $self->{_reporter}->render($report);
411 }
412  
413 # Read-only accessors
414  
415 sub distribution { my ($self) = @_; return $self->{_distribution} }
416 sub runner { my ($self) = @_; return $self->{_runner} }
417 sub reporter { my ($self) = @_; return $self->{_reporter} }
418 sub cache { my ($self) = @_; return $self->{_cache} }
419 sub output_format { my ($self) = @_; return $self->{_format} }
420 sub min_score { my ($self) = @_; return $self->{_min_score} }
421  
422 # ---------------------------------------------------------------------------
423 # Private initialisation helpers
424 # Each is idempotent: call as many times as needed, only runs once.
425 # ---------------------------------------------------------------------------
426  
427 sub _init_distribution {
428 my $self = $_[0];
429  
430 require Test::CPAN::Health::Distribution;
431  
432 if ($self->{_path}) {
433 $self->{_distribution} = Test::CPAN::Health::Distribution->new(
434 path => $self->{_path},
435 );
436 } elsif ($self->{_dist}) {
437 $self->{_distribution} = Test::CPAN::Health::Distribution->from_cpan(
438 $self->{_dist},
439 );
440 } elsif ($self->{_module}) {
441 $self->{_distribution} = Test::CPAN::Health::Distribution->from_module(
442 $self->{_module},
443 );
444 }
445  
446 return $self;
447 }
448  
449 sub _init_cache {
450 my $self = $_[0];
451  
452 require Test::CPAN::Health::Cache;
453  
454 $self->{_cache} = Test::CPAN::Health::Cache->new(
455 $self->{_cache_dir} ? (cache_dir => $self->{_cache_dir}) : (),
456 );
457  
458 return $self;
459 }
460  
461 sub _init_runner {
462 my $self = $_[0];
463  
464 require Test::CPAN::Health::Runner;
465  
466 my @checks;
467 for my $check_class (@{$self->{_checks}}) {
468 next if $self->{_skip}{$check_class};
469  
470 # Defer require so a missing optional check module does not abort
471 # the whole run -- emit a warning and continue instead.
472 my $ok = eval {
473 (my $file = "$check_class.pm") =~ s{ :: }{/}gx;
474 require $file;
475 1;
476 };
477 if (!$ok) {
478 carp "Skipping check $check_class (cannot load): $@";
479 next;
480 }
481  
482 my %extra;
483 if ($check_class eq 'Test::CPAN::Health::Check::AbandonedDeps'
484 && @{ $self->{_ignore_abandoned} }) {
485 $extra{ignore} = $self->{_ignore_abandoned};
486 }
487  
488 push @checks, $check_class->new(
489 severity => $self->{_severity},
490 no_network => $self->{_no_network},
491 no_cover => $self->{_no_cover},
492 %extra,
493 );
494 }
495  
496 $self->{_runner} = Test::CPAN::Health::Runner->new(
497 checks => \@checks,
498 cache => $self->{_cache},
499 );
500  
501 return $self;
502 }
503  
504 sub _init_reporter {
505 my $self = $_[0];
506  
507 Readonly::Hash my %REPORTER_MAP => (
508 terminal => 'Test::CPAN::Health::Reporter::Terminal',
509 json => 'Test::CPAN::Health::Reporter::JSON',
510 html => 'Test::CPAN::Health::Reporter::HTML',
511 tap => 'Test::CPAN::Health::Reporter::TAP',
512 markdown => 'Test::CPAN::Health::Reporter::Markdown',
513 );
514  
515 my $reporter_class = $REPORTER_MAP{ $self->{_format} }
516 or croak "No reporter for format '$self->{_format}'";
517  
518 eval { (my $file = "$reporter_class.pm") =~ s{ :: }{/}gx; require $file; 1 }
519 or croak "Cannot load reporter $reporter_class: $@";
520  
521 $self->{_reporter} = $reporter_class->new();
522  
523 return $self;
524 }
525  
526 =head1 AUTHOR
527  
528 Nigel Horne, C<< <njh at nigelhorne.com> >>
529  
530 =head1 LICENSE AND COPYRIGHT
531  
532 Copyright (C) 2026 Nigel Horne.
533  
534 Usage is subject to the GPL2 licence terms.
535 If you use it,
536 please let me know.
537  
538 =cut
539  
540 1;
↑ Summary blib/lib/Test/CPAN/Health/Cache.pm »