MoreHooks/CheckPerl.pm untested

filter: Statementstmt 0.0% 0 / 178 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 23 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 264 CC 12 SCAR 30.9
CC
12
Cov
0%
check_new_or_modified_files
56.0
_set_critic
42.0
_setup_config
2.0
CRAP 21.9
1 ## no critic (ValuesAndExpressions::RequireInterpolationOfMetachars)
2  
3 package Git::MoreHooks::CheckPerl;
4  
5 use strict;
6 use warnings;
7 use 5.016000;
8 use utf8;
9  
10 # ABSTRACT: Check committed files for Perl::Critic correctness.
11  
12 our $VERSION = '0.019'; # VERSION: generated by DZP::OurPkgVersion
13  
14  
15 # use Git::MoreHooks::CheckCommitBase \&do_hook;
16  
17 use Git::Hooks 3.000000;
18 use Path::Tiny;
19 use Log::Any qw{$log};
20 use Module::Load qw{ load };
21 use Text::Glob qw{ glob_to_regex };
22 use List::MoreUtils qw( any );
23  
24  
25 my $PKG = __PACKAGE__;
26 my ($HOOK) = __PACKAGE__ =~ /::([^:]+)$/msx;
27 my $CFG = 'githooks.' . $HOOK;
28  
29  
30 ####################
31 # Hook configuration, check it and set defaults.
32  
33 sub _setup_config {
34 my ($git) = @_;
35 $log->debugf( __PACKAGE__ . '::_setup_config(%s):', '$git' );
36  
37 my $config = $git->get_config();
38 $log->tracef( __PACKAGE__ . '::_setup_config(): Current Git config:\n%s.', $config );
39  
40 # Put empty hash if there is no config items.
41 $config->{ lc $CFG } //= {};
42  
43 # Set default config values.
44 my $default = $config->{ lc $CFG };
45 $default->{'use-temp-files'} //= [0];
46 $default->{'name'} //= ['*.p[lm]', '*.psgi', '*.t'];
47  
48 $default->{'critic'} //= {};
49 $default->{'b-lint'} //= {};
50 $default->{'perl-c'} //= {};
51  
52 # Perl::Critic
53 $default->{'critic'}->{'active'} //= ['true'];
54 $default->{'critic'}->{'profile'} //= [];
55  
56 # B::Lint
57 $default->{'b-lint'}->{'active'} //= ['true'];
58  
59 # Perl -c
60 $default->{'perl-c'}->{'active'} //= [0];
61  
62 $log->tracef( __PACKAGE__ . '::_setup_config(): Final Git config:\n%s.', $config );
63  
64 return 1;
65 }
66  
67 ####################
68 # Internal
69  
70 use Config::Tiny;
71  
72 sub _get_critic_profile {
73 my ($git, $profile) = @_;
74 $log->debugf( __PACKAGE__ . q{::} . '_get_critic_profile():profile=%s', $profile);
75  
76 my $content = $git->run(qw/cat-file -p/, $profile);
77 $log->tracef( __PACKAGE__ . q{::} . '_get_critic_profile():content=%s', $content);
78  
79 return $content;
80 }
81  
82 sub _read_critic_profile {
83 my ($git, $content) = @_;
84 my $c = Config::Tiny->read_string( $content );
85 return $c;
86 }
87  
88 sub _set_critic {
89 my ($git) = @_;
90 my $cfg_section = $CFG . q{.} . 'critic';
91  
92 eval {
93 load 'Perl::Critic';
94 load 'Perl::Critic::Utils';
95 load 'Perl::Critic::Violation';
96 1; # To cover the fact that operation correctly returns a false value.
97 } or do {
98 $log->errorf( __PACKAGE__ . q{::}
99 . '_set_critic():Cannot load Perl::Critic'
100 );
101 return { 'error' => 'Cannot load Perl::Critic' };
102 };
103  
104 my $pc_rc_filename = $git->get_config( $cfg_section => 'profile');
105 $log->tracef( __PACKAGE__ . q{::} . '_set_critic():pc_rc_filename=%s', $pc_rc_filename);
106  
107 my @critic_cfg_props = qw( severity theme top only force verbose allow-unsafe );
108 my @critic_cfg_list_props = qw( include exclude );
109 my %cfg;
110 if( $pc_rc_filename ) {
111 my $content = _get_critic_profile( $git, $pc_rc_filename );
112 my $rc = _read_critic_profile( $git, $content );
113 $log->debugf( __PACKAGE__ . q{::}
114 . '_set_critic():(rc)=(%s)', $rc
115 );
116  
117 $cfg{'-profile'} = q{}; # Do not read a .perlcriticrc file!
118 ## no critic (ControlStructures::ProhibitPostfixControls)
119 my $props = $rc->{_};
120 $log->debugf( __PACKAGE__ . q{::} . '_set_critic():(props)=%s', $props);
121 foreach my $key ( keys %{ $props } ) {
122 my $item_name = ( any { $key } @critic_cfg_props ) ? "-$key" : $key;
123 my $val = $props->{ $key };
124 $cfg{ $item_name } = $val;
125 }
126 # These two require special handling.
127 foreach my $key ( @critic_cfg_list_props ) {
128 my $val = $props->{ $key };
129 $cfg{ "-$key" } = [ split qr/\s+/msx, $val ] if( $val ); ## no critic (ControlStructures::ProhibitPostfixControls)
130 }
131 } else {
132 my $props = $git->get_config( "$cfg_section.cfg" );
133 $log->debugf( __PACKAGE__ . q{::} . '_set_critic():(props)=%s', $props);
134 foreach my $key ( keys %{ $props } ) {
135 my $item_name = ( any { $key } @critic_cfg_props ) ? "-$key" : $key;
136 my $val = $props->{ $key }->[-1]; # The value is a list, take last item from it.
137 $cfg{ $item_name } = $val;
138 }
139 # These two require special handling.
140 foreach my $key ( @critic_cfg_list_props ) {
141 my $val = $props->{ $key }->[-1];
142 $cfg{ "-$key" } = [ split qr/\s+/msx, $val ] if( $val ); ## no critic (ControlStructures::ProhibitPostfixControls)
143 }
144 }
145 $log->debugf( __PACKAGE__ . q{::} . '_set_critic():(cfg)=(%s)', \%cfg);
146  
147 my $pc = Perl::Critic->new( %cfg );
148 $log->debugf( __PACKAGE__ . q{::} . '_set_critic():(Perl::Critic config)=(%s)', $pc->config);
149  
150 # set the format to be a comment
151 my $verbosity = $pc->config->verbose;
152 my $format = Perl::Critic::Utils::verbosity_to_format( $verbosity );
153 Perl::Critic::Violation::set_format( "# $format" );
154  
155 return { 'critic' => $pc };
156 }
157  
158 sub _check_perl_critic_violations {
159 my ($git, $commit, $cache, $content, $filename) = @_;
160  
161 my ($critic) = $cache->{'critic'};
162 # Source code should only be passed to PPI::Document->new as a SCALAR reference
163 my @violations = $critic->critique( \$content );
164 $log->debugf( __PACKAGE__ . q{::}
165 . '_check_perl_critic_violations():file=%s, violations=%s', $filename, \@violations);
166  
167 return @violations;
168 }
169  
170 # TODO Make this dynamic, add more checkers.
171 my @PERL_CHECKERS = (
172 {
173 name => q{Perl::Critic},
174 cfg => q{critic},
175 f_do => \&_check_perl_critic_violations,
176 input => 'FILE_CONTENT',
177 f_pre => \&_set_critic,
178 cache => undef,
179 }
180 );
181  
182 ####################
183 # Main functions
184  
185 sub check_new_or_modified_files {
186 my ($git, $commit, @files) = @_;
187 $log->debugf( __PACKAGE__ . q{::} . 'check_new_or_modified_files(%s, %s, %s)', 'git', $commit, \@files);
188 my $errors = 0;
189  
190 my $config = $git->get_config( $CFG );
191 $log->tracef( __PACKAGE__ . q{::} . 'check_new_or_modified_files():config=%s', $config);
192 my @name_patterns;
193 foreach my $pattern (@{ $config->{'name'} }) {
194 # TODO Refactor regex.
195 ## no critic (RegularExpressions::RequireDotMatchAnything)
196 ## no critic (RegularExpressions::RequireExtendedFormatting)
197 ## no critic (RegularExpressions::RequireLineBoundaryMatching)
198 if ($pattern =~ m/^qr(.)(.*)\g{1}/) {
199 $pattern = qr/$2/;
200 } else {
201 $pattern = glob_to_regex($pattern);
202 }
203 push @name_patterns, $pattern;
204 }
205 $log->debugf( __PACKAGE__ . q{::} . 'check_new_or_modified_files():name_patterns=%s', \@name_patterns);
206 foreach my $file ($git->run(qw/ls-files -s/, @files)) {
207 my ($mode, $sha, $n, $filename) = split q{ }, $file;
208 $log->tracef( __PACKAGE__ . q{::}
209 . 'check_new_or_modified_files():(mode, sha, n, name)=(%s, %s, %s, %s)',
210 ($mode, $sha, $n, $filename)
211 );
212 my $basename = path($filename)->basename;
213 $log->debugf( __PACKAGE__ . q{::} . 'check_new_or_modified_files():basename=%s', $basename);
214 # The regexes generated from globs might not be /msx compatible.
215 ## no critic (RegularExpressions::RequireDotMatchAnything)
216 ## no critic (RegularExpressions::RequireExtendedFormatting)
217 ## no critic (RegularExpressions::RequireLineBoundaryMatching)
218 next if( ! any { $basename =~ m/$_/ } @name_patterns);
219 my $content = $git->run(qw/cat-file -p/, $sha);
220 $log->tracef( __PACKAGE__ . q{::} . 'check_new_or_modified_files():content=%s', $content);
221  
222 foreach my $checker ( @PERL_CHECKERS ) {
223 $log->debugf( __PACKAGE__ . q{::} . 'check_new_or_modified_files():checker=%s', $checker);
224 my @violations;
225 my $active = $config->{'critic'}->{'active'}->[0];
226 $log->debugf( __PACKAGE__ . q{::} . 'check_new_or_modified_files():active=%s', $active);
227 next if( ! $active );
228  
229 if( ! defined $checker->{'cache'} ) {
230 $checker->{'cache'} = &{ $checker->{'f_pre'} }( $git );
231 }
232 if( defined $checker->{'cache'}->{'error'} ) {
233 $git->fault($checker->{'name'} . ' Error: ' . $checker->{'cache'}->{'error'});
234 ++$errors;
235 return $errors;
236 }
237 if( $checker->{'input'} eq q{FILE_CONTENT} ) {
238 @violations = &{$checker->{'f_do'}}(
239 $git, $commit, $checker->{'cache'}, $content, $filename
240 );
241 } else {
242 # TODO Save file to /tmp dir. Not implemented!
243 }
244 $log->debugf( __PACKAGE__ . q{::}
245 . 'check_new_or_modified_files():file=%s, violations=%s', $filename, \@violations);
246  
247 # Report errors
248 foreach my $violation (@violations) {
249 $git->fault($checker->{'name'} . " error in file '$filename':\n" . $violation,
250 {prefix => 'CheckPerl', commit => $commit});
251 ++$errors;
252 }
253 }
254 }
255 return $errors;
256 }
257  
258 sub check_commit {
259 my ($git) = @_;
260 return check_new_or_modified_files($git, ':0', $git->filter_files_in_index('AM'));
261 }
262 sub check_ref {
263 my ($git, $ref) = @_;
264 my ($old_commit, $new_commit) = $git->get_affected_ref_range($ref);
265 return check_new_or_modified_files(
266 $git,
267 $new_commit,
268 $git->filter_files_in_range('AM', $old_commit, $new_commit),
269 );
270 }
271 sub check_patchset {
272 my ($git, $branch, $commit) = @_;
273 return check_everything($git, $branch, $commit->commit, $commit->extra);
274 }
275  
276 # Install hooks
277 my $options = {config => \&_setup_config};
278  
279 GITHOOKS_CHECK_PRE_COMMIT (\&check_commit, $options);
280 GITHOOKS_CHECK_AFFECTED_REFS (\&check_ref, $options);
281 GITHOOKS_CHECK_PATCHSET (\&check_patchset, $options);
282  
283 1;
284  
285 __END__