blib/lib/Git/MoreHooks/CheckPerl.pm untested

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