blib/lib/Test/CPAN/Health/Check/DuplicateCode.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/Check/DocQuality.pm ↑ Summary blib/lib/Test/CPAN/Health/Check/Examples.pm »
1 package Test::CPAN::Health::Check::DuplicateCode;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 use Carp qw(croak carp);
8 use File::Spec;
9 use Readonly;
10 use Params::Validate::Strict qw(validate_strict);
11  
12 use parent 'Test::CPAN::Health::Check';
13  
14 our $VERSION = '0.1.0';
15  
16 # Minimum consecutive code lines that form a "chunk" worth tracking.
17 # Smaller values produce many false positives (e.g. matching "use strict").
18 Readonly::Scalar my $CHUNK_SIZE => 6;
19  
20 # Score thresholds.
21 Readonly::Scalar my $SCORE_PASS => 90;
22 Readonly::Scalar my $SCORE_WARN => 50;
23  
24 =head1 NAME
25  
26 Test::CPAN::Health::Check::DuplicateCode - Detect copy-paste code blocks across source files
27  
28 =head1 SYNOPSIS
29  
30 use Test::CPAN::Health::Check::DuplicateCode;
31  
32 my $check = Test::CPAN::Health::Check::DuplicateCode->new;
33 my $result = $check->run($dist);
34  
35 printf "%s: %s\n", $result->status, $result->summary;
36  
37 =head1 DESCRIPTION
38  
39 Implements a lightweight, dependency-free clone detector using a sliding-window
40 hash approach:
41  
42 =over 4
43  
44 =item 1.
45  
46 Each source file is reduced to a sequence of I<code lines>: lines that are
47 not blank, not pure comments, and not POD. Each line is whitespace-normalised
48 (leading/trailing whitespace stripped; runs of whitespace collapsed to a single
49 space).
50  
51 =item 2.
52  
53 A sliding window of C<6> consecutive normalised lines forms a "chunk". The
54 hash (MD5-free: joined as a string) of each chunk is recorded along with the
55 originating file.
56  
57 =item 3.
58  
59 Chunks whose hash appears in more than one distinct file are cross-file
60 duplicates.
61  
62 =back
63  
64 Score = round((1 - dup_chunks / total_chunks) * 100) when total_chunks > 0,
65 else 100. Status: pass E<ge> 90, warn E<ge> 50, fail below 50.
66  
67 =head1 LIMITATIONS
68  
69 =over 4
70  
71 =item * Whitespace normalisation is basic: it does not account for string
72 literals or heredocs that span multiple lines.
73  
74 =item * The detector only finds B<cross-file> duplicates; intra-file
75 repetition is not flagged.
76  
77 =item * Short common boilerplate (e.g. C<use strict; use warnings; 1;>) is
78 naturally filtered out because consecutive boilerplate lines rarely reach the
79 minimum chunk size of 6 in the same relative order.
80  
81 =back
82  
83 =cut
84  
85 sub id { return 'duplicate_code' }
86 sub name { return 'Duplicate Code' }
87 sub description { return 'Detects copy-paste code blocks across source files' }
88 sub weight { return 3 }
89 sub category { return 'quality' }
90  
91 =head2 run
92  
93 =head3 PURPOSE
94  
95 Extract code chunks from all source files, identify cross-file duplicates, and
96 return a scored Result.
97  
98 =head3 API SPECIFICATION
99  
100 =head4 INPUT
101  
102 dist Test::CPAN::Health::Distribution required
103 context Hashref optional
104  
105 =head4 OUTPUT
106  
107 L<Test::CPAN::Health::Result> with check_id C<'duplicate_code'>.
108  
109 =head3 MESSAGES
110  
111 Code | Severity | Message | Resolution
112 ------+----------+---------------------------------------------+-----------
113 DC001 | SKIP | No source files found | Add source files
114 DC002 | PASS | No cross-file duplicate code blocks found |
115 DC003 | WARN | N duplicate code block(s) found | Refactor to shared sub
116 DC004 | FAIL | Many duplicate code blocks found | Refactor to shared sub
117  
118 =head3 FORMAL SPECIFICATION
119  
120 -- Z schema (placeholder) --
121 DuplicateCodeOp
122 total_chunks : N
123 dup_chunks : N
124 score : 0..100
125 -------------------------------------------------------
126 total_chunks = 0 => status = pass /\ score = 100
127 score >= 90 => status = pass
128 score >= 50 => status = warn
129 score < 50 => status = fail
130  
131 =head3 SIDE EFFECTS
132  
133 Reads source files only; no network or subprocess I/O.
134  
135 =head3 USAGE EXAMPLE
136  
137 my $result = Test::CPAN::Health::Check::DuplicateCode->new->run($dist);
138 print $result->summary;
139  
140 =cut
141  
142 sub run {
143 my ($self, $dist, $context) = @_;
144  
145 croak 'dist must be a Test::CPAN::Health::Distribution'
146 unless ref($dist) && $dist->isa('Test::CPAN::Health::Distribution');
147  
148 my @files = @{ $dist->all_source_files };
149  
150 unless (@files) {
151 return $self->_skip('No source files found');
152 }
153  
154 # Map: chunk_key => { file => 1, ... } (track unique files per chunk)
155 my %chunk_files;
156 my $total_chunks = 0;
157  
158 for my $file (@files) {
159 $total_chunks += _index_file_chunks($file, \%chunk_files);
160 }
161  
162 unless ($total_chunks) {
163 return $self->_result(
164 status => 'pass',
165 score => 100,
166 summary => 'No code chunks large enough to analyse',
167 data => { name => $self->name, total => 0, duplicates => 0 },
168 );
169 }
170  
171 my @dup_keys = grep { scalar keys %{ $chunk_files{$_} } > 1 } keys %chunk_files;
172  
173 my $dup_count = scalar @dup_keys;
174 my $score = int((1 - $dup_count / $total_chunks) * 100);
175 $score = 0 if $score < 0;
176 my $status = $score >= $SCORE_PASS ? 'pass'
177 : $score >= $SCORE_WARN ? 'warn'
178 : 'fail';
179  
180 my @details;
181 for my $key (@dup_keys) {
182 my @locs = sort keys %{ $chunk_files{$key} };
183 my @rels = map { File::Spec->abs2rel($_, $dist->path) } @locs;
184 push @details, 'Duplicate block in: ' . join(', ', @rels);
185 }
186  
187 return $self->_result(
188 status => $status,
189 score => $score,
190 summary => $dup_count
191 ? sprintf('%d duplicate code block(s) found across source files', $dup_count)
192 : 'No cross-file duplicate code blocks found',
193 details => \@details,
194 data => {
195 name => $self->name,
196 total => $total_chunks,
197 duplicates => $dup_count,
198 },
199 );
200 }
201  
202 # ---------------------------------------------------------------------------
203 # Private helpers
204 # ---------------------------------------------------------------------------
205  
206 # Add all CHUNK_SIZE-line windows from $file into %$chunk_files.
207 # Returns the count of windows added.
208 sub _index_file_chunks {
209 my ($file, $chunk_files) = @_;
210  
211 my @code_lines = _code_lines($file);
212 return 0 if @code_lines < $CHUNK_SIZE;
213  
214 my %seen;
215 my $added = 0;
216 for my $i (0 .. $#code_lines - $CHUNK_SIZE + 1) {
217 my $key = join("\x00", @code_lines[$i .. $i + $CHUNK_SIZE - 1]);
218 next if $seen{$key}++;
219 $chunk_files->{$key}{$file} = 1;
220 $added++;
221 }
222 return $added;
223 }
224  
225 # Return normalised, non-blank, non-comment, non-POD code lines from $file.
226 sub _code_lines {
227 my ($file) = @_;
228  
229 open my $fh, '<', $file or return ();
230 my @raw = <$fh>;
231 close $fh;
232  
233 my @lines;
234 my $in_pod = 0;
235  
236 for my $line (@raw) {
237 chomp $line;
238 if ($line =~ / ^ = (\w+) /x) {
239 $in_pod = ($1 ne 'cut');
240 next;
241 }
242 next if $in_pod;
243 my $norm = _normalise_line($line);
244 push @lines, $norm if defined $norm;
245 }
246 return @lines;
247 }
248  
249 # Normalise one line; return undef if it should be excluded.
250 sub _normalise_line {
251 my ($line) = @_;
252  
253 $line =~ s/ ^ \s+ | \s+ $ //gx;
254 $line =~ s/ \s+ / /gx;
255  
256 return unless length $line;
257 return if $line =~ / ^ [#] /x;
258 return if $line eq '1;';
259 return if $line =~ / ^ use \s+ (?:strict|warnings|autodie|utf8|parent|base) \b /x;
260 return $line;
261 }
262  
263 =head1 AUTHOR
264  
265 Nigel Horne, C<< <njh at nigelhorne.com> >>
266  
267 =head1 LICENSE AND COPYRIGHT
268  
269 Copyright (C) 2025-2026 Nigel Horne.
270  
271 This program is free software; you can redistribute it and/or modify it
272 under the terms of the GNU General Public License as published by the Free
273 Software Foundation; either version 2 of the License, or (at your option)
274 any later version.
275  
276 =cut
277  
278 1;
« blib/lib/Test/CPAN/Health/Check/DocQuality.pm ↑ Summary blib/lib/Test/CPAN/Health/Check/Examples.pm »