Debian Codegraph @

lib/Test2/Harness/Util.pm

raw
1 package Test2::Harness::Util;
2 use strict;
3 use warnings;
4
5 use Carp qw/confess/;
6 use Cwd qw/realpath/;
7 use Test2::Util qw/try_sig_mask do_rename/;
8 use Fcntl qw/LOCK_EX LOCK_UN SEEK_SET :mode/;
9 use File::Spec;
10
11 our $VERSION = '1.000179';
12
13 use Importer Importer => 'import';
14
15 our @EXPORT_OK = qw{
16 find_libraries
17 clean_path
18
19 parse_exit
20 mod2file
21 file2mod
22 fqmod
23
24 maybe_open_file
25 maybe_read_file
26 open_file
27 read_file
28 write_file
29 write_file_atomic
30 lock_file
31 unlock_file
32
33 hub_truth
34
35 apply_encoding
36
37 process_includes
38
39 chmod_tmp
40
41 looks_like_uuid
42 is_same_file
43 };
44
45 sub is_same_file {
46 my ($file1, $file2) = @_;
47
48 return 0 unless defined $file1;
49 return 0 unless defined $file2;
50
51 return 1 if "$file1" eq "$file2";
52 return 1 if clean_path($file1) eq clean_path($file2);
53
54 return 0 unless -e $file1;
55 return 0 unless -e $file2;
56
57 my ($dev1, $inode1) = stat($file1);
58 my ($dev2, $inode2) = stat($file2);
59
60 return 0 unless $dev1 == $dev2;
61 return 0 unless $inode1 == $inode2;
62 return 1;
63 }
64
65 sub looks_like_uuid {
66 my ($in) = @_;
67
68 return undef unless defined $in;
69 return undef unless length($in) == 36;
70 return undef unless $in =~ m/^[0-9A-F\-]+$/i;
71 return $in;
72 }
73
74 sub chmod_tmp {
75 my $file = shift;
76
77 my $mode = S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO;
78
79 chmod($mode, $file);
80 }
81
82 sub process_includes {
83 my %params = @_;
84
85 my @start = @{delete $params{list} // []};
86
87 my @list;
88 my %seen = ('.' => 1);
89
90 if (my $ch_dir = delete $params{ch_dir}) {
91 for my $path (@start) {
92 # '.' is special.
93 $seen{'.'}++ and next if $path eq '.';
94
95 if (File::Spec->file_name_is_absolute($path)) {
96 push @list => $path;
97 }
98 else {
99 push @list => File::Spec->catdir($ch_dir, $path);
100 }
101 }
102 }
103 else {
104 @list = @start;
105 }
106
107 # Skip @INC hook refs; clean_path would stringify them to bogus paths.
108 push @list => grep { !ref($_) } @INC if delete $params{include_current};
109
110 @list = map { $_ eq '.' ? $_ : clean_path($_) || $_ } @list if delete $params{clean};
111
112 @list = grep { !$seen{$_}++ } @list;
113
114 # If we ask for dot add it to the end.
115 push @list => '.' if delete($params{include_dot});
116
117 confess "Invalid parameters: " . join(', ' => sort keys %params) if keys %params;
118
119 return @list;
120 }
121
122 sub apply_encoding {
123 my ($fh, $enc) = @_;
124 return unless $enc;
125
126 # https://rt.perl.org/Public/Bug/Display.html?id=31923
127 # If utf8 is requested we use ':utf8' instead of ':encoding(utf8)' in
128 # order to avoid the thread segfault.
129 return binmode($fh, ":utf8") if $enc =~ m/^utf-?8$/i;
130 binmode($fh, ":encoding($enc)");
131 }
132
133 sub parse_exit {
134 my ($exit) = @_;
135
136 my $sig = $exit & 127;
137 my $dmp = $exit & 128;
138
139 return {
140 sig => $sig,
141 err => ($exit >> 8),
142 dmp => $dmp,
143 all => $exit,
144 };
145 }
146
147 sub fqmod {
148 my ($prefix, $input) = @_;
149 return $1 if $input =~ m/^\+(.*)$/;
150 return "$prefix\::$input";
151 }
152
153 sub hub_truth {
154 my ($f) = @_;
155
156 return $f->{hubs}->[0] if $f->{hubs} && @{$f->{hubs}};
157 return $f->{trace} if $f->{trace};
158 return {};
159 }
160
161 sub maybe_read_file {
162 my ($file) = @_;
163 return undef unless -f $file;
164 return read_file($file);
165 }
166
167 sub read_file {
168 my ($file, @args) = @_;
169
170 my $fh = open_file($file, '<', @args);
171 local $/;
172 my $out = <$fh>;
173 close_file($fh, $file);
174
175 return $out;
176 }
177
178 sub write_file {
179 my ($file, @content) = @_;
180
181 my $fh = open_file($file, '>');
182 print $fh @content;
183 close_file($fh, $file);
184
185 return @content;
186 };
187
188 my %COMPRESSION = (
189 bz2 => {module => 'IO::Uncompress::Bunzip2', errors => \$IO::Uncompress::Bunzip2::Bunzip2Error},
190 gz => {module => 'IO::Uncompress::Gunzip', errors => \$IO::Uncompress::Gunzip::GunzipError},
191 );
192 sub open_file {
193 my ($file, $mode, %opts) = @_;
194 $mode ||= '<';
195
196 unless ($opts{no_decompress}) {
197 if (my $ext = $opts{ext}) {
198 $opts{compression} //= $COMPRESSION{$ext} or die "Unknown compression: $ext";
199 }
200
201 if ($file =~ m/\.(gz|bz2)$/i) {
202 my $ext = lc($1);
203 $opts{compression} //= $COMPRESSION{$ext} or die "Unknown compression: $ext";
204 }
205
206 if ($mode eq '<' && $opts{compression}) {
207 my $spec = $opts{compression};
208 my $mod = $spec->{module};
209 require(mod2file($mod));
210
211 my $fh = $mod->new($file) or die "Could not open file '$file' ($mode): ${$spec->{errors}}";
212 return $fh;
213 }
214 }
215
216 open(my $fh, $mode, $file) or confess "Could not open file '$file' ($mode): $!";
217 return $fh;
218 }
219
220 sub maybe_open_file {
221 my ($file, $mode) = @_;
222 return undef unless -f $file;
223 return open_file($file, $mode);
224 }
225
226 sub close_file {
227 my ($fh, $name) = @_;
228 return if close($fh);
229 confess "Could not close file: $!" unless $name;
230 confess "Could not close file '$name': $!";
231 }
232
233 sub write_file_atomic {
234 my ($file, @content) = @_;
235
236 my $pend = "$file.pend";
237
238 my ($ok, $err) = try_sig_mask {
239 write_file($pend, @content);
240 my ($ren_ok, $ren_err) = do_rename($pend, $file);
241 die "$pend -> $file: $ren_err" unless $ren_ok;
242 };
243
244 die $err unless $ok;
245
246 return @content;
247 }
248
249 sub lock_file {
250 my ($file, $mode) = @_;
251
252 my $fh;
253 if (ref $file) {
254 $fh = $file;
255 }
256 else {
257 open($fh, $mode // '>>', $file) or die "Could not open file '$file': $!";
258 }
259
260 for (1 .. 21) {
261 flock($fh, LOCK_EX) and last;
262 die "Could not lock file (try $_): $!" if $_ >= 20;
263 next if $!{EINTR} || $!{ERESTART};
264 die "Could not lock file: $!";
265 }
266
267 return $fh;
268 }
269
270 sub unlock_file {
271 my ($fh) = @_;
272 for (1 .. 21) {
273 flock($fh, LOCK_UN) and last;
274 die "Could not unlock file (try $_): $!" if $_ >= 20;
275 next if $!{EINTR} || $!{ERESTART};
276 die "Could not unlock file: $!";
277 }
278
279 return $fh;
280 }
281
282 sub clean_path {
283 my ( $path, $absolute ) = @_;
284
285 $absolute //= 1;
286 $path = realpath($path) // $path if $absolute;
287
288 return File::Spec->rel2abs($path);
289 }
290
291 sub mod2file {
292 my ($mod) = @_;
293 confess "No module name provided" unless $mod;
294 my $file = $mod;
295 $file =~ s{::}{/}g;
296 $file .= ".pm";
297 return $file;
298 }
299
300 sub file2mod {
301 my $file = shift;
302 my $mod = $file;
303 $mod =~ s{/}{::}g;
304 $mod =~ s/\..*$//;
305 return $mod;
306 }
307
308
309 sub find_libraries {
310 my ($search, @paths) = @_;
311 my @parts = grep $_, split /::(\*)?/, $search;
312
313 # Skip @INC hook refs; canonpath would stringify them to bogus paths.
314 @paths = grep { !ref($_) } @INC unless @paths;
315
316 @paths = map { File::Spec->canonpath($_) } @paths;
317
318 my %prefixes = map {$_ => 1} @paths;
319
320 my @found;
321 my @bases = ([map { [$_ => length($_)] } @paths]);
322 while (my $set = shift @bases) {
323 my $new_base = [];
324 my $part = shift @parts;
325
326 for my $base (@$set) {
327 my ($dir, $prefix) = @$base;
328 if ($part ne '*') {
329 my $path = File::Spec->catdir($dir, $part);
330 if (@parts) {
331 push @$new_base => [$path, $prefix] if -d $path;
332 }
333 elsif (-f "$path.pm") {
334 push @found => ["$path.pm", $prefix];
335 }
336
337 next;
338 }
339
340 opendir(my $dh, $dir) or next;
341 for my $item (readdir($dh)) {
342 next if $item =~ m/^\./;
343 my $path = File::Spec->catdir($dir, $item);
344 if (@parts) {
345 # Sometimes @INC dirs are nested in eachother.
346 next if $prefixes{$path};
347
348 push @$new_base => [$path, $prefix] if -d $path;
349 next;
350 }
351
352 next unless -f $path && $path =~ m/\.pm$/;
353 push @found => [$path, $prefix];
354 }
355 }
356
357 push @bases => $new_base if @$new_base;
358 }
359
360 my %out;
361 for my $found (@found) {
362 my ($path, $prefix) = @$found;
363
364 my @file_parts = File::Spec->splitdir(substr($path, $prefix));
365 shift @file_parts if $file_parts[0] eq '';
366
367 my $file = join '/' => @file_parts;
368 $file_parts[-1] = substr($file_parts[-1], 0, -3);
369 my $module = join '::' => @file_parts;
370
371 $out{$module} //= $file;
372 }
373
374 return \%out;
375 }
376
377 1;
378
379 __END__
380
381
382 =pod
383
384 =encoding UTF-8
385
386 =head1 NAME
387
388 Test2::Harness::Util - General utility functions.
389
390 =head1 DESCRIPTION
391
392 Utility functions used throughout the harness. Nothing here is specific to any
393 one part of it; the sections below group the functions by the kind of work
394 they do.
395
396 =head1 METHODS
397
398 =head2 MISC
399
400 =over 4
401
402 =item apply_encoding($fh, $enc)
403
404 Apply the specified encoding to the filehandle.
405
406 B<Justification>:
407 L<PERLBUG 31923|https://rt.perl.org/Public/Bug/Display.html?id=31923>
408 If utf8 is requested we use ':utf8' instead of ':encoding(utf8)' in
409 order to avoid the thread segfault.
410
411 This is a reusable implementation of this:
412
413 sub apply_encoding {
414 my ($fh, $enc) = @_;
415 return unless $enc;
416 return binmode($fh, ":utf8") if $enc =~ m/^utf-?8$/i;
417 binmode($fh, ":encoding($enc)");
418 }
419
420 =item $clean = clean_path($path)
421
422 Take a file path and clean it up to a minimal absolute path if possible. Always
423 returns a path, but if it cannot be cleaned up it is unchanged.
424
425 =item $hashref = find_libraries($search)
426
427 =item $hashref = find_libraries($search, @paths)
428
429 C<@INC> is used if no C<@paths> are provided.
430
431 C<$search> should be a module name with C<*> wildcards replacing sections.
432
433 find_libraries('Foo::*::Baz')
434 find_libraries('*::Bar::Baz')
435 find_libraries('Foo::Bar::*')
436
437 These all look for modules matching the search, this is a good way to find
438 plugins, or similar patterns.
439
440 The result is a hashref of C<< { $module => $path } >>. If a module exists in
441 more than 1 search path the first is used.
442
443 =item $mod = fqmod($prefix, $mod)
444
445 This will automatically add C<$prefix> to C<$mod> with C<'::'> to join them. If
446 C<$mod> starts with the C<'+'> character the character will be removed and the
447 result returned without prepending C<$prefix>.
448
449 =item hub_truth
450
451 This is an internal implementation detail, do not use it.
452
453 =item $hashref = parse_exit($?)
454
455 This parses the exit value as typically stored in C<$?>.
456
457 Resulting hash:
458
459 {
460 sig => ($? & 127), # Signal value if the exit was caused by a signal
461 err => ($? >> 8), # Actual exit code, if any.
462 dmp => ($? & 128), # Was there a core dump?
463 all => $?, # Original exit value, unchanged
464 }
465
466
467 =item @list = process_includes(%PARAMS)
468
469 This method will build up a list of include dirs fit for C<@INC>. The returned
470 list should contain only unique values, in proper order.
471
472 Params:
473
474 =over 4
475
476 =item list => \@START
477
478 Paths to start the new list.
479
480 Optional.
481
482 =item ch_dir => $path
483
484 Prefix to prepend to all paths in the C<list> param. No effect without an
485 initial list.
486
487 =item include_current => $bool
488
489 This will add all paths from C<@INC> to the output, after the initial list.
490 Hook entries in C<@INC> - coderefs, arrayrefs, and blessed objects - are not
491 paths and are skipped. C<'.'> is skipped as well; use C<include_dot> to add it.
492
493 =item clean => $bool
494
495 If included all paths except C<'.'> will be cleaned using C<clean_path()>.
496
497 =item include_dot => $bool
498
499 If true C<'.'> will be appended to the end of the output.
500
501 B<Note> this is the only way to get C<'.'> into the output. It is dropped from
502 the initial list and from C<@INC> alike.
503
504 =back
505
506 =back
507
508 =head2 FOR DEALING WITH MODULE <-> FILE CONVERSION
509
510 These convert between module names like C<Foo::Bar> and filenames like
511 C<Foo/Bar.pm>.
512
513 =over 4
514
515 =item $file = mod2file($mod)
516
517 =item $mod = file2mod($file)
518
519 =back
520
521 =head2 FOR READING/WRITING FILES
522
523 =over 4
524
525 =item $fh = open_file($path, $mode)
526
527 =item $fh = open_file($path)
528
529 If no mode is provided C<< '<' >> is assumed.
530
531 This will open the file at C<$path> and return a filehandle.
532
533 An exception will be thrown if the file cannot be opened.
534
535 B<NOTE:> This will automatically use L<IO::Uncompress::Bunzip2> or
536 L<IO::Uncompress::Gunzip> to uncompress the file if it has a .bz2 or .gz
537 extension.
538
539 =item $text = read_file($file)
540
541 This will open the file at C<$path> and return all its contents.
542
543 An exception will be thrown if the file cannot be opened.
544
545 B<NOTE:> This will automatically use L<IO::Uncompress::Bunzip2> or
546 L<IO::Uncompress::Gunzip> to uncompress the file if it has a .bz2 or .gz
547 extension.
548
549 =item $fh = maybe_open_file($path)
550
551 =item $fh = maybe_open_file($path, $mode)
552
553 If no mode is provided C<< '<' >> is assumed.
554
555 This will open the file at C<$path> and return a filehandle.
556
557 C<undef> is returned if the file cannot be opened.
558
559 B<NOTE:> This will automatically use L<IO::Uncompress::Bunzip2> or
560 L<IO::Uncompress::Gunzip> to uncompress the file if it has a .bz2 or .gz
561 extension.
562
563 =item $text = maybe_read_file($path)
564
565 This will open the file at C<$path> and return all its contents.
566
567 This will return C<undef> if the file cannot be opened.
568
569 B<NOTE:> This will automatically use L<IO::Uncompress::Bunzip2> or
570 L<IO::Uncompress::Gunzip> to uncompress the file if it has a .bz2 or .gz
571 extension.
572
573 =item @content = write_file($path, @content)
574
575 Write content to the specified file. This will open the file with mode
576 C<< '>' >>, write the content, then close the file.
577
578 An exception will be thrown if any part fails.
579
580 =item @content = write_file_atomic($path, @content)
581
582 This will open a temporary file, write the content, close the file, then rename
583 the file to the desired C<$path>. This is essentially an atomic write in that
584 C<$file> will not exist until all content is written, preventing other
585 processes from doing a partial read while C<@content> is being written.
586
587 =back
588
589 =head1 SOURCE
590
591 The source code repository for Test2-Harness can be found at
592 F<http://github.com/Test-More/Test2-Harness/>.
593
594 =head1 MAINTAINERS
595
596 =over 4
597
598 =item Chad Granum E<lt>[email protected]<gt>
599
600 =back
601
602 =head1 AUTHORS
603
604 =over 4
605
606 =item Chad Granum E<lt>[email protected]<gt>
607
608 =back
609
610 =head1 COPYRIGHT
611
612 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
613
614 This program is free software; you can redistribute it and/or
615 modify it under the same terms as Perl itself.
616
617 See F<http://dev.perl.org/licenses/>
618
619 =cut