blib/lib/Git/Hooks/CheckFile.pm untested

filter: Statementstmt 0.0% 0 / 257 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 37 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 407 CC 40 SCAR 37.0
CC
40
Cov
0%
check_acls
90.0
check_executables
72.0
check_everything
72.0
CRAP 40.6
1 use warnings;
2  
3 package Git::Hooks::CheckFile;
4 # ABSTRACT: Git::Hooks plugin for checking files
5 $Git::Hooks::CheckFile::VERSION = '3.5.0';
6 use v5.16.0;
7 use utf8;
8 use Carp;
9 use Log::Any '$log';
10 use Git::Hooks;
11 use Text::Glob qw/glob_to_regex/;
12 use Path::Tiny;
13 use List::MoreUtils qw/any none/;
14  
15 my $CFG = __PACKAGE__ =~ s/.*::/githooks./r;
16  
17 #############
18 # Grok hook configuration, check it and set defaults.
19  
20 sub _setup_config {
21 my ($git) = @_;
22  
23 my $config = $git->get_config();
24  
25 $config->{lc $CFG} //= {};
26  
27 my $default = $config->{lc $CFG};
28  
29 $default->{sizelimit} //= [0];
30  
31 $default->{'max-path'} //= [0];
32  
33 return;
34 }
35  
36 sub check_command {
37 my ($git, $ctx, $commit, $file, $command) = @_;
38  
39 my $tmpfile = $git->blob($commit, $file)
40 or return 1;
41  
42 # interpolate filename in $command
43 my $cmd = $command =~ s/\{\}/\'$tmpfile\'/gr;
44  
45 # execute command and update $errors
46 my ($exit, $output);
47 {
48 my $tempfile = Path::Tiny->tempfile(UNLINK => 1);
49  
50 ## no critic (RequireBriefOpen, RequireCarping)
51 open(my $oldout, '>&', \*STDOUT) or croak "Can't dup STDOUT: $!";
52 open(STDOUT , '>' , $tempfile) or croak "Can't redirect STDOUT to \$tempfile: $!";
53 open(my $olderr, '>&', \*STDERR) or croak "Can't dup STDERR: $!";
54 open(STDERR , '>&', \*STDOUT) or croak "Can't dup STDOUT for STDERR: $!";
55  
56 # Let the external command know the commit that's being checked in
57 # case it needs to grok something from Git.
58 local $ENV{GIT_COMMIT} = $commit;
59 $exit = system $cmd;
60  
61 open(STDOUT, '>&', $oldout) or croak "Can't dup \$oldout: $!";
62 open(STDERR, '>&', $olderr) or croak "Can't dup \$olderr: $!";
63 ## use critic
64  
65 $output = $tempfile->slurp;
66 }
67  
68 if ($exit != 0) {
69 $command =~ s/\{\}/\'$file\'/g;
70 my $message = do {
71 if ($exit == -1) {
72 "Command '$command' could not be executed: $!";
73 } elsif ($exit & 127) {
74 sprintf("Command '%s' was killed by signal %d, %s coredump",
75 $command, ($exit & 127), ($exit & 128) ? 'with' : 'without');
76 } else {
77 sprintf("Command '%s' failed with exit code %d", $command, $exit >> 8);
78 }
79 };
80  
81 # Replace any instance of the $tmpfile name in the output by
82 # $file to avoid confounding the user.
83 $output =~ s/\Q$tmpfile\E/$file/g;
84  
85 $git->fault($message, {%$ctx, details => $output});
86 return 1;
87 } else {
88 # FIXME: What should we do with eventual output from a
89 # successful command?
90 }
91 return 0;
92 }
93  
94 sub check_commands {
95 my ($git, $ctx, $commit, $files) = @_;
96  
97 # Construct a list of command checks from the
98 # githooks.checkfile.name configuration. Each check in the list is a
99 # pair containing a regex and a command specification.
100 my @name_checks;
101 foreach my $check ($git->get_config($CFG => 'name')) {
102 my ($pattern, $command) = split ' ', $check, 2;
103 if ($pattern =~ m/^qr(.)(.*)\g{1}/) {
104 $pattern = qr/$2/;
105 } else {
106 $pattern = glob_to_regex($pattern);
107 }
108 $command .= ' {}' unless $command =~ /\{\}/;
109 push @name_checks, [$pattern => $command];
110 }
111  
112 my $errors = 0;
113  
114 foreach my $file (@$files) {
115 my $basename = path($file)->basename;
116  
117 foreach my $command (map {$_->[1]} grep {$basename =~ $_->[0]} @name_checks) {
118 $errors += check_command($git, $ctx, $commit, $file, $command);
119 } continue {
120 $git->check_timeout();
121 }
122 }
123  
124 return $errors;
125 }
126  
127 sub check_sizes {
128 my ($git, $ctx, $commit, $files) = @_;
129  
130 # See if we have to check a file size limit
131 my $sizelimit = $git->get_config_integer($CFG => 'sizelimit');
132  
133 # Grok all REGEXP checks
134 my %re_checks;
135 foreach ($git->get_config("$CFG.basename" => 'sizelimit')) {
136 my ($bytes, $regexp) = split ' ', $_, 2;
137 unshift @{$re_checks{basename}{sizelimit}}, [qr/$regexp/, $bytes];
138 }
139  
140 return 0 unless $sizelimit || %re_checks;
141  
142 my $errors = 0;
143  
144 foreach my $file (@$files) {
145 my $basename = path($file)->basename;
146  
147 my $size = $git->file_size($commit, $file);
148  
149 my $file_sizelimit = $sizelimit;
150 foreach my $spec (@{$re_checks{basename}{sizelimit}}) {
151 if ($basename =~ $spec->[0]) {
152 $file_sizelimit = $spec->[1];
153 last;
154 }
155 }
156  
157 if ($file_sizelimit && $file_sizelimit < $size) {
158 $git->fault(<<"EOS", {%$ctx, option => '[basename.]sizelimit'});
159 The file '$file' is too big.
160  
161 It has $size bytes but the current limit is $file_sizelimit bytes.
162 Please, check your configuration options.
163 EOS
164 ++$errors;
165 }
166 }
167  
168 return $errors;
169 }
170  
171 sub check_executables {
172 my ($git, $ctx, $commit, $files) = @_;
173  
174 # Grok the list of patterns to check for executable permissions
175 my %executable_checks;
176 foreach my $check (qw/executable not-executable/) {
177 foreach my $pattern ($git->get_config($CFG => $check)) {
178 if ($pattern =~ m/^qr(.)(.*)\g{1}/) {
179 $pattern = qr/$2/;
180 } else {
181 $pattern = glob_to_regex($pattern);
182 }
183 push @{$executable_checks{$check}}, $pattern;
184 }
185 }
186  
187 return 0 unless %executable_checks;
188  
189 my $errors = 0;
190  
191 FILE:
192 foreach my $file (@$files) {
193 my $basename = path($file)->basename;
194  
195 my $mode;
196  
197 if (any {$basename =~ $_} @{$executable_checks{'executable'}}) {
198 $mode = $git->file_mode($commit, $file);
199 unless ($mode & 0b1) {
200 $git->fault(<<"EOS", {%$ctx, option => 'executable'});
201 The file '$file' is not executable but should be.
202 Please, check your configuration options.
203 EOS
204 ++$errors;
205 }
206 }
207  
208 if (any {$basename =~ $_} @{$executable_checks{'not-executable'}}) {
209 if (defined $mode) {
210 git->fault(<<"EOS", {%$ctx, option => '[not-]executable'});
211 Configuration error: The file '$file' matches a 'executable' and a
212 'not-executable' option simultaneously, which is inconsistent.
213 Please, fix your configuration so that it matches only one of these options.
214 EOS
215 ++$errors;
216 }
217 $mode = $git->file_mode($commit, $file);
218 if ($mode & 0b1) {
219 $git->fault(<<"EOS", {%$ctx, option => 'not-executable'});
220 The file '$file' is executable but should not be.
221 Please, check your configuration options.
222 EOS
223 ++$errors;
224 }
225 }
226 }
227  
228 return $errors;
229 }
230  
231 sub deny_case_conflicts {
232 my ($git, $ctx, $commit, $files) = @_;
233  
234 return 0 unless $git->get_config_boolean($CFG => 'deny-case-conflict');
235  
236 # Grok the list of all files in the repository at $commit
237 my @ls_files = split(
238 /\0/,
239 $git->run(qw/ls-tree -r -z --name-only --full-tree/,
240 $commit ne ':0' ? $commit : $git->get_head_or_empty_tree),
241 );
242  
243 my $errors = 0;
244  
245 # Check if the new files conflict with each other
246 for (my $i = 0; $i < $#$files; ++$i) {
247 for (my $j = $i + 1; $j <= $#$files; ++$j) {
248 if (lc($files->[$i]) eq lc($files->[$j]) &&
249 $files->[$i] ne $files->[$j]) {
250 ++$errors;
251 $git->fault(<<"EOS", {%$ctx, option => 'deny-case-conflict'});
252 This commit adds two files with names that will conflict
253 with each other in the repository in case-insensitive
254 filesystems:
255  
256 $files->[$i]
257 $files->[$j]
258  
259 Please, rename the added files to avoid the conflict and amend your commit.
260 EOS
261 }
262 }
263 }
264  
265 # Check if the new files conflict with already existing files
266 foreach my $file (@ls_files) {
267 my $lc_file = lc $file;
268 foreach my $name (@$files) {
269 my $lc_name = lc $name;
270 if ($lc_name eq $lc_file && $name ne $file) {
271 ++$errors;
272 $git->fault(<<"EOS", {%$ctx, option => 'deny-case-conflict'});
273 This commit adds a file with a name that will conflict
274 with the name of another file already existing in the repository
275 in case-insensitive filesystems:
276  
277 ADDED: $name
278 EXISTING: $file
279  
280 Please, rename the added file to avoid the conflict and amend your commit.
281 EOS
282 }
283 }
284 }
285  
286 return $errors;
287 }
288  
289 sub check_max_paths {
290 my ($git, $ctx, $commit, $files) = @_;
291  
292 # See if we have to check a file size limit
293 my $max_path = $git->get_config_integer($CFG => 'max-path');
294  
295 return 0 unless $max_path;
296  
297 my @bigs = grep {length > $max_path} @$files;
298  
299 if (@bigs) {
300 $git->fault(<<"EOS", {%$ctx, option => 'max-path'});
301 The following files have paths more than $max_path characters long.
302  
303 @{[join("\n ", @bigs)]}
304  
305 Git may not be able to check them out on a Windows host due to its maximum path
306 length limit of 260 characteres. See:
307 https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
308  
309 Please, ammend your changes to shorten their paths.
310 EOS
311 }
312  
313 return @bigs;
314 }
315  
316 sub deny_token {
317 my ($git, $ctx, $commit) = @_;
318  
319 my $regex = $git->get_config($CFG => 'deny-token')
320 or return 0;
321  
322 # Extract only the lines showing addition of the $regex
323 my @diff = grep {/^\+.*?(?:$regex)/}
324 ($commit ne ':0'
325 ? $git->run(qw/diff-tree -p --diff-filter=AM --ignore-submodules/,
326 "-G$regex", $commit)
327 : $git->run(qw/diff-index --cached -p --diff-filter=AM --ignore-submodules/,
328 "-G$regex", $git->get_head_or_empty_tree));
329  
330 if (@diff) {
331 $git->fault(<<"EOS", {%$ctx, option => 'deny-token', details => join("\n", @diff)});
332 Invalid tokens detected in added lines.
333 This option rejects lines matching $regex.
334 Please, amend these lines and try again.
335 EOS
336 }
337  
338 return scalar @diff;
339 }
340  
341 # Assign meaningful names to action codes.
342 my %ACTION = (
343 A => 'add',
344 M => 'modify',
345 D => 'delete',
346 );
347  
348 sub check_acls {
349 my ($git, $ctx, $name2status) = @_;
350  
351 my @acls = eval { $git->grok_acls($CFG, 'AMD') };
352 if ($@) {
353 $git->fault($@, $ctx);
354 return 1;
355 }
356  
357 return 0 unless @acls;
358  
359 # Collect the ACL errors and group them by ACL/ACTION so that we can produce
360 # more compact error messages.
361 my %acl_errors;
362  
363 FILE:
364 foreach my $file (sort keys %$name2status) {
365 my $statuses = $name2status->{$file};
366 foreach my $acl (@acls) {
367 next unless ref $acl->{spec} ? $file =~ $acl->{spec} : $file eq $acl->{spec};
368  
369 # $status is usually a single letter but it can be a string of
370 # letters if we grokked affected files in a merge commit. So, we
371 # consider a match if the intersection of the two strings ($statuses
372 # and $acl->{action}) is not empty.
373 next if none {index($acl->{action}, $_) >= 0} split //, $statuses;
374  
375 unless ($acl->{allow}) {
376 my $action = $ACTION{$statuses} || $statuses;
377 push @{$acl_errors{$acl->{acl}}{$action}}, $file;
378 }
379  
380 next FILE;
381 }
382 }
383  
384 if (%acl_errors) {
385 my $myself = $git->authenticated_user();
386 my %context = (%$ctx, option => 'acl');
387 while (my ($acl, $actions) = each %acl_errors) {
388 while (my ($action, $files) = each %$actions) {
389 my $these_files = scalar(@$files) > 1 ? 'these files' : 'this file';
390 $git->fault(<<"EOS", \%context);
391 Authorization error: you ($myself) cannot $action $these_files:
392  
393 @{[join("\n ", @$files)]}
394  
395 Due to the following acl:
396  
397 $acl
398 EOS
399 }
400 }
401 }
402  
403 return scalar %acl_errors;
404 }
405  
406 sub check_everything {
407 my ($git, $ref, $commit, $extra) = @_;
408  
409 # The $extra information was generated by the --name-status --cc options to
410 # git-log. It has one line for each file affected in the commit. Merge
411 # commits only show files with conflicts. The format is "<S>+\t<FILE>". <S>
412 # is one letter indicating how the file was affected, as documented in the
413 # --diff-filter option. <FILE> is the file path since the repository root,
414 # without a leading slash.
415  
416 my %name2status;
417  
418 if (defined $extra) {
419 foreach (split /\n/, $extra) {
420 if (/^(?<status>[ACDMRTUXB0-9]+)\t(?<file>.+)/) {
421 my ($status, $file) = ($+{status}, $+{file});
422 if ($file =~ /^\".*\"$/) {
423 # Pathnames with "unusual" characters are quoted as
424 # explained for the configuration variable core.quotePath
425 # (see git-config(1)): "by enclosing the pathname in
426 # double-quotes and escaping those characters with
427 # backslashes in the same way C escapes control characters
428 # (e.g. \t for TAB, \n for LF, \\ for backslash) or bytes
429 # with values larger than 0x80 (e.g. octal \302\265 for
430 # "micro" in UTF-8)."
431  
432 # The section "Quote and Quote-like Operators" of perlop
433 # explains how Perl's string literal syntax is an (almost)
434 # superset of C's. The only C escape that Perl doesn't have
435 # is "\v", which can be expressed in Perl as "\x0b". So,
436 # first we use a s/// operator to replace any and all
437 # occurrences of \v.
438  
439 $file =~ s/(?<!\\)\\v/\x0b/g;
440  
441 # However, since we must evaluate the literal string as
442 # doubly-quoted we must take care to escape the $ and @
443 # sigils, or Perl will try to innterpolate them.
444  
445 $file =~ s/([\$\@])/\\$1/g;
446  
447 # Now, we can use eval to read the resulting string as if it
448 # were a Perl string literal.
449  
450 $file = eval $file; ## no critic (ProhibitStringyEval)
451 }
452 $name2status{$file} = $status;
453 }
454 }
455 }
456  
457 my %context = (ref => $ref);
458 $context{commit} = $commit unless $commit eq ':0';
459  
460 my $errors =
461 check_acls($git, \%context, \%name2status) +
462 deny_token($git, \%context, $commit);
463  
464 if (my @AC_files = sort grep {$name2status{$_} =~ /[AC]/} keys %name2status) {
465 $errors +=
466 deny_case_conflicts($git, \%context, $commit, \@AC_files) +
467 check_max_paths($git, \%context, $commit, \@AC_files);
468 }
469  
470 if (my @ACM_files = sort grep {$name2status{$_} =~ /[ACM]/} keys %name2status) {
471 $errors +=
472 check_executables($git, \%context, $commit, \@ACM_files) +
473 check_sizes($git, \%context, $commit, \@ACM_files);
474 # Avoid external checks if there are errors already
475 $errors += check_commands($git, \%context, $commit, \@ACM_files)
476 unless $errors;
477 }
478  
479 return $errors;
480 }
481  
482 sub check_ref {
483 my ($git, $ref) = @_;
484  
485 my ($old_commit, $new_commit) = $git->get_affected_ref_range($ref);
486  
487 my @commits = $git->get_commits(
488 $old_commit,
489 $new_commit,
490 [qw/--name-status --ignore-submodules -r --cc/],
491 );
492  
493 my $errors = 0;
494  
495 foreach my $commit (@commits) {
496 $errors += check_everything($git, $ref, $commit->commit, $commit->extra);
497 }
498  
499 return $errors;
500 }
501  
502 sub check_commit {
503 my ($git, $current_branch) = @_;
504  
505 my $extra = $git->run(qw/diff-index --name-status --ignore-submodules --no-commit-id --cached -r/,
506 $git->get_head_or_empty_tree);
507  
508 return check_everything(
509 $git,
510 $current_branch,
511 ':0', # mark to signify the index
512 $extra,
513 );
514 }
515  
516 sub check_patchset {
517 my ($git, $branch, $commit) = @_;
518  
519 return check_everything($git, $branch, $commit->commit, $commit->extra);
520 }
521  
522 # Install hooks
523 my $options = {config => \&_setup_config};
524  
525 GITHOOKS_CHECK_AFFECTED_REFS(\&check_ref, $options);
526 GITHOOKS_CHECK_PRE_COMMIT(\&check_commit, $options);
527 GITHOOKS_CHECK_PATCHSET(\&check_patchset, $options);
528  
529 1;
530  
531 __END__