blib/lib/Code/TidyAll/Git/Prereceive.pm untested

filter: Statementstmt 0.0% 0 / 125 Branchbran 0.0% 0 / 24 Conditioncond 0.0% 0 / 13 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 187 CC 13 SCAR 27.4
CC
13
Cov
0%
check_repeated_push
42.0
check_input
30.0
check
12.0
CRAP 15.5
1 package Code::TidyAll::Git::Prereceive;
2  
3 use strict;
4 use warnings;
5  
6 use Capture::Tiny qw(capture);
7 use Code::TidyAll::Util qw(tempdir_simple);
8 use Code::TidyAll;
9 use Digest::SHA qw(sha1_hex);
10 use IPC::System::Simple qw(capturex run);
11 use Path::Tiny qw(cwd path);
12 use Specio::Library::Builtins;
13 use Specio::Library::Numeric;
14 use Specio::Library::String;
15 use Try::Tiny;
16  
17 use Moo;
18  
19 our $VERSION = '0.83';
20  
21 has allow_repeated_push => (
22 is => 'ro',
23 isa => t('PositiveInt'),
24 default => 3,
25 );
26  
27 has conf_name => (
28 is => 'ro',
29 isa => t('NonEmptyStr'),
30 );
31  
32 has extra_conf_files => (
33 is => 'ro',
34 isa => t( 'ArrayRef', of => t('NonEmptyStr') ),
35 default => sub { [] },
36 );
37  
38 has git_path => (
39 is => 'ro',
40 isa => t('NonEmptyStr'),
41 default => 'git',
42 );
43  
44 has tidyall_class => (
45 is => 'ro',
46 isa => t('ClassName'),
47 default => 'Code::TidyAll',
48 );
49  
50 has tidyall_options => (
51 is => 'ro',
52 isa => t('HashRef'),
53 default => sub { {} }
54 );
55  
56 sub check {
57 my ( $class, %params ) = @_;
58  
59 my $fail_msg;
60 try {
61 my $self = $class->new(%params);
62  
63 my $root_dir = cwd();
64 local $ENV{GIT_DIR} = $root_dir;
65  
66 my $input = do { local $/; <STDIN> };
67 $fail_msg = $self->check_input($input);
68 }
69 catch {
70 my $error = $_;
71 if ( $params{reject_on_error} ) {
72 die $error;
73 }
74 else {
75 print STDERR "*** Error running pre-receive hook (allowing push to proceed):\n$error";
76 }
77 };
78 die "$fail_msg\n" if $fail_msg;
79 }
80  
81 sub check_input {
82 my ( $self, $input ) = @_;
83  
84 my @lines = split( "\n", $input );
85 my ( @results, $tidyall );
86 foreach my $line (@lines) {
87 chomp($line);
88 my ( $base, $commit, $ref ) = split( /\s+/, $line );
89  
90 # Create tidyall using configuration found in first commit
91 #
92 $tidyall ||= $self->create_tidyall($commit);
93  
94 my @files = $self->get_changed_files( $base, $commit );
95 foreach my $file (@files) {
96 my $contents = $self->get_file_contents( $file, $commit );
97 if ( $contents =~ /\S/ && $contents =~ /\n/ ) {
98 push( @results, $tidyall->process_source( $contents, $file ) );
99 }
100 }
101 }
102  
103 my $fail_msg;
104 if ( my @error_results = grep { $_->error } @results ) {
105 unless ( $self->check_repeated_push($input) ) {
106 my $error_count = scalar(@error_results);
107 $fail_msg = sprintf(
108 '%d file%s did not pass tidyall check',
109 $error_count, $error_count > 1 ? 's' : q{}
110 );
111 }
112 }
113 return $fail_msg;
114 }
115  
116 sub create_tidyall {
117 my ( $self, $commit ) = @_;
118  
119 my $temp_dir = tempdir_simple();
120 my @conf_names = $self->conf_name ? ( $self->conf_name ) : Code::TidyAll->default_conf_names;
121 my ($conf_file) = grep { $self->get_file_contents( $_, $commit ) } @conf_names
122 or die sprintf( 'could not find conf file %s', join( ' or ', @conf_names ) );
123 foreach my $rel_file ( $conf_file, @{ $self->extra_conf_files } ) {
124 my $contents = $self->get_file_contents( $rel_file, $commit )
125 or die sprintf( q{could not find file '%s' in repo root}, $rel_file );
126 $temp_dir->child($rel_file)->spew($contents);
127 }
128 my $tidyall = $self->tidyall_class->new_from_conf_file(
129 "$temp_dir/" . $conf_file,
130 mode => 'commit',
131 quiet => 1,
132 %{ $self->tidyall_options },
133 no_cache => 1,
134 no_backups => 1,
135 check_only => 1,
136 );
137 return $tidyall;
138 }
139  
140 sub get_changed_files {
141 my ( $self, $base, $commit ) = @_;
142 my $output = capturex( $self->git_path, 'diff', '--numstat', '--name-only', "$base..$commit" );
143 my @files = grep {/\S/} split( "\n", $output );
144 return @files;
145 }
146  
147 sub get_file_contents {
148 my ( $self, $file, $commit ) = @_;
149 my ( $contents, $error ) = capture { system( $self->git_path, 'show', "$commit:$file" ) };
150 return $contents;
151 }
152  
153 sub check_repeated_push {
154 my ( $self, $input ) = @_;
155  
156 my $allow = $self->allow_repeated_push;
157 return 0 unless defined $allow;
158  
159 my $cwd = path($0)->realpath->parent;
160 my $last_push_file = $cwd->child('.prereceive_lastpush');
161 if ( -w $cwd || -w $last_push_file ) {
162 my $push_sig = sha1_hex($input);
163 if ( -f $last_push_file ) {
164 my ( $last_push_sig, $count ) = split( /\s+/, $last_push_file->slurp );
165 if ( $last_push_sig eq $push_sig ) {
166 ++$count;
167 print STDERR "*** Identical push seen $count times\n";
168 if ( $count >= $allow ) {
169 print STDERR "*** Allowing push to proceed despite errors\n";
170 unlink($last_push_file);
171 return 1;
172 }
173 $last_push_file->spew( join( q{ }, $push_sig, $count ) );
174 return 0;
175 }
176 }
177 $last_push_file->spew( join( q{ }, $push_sig, 1 ) );
178 }
179  
180 return 0;
181 }
182  
183 1;
184  
185 # ABSTRACT: Git pre-receive hook that requires files to be tidyall'd
186  
187 __END__
188  
189 =pod
190  
191 =encoding UTF-8
192  
193 =head1 NAME
194  
195 Code::TidyAll::Git::Prereceive - Git pre-receive hook that requires files to be tidyall'd
196  
197 =head1 VERSION
198  
199 version 0.83
200  
201 =head1 SYNOPSIS
202  
203 In .git/hooks/pre-receive:
204  
205 #!/usr/bin/perl
206 use Code::TidyAll::Git::Prereceive;
207 use strict;
208 use warnings;
209  
210 Code::TidyAll::Git::Prereceive->check();
211  
212  
213 # or
214  
215 my $input = do { local $/; <STDIN> };
216  
217 # Do other things with $input here
218  
219 my $hook = Code::TidyAll::Git::Prereceive->new();
220 if (my $error = $hook->check_input($input)) {
221 die $error;
222 }
223  
224 =head1 DESCRIPTION
225  
226 This module implements a L<Git pre-receive
227 hook|http://git-scm.com/book/en/Customizing-Git-Git-Hooks> that checks if all
228 pushed files are tidied and valid according to L<tidyall>, and rejects the push
229 if not.
230  
231 This is typically used to validate pushes from multiple developers to a shared
232 repo, possibly on a remote server.
233  
234 See also L<Code::TidyAll::Git::Precommit>, which operates locally.
235  
236 =head1 METHODS
237  
238 This class provides the following methods:
239  
240 =head2 Code::TidyAll::Git::Prereceive->check(%params)
241  
242 This method reads commit info from standard input, then checks that all files
243 being added or modified in this push are tidied and valid according to
244 L<tidyall>. If not, then the entire push is rejected and the reason(s) are
245 output to the client. e.g.
246  
247 % git push
248 Counting objects: 9, done.
249 ...
250 remote: [checked] lib/CHI/Util.pm
251 remote: Code before strictures are enabled on line 13 [TestingAndDebugging::RequireUseStrict]
252 remote:
253 remote: 1 file did not pass tidyall check
254 To ...
255 ! [remote rejected] master -> master (pre-receive hook declined)
256  
257 The configuration file (C<tidyall.ini> or C<.tidyallrc>) must be checked into
258 git in the repo root directory, i.e. next to the .git directory.
259  
260 In an emergency the hook can be bypassed by pushing the exact same set of
261 commits 3 consecutive times (configurable via L</allow_repeated_push>):
262  
263 % git push
264 ...
265 remote: 1 file did not pass tidyall check
266  
267 % git push
268 ...
269 *** Identical push seen 2 times
270 remote: 1 file did not pass tidyall check
271  
272 % git push
273 ...
274 *** Identical push seen 3 times
275 *** Allowing push to proceed despite errors
276  
277 Or you can disable the hook in the repo being pushed to, e.g. by renaming
278 .git/hooks/pre-receive.
279  
280 If an unexpected runtime error occurs, it is reported but by default the commit
281 will be allowed through (see L</reject_on_error>).
282  
283 Passes mode = "commit" by default; see L<modes|tidyall/MODES>.
284  
285 Key/value parameters:
286  
287 =over 4
288  
289 =item * allow_repeated_push
290  
291 Number of times a push must be repeated exactly after which it will be let
292 through regardless of errors. Defaults to 3. Set to 0 or C<undef> to disable
293 this feature.
294  
295 =item * conf_name
296  
297 Conf file name to search for instead of the defaults.
298  
299 =item * extra_conf_files
300  
301 An arrayref of extra configuration files referred to from the main
302 configuration file, e.g.
303  
304 extra_conf_files => ['perlcriticrc', 'perltidyrc']
305  
306 These files will be pulled out of the repo alongside the main configuration
307 file. If you don't list them here then you'll get errors like 'cannot find
308 perlcriticrc' when the hook runs.
309  
310 =item * git_path
311  
312 Path to git to use in commands, e.g. '/usr/bin/git' or '/usr/local/bin/git'. By
313 default, just uses 'git', which will search the user's PATH.
314  
315 =item * reject_on_error
316  
317 Whether C<check> should reject the commit when an unexpected runtime error
318 occurs. By default, the error will be reported but the commit will be allowed.
319  
320 =item * tidyall_class
321  
322 Subclass to use instead of L<Code::TidyAll>
323  
324 =item * tidyall_options
325  
326 Hashref of options to pass to the L<Code::TidyAll> constructor. You can use
327 this to override the default options
328  
329 mode => 'commit',
330 quiet => 1,
331  
332 or pass additional options.
333  
334 =back
335  
336 =head2 Code::TidyAll::Git::Prereceive->new(%params)
337  
338 This takes the same parameters documented as documented in C<check> above and
339 returns a new object which you can then call C<check_input> on.
340  
341 =head2 $prereceive->check_input($input)
342  
343 Runs a check on I<$input>, the text block of lines that came from standard
344 input. You can call this manually before or after you do other processing on
345 the input. Returns an error string if there was a problem or undef if there
346 were no problems.
347  
348 =head1 KNOWN BUGS
349  
350 This hook will ignore any files with only a single line of content (no
351 newlines), as an imperfect way of filtering out symlinks.
352  
353 =head1 SUPPORT
354  
355 Bugs may be submitted at L<https://github.com/houseabsolute/perl-code-tidyall/issues>.
356  
357 =head1 SOURCE
358  
359 The source code repository for Code-TidyAll can be found at L<https://github.com/houseabsolute/perl-code-tidyall>.
360  
361 =head1 AUTHORS
362  
363 =over 4
364  
365 =item *
366  
367 Jonathan Swartz <swartz@pobox.com>
368  
369 =item *
370  
371 Dave Rolsky <autarch@urth.org>
372  
373 =back
374  
375 =head1 COPYRIGHT AND LICENSE
376  
377 This software is copyright (c) 2011 - 2022 by Jonathan Swartz.
378  
379 This is free software; you can redistribute it and/or modify it under
380 the same terms as the Perl 5 programming language system itself.
381  
382 The full text of the license can be found in the
383 F<LICENSE> file included with this distribution.
384  
385 =cut