File Coverage

blib/lib/App/PerlNitpick/Rule/DedupeIncludeStatements.pm
Criterion Covered Total %
statement 26 26 100.0
branch 6 10 60.0
condition 1 3 33.3
subroutine 4 4 100.0
pod 0 1 0.0
total 37 44 84.0


line stmt bran cond sub pod time code
1             package App::PerlNitpick::Rule::DedupeIncludeStatements;
2 1     1   371945 use Moose;
  1         485906  
  1         6  
3              
4             sub rewrite {
5 4     4 0 21699 my ($self, $document) = @_;
6              
7 4         10 my %used;
8             my @to_delete;
9 4 50       6 for my $el (@{ $document->find('PPI::Statement::Include') ||[]}) {
  4         19  
10 9 50 33     2653 next unless $el->type && $el->type eq 'use';
11 9         377 my $module = $el->module;
12 9         202 my $code = "$el";
13 9 100       193 if ($used{$code}) {
14 4         12 push @to_delete, $el;
15             } else {
16 5         16 $used{$code} = 1;
17             }
18             }
19              
20 4         10 for my $el (@to_delete) {
21 4         12 $self->_remove_with_trailing_characters($el);
22             }
23              
24 4         21 return $document;
25             }
26              
27             sub _remove_with_trailing_characters {
28 4     4   10 my ($self, $el) = @_;
29              
30 4         18 while ( my $next = $el->next_sibling ) {
31 1 50       34 last if !$next->isa('PPI::Token::Whitespace');
32 1         9 $next->remove;
33 1 50       46 last if $next eq "\n";
34             }
35 4         130 $el->remove;
36 4         181 return;
37             }
38              
39 1     1   8257 no Moose;
  1         10  
  1         8  
40             1;
41              
42             __END__
43              
44             =head1 DedupeIncludeStatements
45              
46             In this rule, multiple identical "use" statements of the same module are merged.
47              
48             For example, this code:
49              
50             use File::Temp;
51             use Foobar;
52             use File::Temp;
53              
54             ... is transformed to:
55              
56             use File::Temp;
57             use Foobar;
58              
59             Two statements are consider identical if, and only if, they are literally the same, character-to-character.