Debian Codegraph @

lib/App/Yath/Util.pm

raw
1 package App::Yath::Util;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use File::Spec;
8 use Sys::Hostname qw/hostname/;
9
10 use Test2::Harness::Util qw/clean_path/;
11 use Test2::Harness::Util::File::JSON;
12
13 use Cwd qw/realpath/;
14 use Importer Importer => 'import';
15 use Config qw/%Config/;
16 use Carp qw/croak/;
17
18 our @EXPORT_OK = qw{
19 find_pfile
20 find_in_updir
21 is_generated_test_pl
22 fit_to_width
23 isolate_stdout
24 find_yath
25 };
26
27 my @CONFIG_SCRIPT_KEYS = qw{
28 bin binexp initialinstalllocation installbin installscript
29 installsitebin installsitescript installusrbinperl installvendorbin
30 scriptdir scriptdirexp sitebin sitebinexp sitescript sitescriptexp
31 vendorbin vendorbinexp
32 };
33
34 sub find_yath {
35 return $App::Yath::Script::SCRIPT if defined $App::Yath::Script::SCRIPT;
36
37 my @searched;
38
39 my $script = _find_yath(\@searched);
40 return $App::Yath::Script::SCRIPT = $script if $script;
41
42 die _find_yath_error(\@searched);
43 }
44
45 sub _find_yath {
46 my ($searched) = @_;
47
48 for my $candidate (_yath_scripts()) {
49 my ($script, $need_exec) = @$candidate;
50
51 push @$searched => $script;
52 next unless -f $script && -r _;
53 next if $need_exec && !-x _;
54
55 return clean_path($script);
56 }
57
58 return undef;
59 }
60
61 # Callers run the script as an argument to perl, so it only needs to be
62 # readable. PATH is the exception: a yath without the exec bit is not the
63 # command someone typing 'yath' would get.
64 sub _yath_scripts {
65 my @scripts;
66
67 # Set by the yath script itself, so it names the script running this
68 # process tree. Under a yath run this is also how a checkout's own script
69 # gets here: App::Yath::Script re-execs into an executable './scripts/yath'
70 # when the current directory has one, and that script sets this to itself.
71 push @scripts => [$ENV{YATH_SCRIPT}, 0] if $ENV{YATH_SCRIPT};
72
73 push @scripts => map { [File::Spec->catfile($_, 'yath'), 0] } _yath_script_dirs();
74 push @scripts => map { [File::Spec->catfile($_, 'yath'), 1] } File::Spec->path();
75
76 my %seen;
77 return grep { !$seen{$_->[0]}++ } @scripts;
78 }
79
80 sub _yath_script_dirs {
81 my @dirs;
82
83 # An uninstalled dist is never in a Config path, so it comes first.
84 push @dirs => _yath_dirs_from_inc(qr{^(.*)[/\\]blib[/\\](?:lib|arch)$}, 'blib', 'script');
85
86 push @dirs => grep { $_ } @Config{@CONFIG_SCRIPT_KEYS};
87
88 # A guess at the layout, so it comes after anything authoritative.
89 push @dirs => _yath_dirs_from_inc(qr{^(.*)[/\\]lib[/\\]perl5(?:[/\\][^/\\]+)*$}, 'bin');
90
91 my %seen;
92 return grep { $_ && !$seen{$_}++ } @dirs;
93 }
94
95 # The script may live next to the libs it belongs to without ever being
96 # installed. CPAN smokers do this: they add each prerequisite's uninstalled
97 # '<build>/blib/lib' to PERL5LIB, leaving the script in '<build>/blib/script'.
98 # local::lib and 'cpanm -l' trees pair '<base>/lib/perl5' with '<base>/bin'.
99 sub _yath_dirs_from_inc {
100 my ($pattern, @subdirs) = @_;
101
102 my @dirs;
103 for my $inc (@INC) {
104 next if ref $inc;
105 next unless $inc =~ $pattern;
106
107 push @dirs => File::Spec->catdir($1, @subdirs);
108 }
109
110 return @dirs;
111 }
112
113 # Failing to find the script is nearly always an environment we have not
114 # taught find_yath about yet. Dump everything needed to teach it.
115 sub _find_yath_error {
116 my ($searched) = @_;
117
118 my $msg = "Could not find the yath script.\n";
119
120 $msg .= "Searched:\n";
121 $msg .= " $_\n" for @$searched;
122
123 my @mods = grep { -f File::Spec->catfile($_, 'App', 'Yath', 'Script.pm') } grep { !ref $_ } @INC;
124 $msg .= "App::Yath::Script loaded from: " . ($INC{'App/Yath/Script.pm'} // '(not loaded)') . "\n";
125 $msg .= "App::Yath::Script found in: " . (@mods ? join(', ' => @mods) : '(nowhere in @INC)') . "\n";
126
127 # Some candidates are relative to the current directory, so it is needed to
128 # make sense of them.
129 $msg .= "Cwd: " . clean_path('.') . "\n";
130 $msg .= "PATH: " . ($ENV{PATH} // '(not set)') . "\n";
131 $msg .= "PERL5LIB: " . ($ENV{PERL5LIB} // '(not set)') . "\n";
132
133 $msg .= "\@INC:\n";
134 $msg .= " $_\n" for grep { !ref $_ } @INC;
135
136 $msg .= "Please report this at https://github.com/Test-More/Test2-Harness/issues along with the output above.\n";
137
138 return $msg;
139 }
140
141 sub isolate_stdout {
142 # Make $fh point at STDOUT, it is our primary output
143 open(my $fh, '>&', STDOUT) or die "Could not clone STDOUT: $!";
144 select $fh;
145 $| = 1;
146
147 # re-open STDOUT redirected to STDERR
148 open(STDOUT, '>&', STDERR) or die "Could not redirect STDOUT to STDERR: $!";
149 select STDOUT;
150 $| = 1;
151
152 # Yes, we want to keep STDERR selected
153 select STDERR;
154 $| = 1;
155
156 return $fh;
157 }
158
159 sub is_generated_test_pl {
160 my ($file) = @_;
161
162 open(my $fh, '<', $file) or die "Could not open '$file': $!";
163
164 my $count = 0;
165 while (my $line = <$fh>) {
166 last if $count++ > 5;
167 next unless $line =~ m/^# THIS IS A GENERATED YATH RUNNER TEST$/;
168 return 1;
169 }
170
171 return 0;
172 }
173
174
175 sub find_in_updir {
176 my $path = shift;
177 return clean_path($path) if -f $path;
178
179 my %seen;
180 while(1) {
181 $path = File::Spec->catdir('..', $path);
182 my $check = eval { realpath(File::Spec->rel2abs($path)) };
183 last unless $check;
184 last if $seen{$check}++;
185 return $check if -f $check;
186 }
187
188 return;
189 }
190
191 sub _find_pfile {
192 my ($settings, %params) = @_;
193
194 croak "Settings is a required argument" unless $settings;
195
196 # First do the entire search without vivify
197 if ($params{vivify}) {
198 my $found = find_pfile($settings, %params, vivify => 0);
199 return $found if $found;
200 }
201
202 my $yath = $settings->harness;
203
204 if (my $pfile = $yath->persist_file) {
205 return $pfile if -f $pfile || $params{vivify};
206
207 return; # Specified, but not found and no vivify
208 }
209
210 my $basename = "yath-persist.json";
211 my $user = $ENV{USER};
212 my $hostname = hostname();
213 my $project = $yath->project;
214
215 my @names = ($basename);
216 @names = (@names, map { "$project-$_" } @names) if $project;
217 @names = (@names, map { "$hostname-$_" } @names) if $hostname;
218 @names = (@names, map { "$user-$_" } @names) if $user;
219 @names = reverse map { ".$_" } @names;
220
221 my $set_dir = $yath->persist_dir // $ENV{YATH_PERSISTENCE_DIR};
222 my $dir = $set_dir // $ENV{TMPDIR} // $ENV{TEMPDIR} // File::Spec->tmpdir;
223
224 # If a dir was specified, or if the current dir is not writable then we must use $dir/$name
225 if ($project || $set_dir || !-w '.') {
226 for my $name (@names) {
227 my $pfile = clean_path(File::Spec->catfile($dir, $name));
228 return $pfile if -f $pfile;
229 }
230
231 return clean_path(File::Spec->catfile($dir, $names[0])) if $params{vivify};
232 return; # Not found
233 }
234
235 # Fall back to using the current dir (which must be writable)
236 for my $name (@names) {
237 my $pfile = find_in_updir($name);
238 return $pfile if $pfile && -f $pfile;
239 }
240
241 # Creating it here!
242 return clean_path(File::Spec->catfile('.', $names[0])) if $params{vivify};
243
244 # Nope, nothing.
245 return;
246 }
247
248 sub fit_to_width {
249 my ($width, $join, $text) = @_;
250
251 my @parts = ref($text) ? @$text : split /\s+/, $text;
252
253 my @out;
254
255 my $line = "";
256 for my $part (@parts) {
257 my $new = $line ? "$line$join$part" : $part;
258
259 if ($line && length($new) > $width) {
260 push @out => $line;
261 $line = $part;
262 }
263 else {
264 $line = $new;
265 }
266 }
267 push @out => $line if $line;
268
269 return join "\n" => @out;
270 }
271
272 my $SEEN_ERROR = 0;
273 sub find_pfile {
274 my ($settings, %params) = @_;
275 my $pfile = _find_pfile($settings, %params) or return;
276
277 return $pfile unless -e $pfile;
278 return $pfile if $params{no_checks};
279 return $pfile if $SEEN_ERROR;
280
281 my $data = Test2::Harness::Util::File::JSON->new(name => $pfile)->read();
282
283 $data->{version} //= '';
284 $data->{hostname} //= '';
285 $data->{user} //= '';
286 $data->{pid} //= '';
287 $data->{dir} //= '';
288
289 my $hostname = hostname();
290 my $user = $ENV{USER};
291
292 my @bad;
293
294 push @bad => "** Version mismatch, persistent runner is version $data->{version}, current is version $VERSION. **"
295 if $data->{version} ne $VERSION;
296
297 push @bad => "** Hostname mismatch, persistent runner hostname is '$data->{hostname}', current hostname is '$hostname'. **"
298 if $data->{hostname} ne $hostname;
299
300 push @bad => "** User mismatch, persistent runner user is '$data->{user}', current user is '$user'. **"
301 if $data->{user} ne $user;
302
303 push @bad => "** Workdir missing, persistent runner is supposed to be at '$data->{dir}', but it does not exist. **"
304 unless -d $data->{dir};
305
306 push @bad => "** PID not running, persistent runner is supposed to be running with PID '$data->{pid}', but it is not. **"
307 unless kill(0, $data->{pid});
308
309 return $pfile unless @bad;
310
311 my $break = ('=' x 120) . "\n";
312 my $msg = join "\n" => $break, @bad, <<" EOT", $break;
313
314 Errors like this usually indicate that the persistent runner has gone away.
315 Maybe the system was shut down improperly, or maybe the process was killed too
316 quickly to clean up after itself.
317
318 Here is the information indicated by the persistence file:
319 Runner PID: $data->{pid}
320 Runner Vers: $data->{version}
321 Runner user: $data->{user}
322 Runner host: $data->{hostname}
323 Working dir: $data->{dir}
324
325 If the persistent runner is truly gone you should delete the following file to
326 continue:
327
328 $pfile
329 EOT
330
331 $SEEN_ERROR = 1;
332 die $msg unless $params{no_fatal};
333 warn $msg unless $params{no_warn};
334 return $pfile;
335 }
336
337 1;
338
339 __END__
340
341 =pod
342
343 =encoding UTF-8
344
345 =head1 NAME
346
347 App::Yath::Util - General utilities for yath that do not fit anywhere else.
348
349 =head1 DESCRIPTION
350
351 This package exports several tools used throughout yath that did not fit into
352 any other package.
353
354 =head1 SYNOPSIS
355
356 use App::Yath::Util qw{
357 find_pfile
358 find_in_updir
359 is_generated_test_pl
360 fit_to_width
361 isolate_stdout
362 find_yath
363 };
364
365 =head1 EXPORTS
366
367 Note that nothing is exported by default, you must request each function to
368 import.
369
370 =over 4
371
372 =item $path_to_pfile = find_pfile($settings, %params)
373
374 The first argument must be an instance of L<Test2::Harness::Settings>.
375
376 Currently the only supported param is C<vivify>, when set to true the pfile
377 will be created if one does not already exist.
378
379 The pfile is a file that tells yath that a persistent runner is active, and how
380 to communicate with it.
381
382 =item $path_to_file = find_in_updir($file_name)
383
384 Look for C<$file_name> in the current directory or any parent directory.
385
386 =item $bool = is_generated_test_pl($path_to_test_file)
387
388 Check if the specified test file was generated by the C<yath init> command.
389
390 =item fit_to_width($width, $join, $text)
391
392 This will split the C<$text> on space, and then recombine it using C<$join>
393 inserting newlines as necessary in an attempt to fit the text into C<$width>
394 horizontal characters. If any words are larger than C<$width> they will not be
395 split and text-wrapping may occur if used for terminal display.
396
397 =item $stdout = isolate_stdout()
398
399 This will close STDOUT and reopen it to point at STDERR. The result of this is
400 that any print statement that does not specify a filehandle will print to
401 STDERR instead of STDOUT, in addition any print directly to STDOUT will instead
402 go to STDERR. A filehandle to the real STDOUT is returned for you to use when
403 you actually want to write to STDOUT.
404
405 This is used by some yath processes that need to print structured data to
406 STDOUT without letting any third part modules they may load write to the real
407 STDOUT.
408
409 =item $path_to_script = find_yath()
410
411 This will attempt to find the C<yath> command line script. When possible this
412 will return the path that was used to launch yath. If
413 C<$App::Yath::Script::SCRIPT> is not set the following are searched, in order:
414
415 =over 8
416
417 =item The C<YATH_SCRIPT> environment variable
418
419 The yath script sets this, so it identifies the script that launched the
420 current process tree. Under a yath run this also covers a checkout's own
421 script: L<App::Yath::Script> re-execs into an executable C<./scripts/yath> of
422 its own accord when the current directory has one, and the script it re-execs
423 into sets this variable to itself.
424
425 =item C<< <base>/blib/script >> for any C<< <base>/blib/lib >> or C<< <base>/blib/arch >> in C<@INC>
426
427 This finds the script when the L<App::Yath::Script> distribution is being used
428 uninstalled from its build directory, as CPAN smokers do.
429
430 =item The paths specified in the L<Config> module
431
432 =item C<< <base>/bin >> for any C<< <base>/lib/perl5 >> in C<@INC>
433
434 Anything after C<lib/perl5> is ignored, so
435 C<< <base>/lib/perl5/5.36.0/x86_64-linux >> also gives C<< <base>/bin >>. This
436 finds the script in a L<local::lib> or C<cpanm -l> tree.
437
438 =item The C<PATH> environment variable
439
440 =back
441
442 Every candidate but the C<PATH> ones only needs to be readable, because the
443 script is run as an argument to perl rather than executed. A candidate found
444 via C<PATH> must also be executable.
445
446 This will throw an exception if the script cannot be found. The exception lists
447 every path that was checked, along with the current directory, C<@INC>, C<PATH>,
448 and C<PERL5LIB>, so the missing case can be reported.
449
450 Note: The result is cached so that subsequent calls will return the same path
451 even if something installs a new yath script in another location that would
452 otherwise be found first. This guarantees that a single process will not switch
453 scripts.
454
455 =back
456
457 =head1 SOURCE
458
459 The source code repository for Test2-Harness can be found at
460 F<http://github.com/Test-More/Test2-Harness/>.
461
462 =head1 MAINTAINERS
463
464 =over 4
465
466 =item Chad Granum E<lt>[email protected]<gt>
467
468 =back
469
470 =head1 AUTHORS
471
472 =over 4
473
474 =item Chad Granum E<lt>[email protected]<gt>
475
476 =back
477
478 =head1 COPYRIGHT
479
480 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
481
482 This program is free software; you can redistribute it and/or
483 modify it under the same terms as Perl itself.
484
485 See F<http://dev.perl.org/licenses/>
486
487 =cut