blib/lib/SimpleFlow.pm

filter: Statementstmt 83.7% 1432 / 1710 Branchbran 74.1% 660 / 890 Conditioncond 69.4% 438 / 631 MC/DCmcdc 54.3% 195 / 359 Subroutinesub 76.8% 93 / 121 Podpod 42.8% 3 / 7 totaltotal 75.8% 2821 / 3718 CC 1343 SCAR 42.9
CC
1343
Cov
78%
task
194.3
task
194.3
_run_forked
108.4
CRAP 72.9
↑ Summary
1 # ABSTRACT: SimpleFlow - easy, simple workflow manager (and logger); for keeping track of and debugging large and complex shell command workflows
2 package SimpleFlow;
3 # NB: the package statement comes first on purpose. Until 0.16 the "use"
4 # lines below sat above it, so DDP's "p"/"np" and Cwd's "getcwd" were
5 # imported into main:: -- every program that loaded SimpleFlow silently
6 # acquired three subs it never asked for, and could collide with its own.
7 447 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 447 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 447 require 5.010;
10 447 ▶use feature 'say';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # While this file compiles, perl names each anonymous sub for where it was
13 # written -- SimpleFlow::__ANON__[.../SimpleFlow.pm:123] rather than plain
14 # SimpleFlow::__ANON__ -- so that a stack trace through one of SimpleFlow's
15 # closures says which. These are the $^P bits Devel::Confess's import() sets
16 # (0x100, informative names for evals; 0x200, for anonymous subs; perlvar,
17 # "$^P"), for the whole program and for good. Until 0.19 the module imported
18 # Devel::Confess, and so set them for its caller too; now it sets them for
19 # its own code only, and the BEGIN block just above "1;" puts back whatever
20 # was there before.
21 447 our $CALLER_PERLDB_FLAGS;
22 447 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
23 447 $CALLER_PERLDB_FLAGS = $^P;
24 447 $^P |= 0x100 | 0x200;
25 }
26  
27 # Quoted, not the bare number: a numeric version is stringified through %g,
28 # so 0.20 would become "0.2" and compare as older than "0.15" on CPAN.
29 447 our $VERSION = '0.1961';
30  
31 447 ▶use Cwd 'getcwd';
Subroutine BEGIN: called CC=1 SCAR=0.0
32 447 ▶use Digest::MD5 'md5_hex';
Subroutine BEGIN: called CC=1 SCAR=0.0
33 447 ▶use DDP {output => 'STDOUT', array_max => 10, show_memsize => 1};
Subroutine BEGIN: called CC=1 SCAR=0.0
34 447 ▶use Devel::Confess (); # loaded, not imported: task() enables it for itself; see _confess_here
Subroutine BEGIN: called CC=1 SCAR=0.0
35 447 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
36 447 ▶use Fcntl ();
Subroutine BEGIN: called CC=1 SCAR=0.0
37 447 ▶use File::Find ();
Subroutine BEGIN: called CC=1 SCAR=0.0
38 447 ▶use File::Path ();
Subroutine BEGIN: called CC=1 SCAR=0.0
39 447 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 447 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
41 447 ▶use List::Util qw(max min sum);
Subroutine BEGIN: called CC=1 SCAR=0.0
42 447 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
43 447 ▶use Scalar::Util 'openhandle';
Subroutine BEGIN: called CC=1 SCAR=0.0
44 447 ▶use Storable ();
Subroutine BEGIN: called CC=1 SCAR=0.0
45 447 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
46  
47 447 our @EXPORT = qw(say2 task);
48 # not exported unless asked for, so that a program loading SimpleFlow does not
49 # acquire two more common names
50 447 our @EXPORT_OK = (@EXPORT, 'parallel', 'report');
51  
52 # Defaults for every task() in the program, for any key the call itself leaves
53 # undefined: local %SimpleFlow::DEFAULTS = ('dry_run' => 1) dry-runs a whole
54 # pipeline from one line. "env" and "env_secret" are merged with a task's own
55 # rather than replaced by it. Keys that name one particular step are refused;
56 # see @PER_STEP_KEYS in task().
57 447 our %DEFAULTS;
58  
59 # [file, line] for task() to report as its caller, instead of its real one;
60 # undef = its real one. parallel() sets it, since each task it runs is called
61 # from parallel() itself, in a child, and the caller wants its own line.
62 447 our $CALLER;
63  
64 # Runs a closure when it goes out of scope, however the scope is left: return,
65 # die, or the end of the block. task() uses it to go back to the caller's
66 # directory after "dir". The package name is on its own line so that PAUSE and
67 # MetaProvides do not index it: it is not API.
68 package # not indexed
69 SimpleFlow::Guard;
70 1182 ▶sub new {
Subroutine new: called CC=1 SCAR=1.2
71 0 ▶ my ($class, $code) = @_;
Subroutine new: not called CC=1 SCAR=1.2
72 0 return bless { code => $code }, $class;
73 }
74 1092 ▶sub DESTROY {
Subroutine DESTROY: called CC=1 SCAR=1.2
75 0 ▶ my $self = shift;
Subroutine DESTROY: not called CC=1 SCAR=1.2
76 0 $self->{code}->();
77 0 return;
78 }
79 package SimpleFlow;
80  
81 # Windows portability: the legacy Windows console (cmd.exe) prints raw ANSI
82 # escape sequences as garbage. Disable colouring there unless a terminal that
83 # understands ANSI is in use (Windows Terminal, ConEmu, ANSICON). Unix and
84 # modern Windows terminals are left untouched.
85 447 ▶BEGIN {
Subroutine BEGIN: called CC=5 SCAR=23.0
86 $ENV{ANSI_COLORS_DISABLED} = 1
87 if $^O eq 'MSWin32'
88 && !$ENV{WT_SESSION} # Windows Terminal
89 && !$ENV{ConEmuANSI} # ConEmu
90 447 ▶ && !$ENV{ANSICON}; # ANSICON
Branch: 1 branch
BranchTrueFalseTotal
if $^O eq "MSWin32" and not $ENV{"WT_SESSION"} and not $ENV{"ConEmuANSI"} and not $ENV{"ANSICON"} 0 447 447
Condition33%3/9
$^O eq "MSWin32" and not $ENV{"WT_SESSION"} and not $ENV{"ConEmuANSI"} and not $ENV{"ANSICON"}
!ll&&!rl&&r
44700
$^O eq "MSWin32" and not $ENV{"WT_SESSION"} and not $ENV{"ConEmuANSI"}
!ll&&!rl&&r
44700
$^O eq "MSWin32" and not $ENV{"WT_SESSION"}
!ll&&!rl&&r
44700
MC/DC0%0/4
$^O eq "MSWin32" and not $ENV{"WT_SESSION"} and not $ENV{"ConEmuANSI"} and not $ENV{"ANSICON"}
$^O eq "MSWin32" not $ENV{"WT_SESSION"} not $ENV{"ConEmuANSI"} not $ENV{"ANSICON"}
Truth table20%1/5
A and not(B) and not(C) and not(D)
A= $^O eq "MSWin32"B= not $ENV{"WT_SESSION"}C= not $ENV{"ConEmuANSI"}D= not $ENV{"ANSICON"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
91 }
92  
93 # Ceiling on the length of any one field of the record when it is printed.
94 # Nothing was capped at all before 0.16, so a chatty command's entire stdout
95 # was echoed: a measured 3 MB capture wrote 3,002,832 bytes to the terminal
96 # and the same again to the log. 4096 is roughly 50 lines of an 80-column
97 # terminal -- enough to read a typical error message in full. What was
98 # dropped is marked, so a clipped field is never mistaken for a short one.
99 447 my $STRING_MAX_CAP = 4096;
100  
101 # Minimal drop-in for Term::ANSIColor's colored(\@attrs, $text): map the few
102 # colour names we use to SGR codes so Perl core alone can colour the output.
103 # Honours $ENV{ANSI_COLORS_DISABLED} at call time (set above and by the caller).
104 447 my %ANSI_CODE = (
105 reset => 0,
106 black => 30,
107 red => 31,
108 green => 32,
109 blue => 34,
110 on_black => 40,
111 on_green => 42,
112 on_bright_red => 101,
113 );
114 5390 ▶sub colored {
Subroutine colored: called CC=4 SCAR=20.7
Pod undocumented
115 0 ▶ my ($attrs, $text) = @_;
Subroutine colored: not called CC=4 SCAR=20.7
Pod undocumented
116 0 ▶ return $text if $ENV{ANSI_COLORS_DISABLED};
Branch: 2 branches
BranchTrueFalseTotal
if $ENV{"ANSI_COLORS_DISABLED"} 0 5390 5390
if $ENV{"ANSI_COLORS_DISABLED"} 0 0 0
117 my @codes = map {
118 0 ▶ $ANSI_CODE{$_} // die "unknown colour attribute '$_'"
Condition25%1/4
$ANSI_CODE{$_} // die("unknown colour attribute '${_}'")
l!l
107800
$ANSI_CODE{$_} // die("unknown colour attribute '${_}'")
l!l
00
MC/DC0%0/1
$ANSI_CODE{$_} // die("unknown colour attribute '${_}'")
$ANSI_CODE{$_}
MC/DC0%0/1
$ANSI_CODE{$_} // die("unknown colour attribute '${_}'")
$ANSI_CODE{$_}
Truth table50%1/2
A
A= $ANSI_CODE{$_}
Aresult
11
00
Truth table0%0/2
A
A= $ANSI_CODE{$_}
Aresult
11
00
119 } split ' ', join ' ', @$attrs;
120 0 ▶ return $text unless @codes;
Branch: 2 branches
BranchTrueFalseTotal
unless @codes 0 5390 5390
unless @codes 0 0 0
121 0 return "\e[" . join(';', @codes) . 'm' . $text . "\e[0m";
122 }
123  
124 96 ▶sub say2 { # say to both command line and log file
Subroutine say2: called CC=3 SCAR=14.2
Pod documented
125 # Devel::Confess for this call only, as in task(): see _confess_here
126 0 ▶ local $SIG{__DIE__} = $SIG{__DIE__};
Subroutine say2: not called CC=3 SCAR=14.2
Pod documented
127 0 local $SIG{__WARN__} = $SIG{__WARN__};
128 0 local $Devel::Confess::OLD_SIG{__DIE__} = $Devel::Confess::OLD_SIG{__DIE__};
129 0 local $Devel::Confess::OLD_SIG{__WARN__} = $Devel::Confess::OLD_SIG{__WARN__};
130 0 local $Devel::Confess::OPTIONS{color} = $Devel::Confess::OPTIONS{color};
131 0 _confess_here();
132 0 my ($msg, $fh) = @_;
133 0 my $current_sub = (split(/::/,(caller(0))[3]))[-1]; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
134 0 my @c = caller;
135 0 ▶ $msg = '' if not defined $msg; # interpolating undef below would be fatal under "warnings FATAL => 'all'"
Branch: 2 branches
BranchTrueFalseTotal
unless defined $msg 22 74 96
unless defined $msg 0 0 0
136 0 ▶ if (not openhandle($fh)) {
Branch: 2 branches
BranchTrueFalseTotal
unless (&openhandle($fh)) 6 90 96
unless (&openhandle($fh)) 0 0 0
137 0 die "the filehandle given to $current_sub with \"$msg\" from $c[1] line $c[2] isn't actually a filehandle";
138 }
139 0 _autoflush($fh);
140 0 $msg = "\@ $c[1] line $c[2] $msg";
141 0 say $msg;
142 0 say $fh $msg;
143 0 return $msg;
144 }
145  
146 # Turn on autoflush for a log filehandle. Without it the record of the very
147 # task that killed the run is still sitting in stdio's buffer when the process
148 # dies: measured with a SIGKILL (the shape of an OOM kill or a scheduler
149 # eviction) part-way through a pipeline, a log that reached 862 bytes on a
150 # clean exit held only 139 bytes after the kill -- every line written after
151 # the last command started was lost, including that command's exit code,
152 # duration and captured output. select() is used rather than
153 # IO::Handle::autoflush so that nothing outside core is needed.
154 504 ▶sub _autoflush {
Subroutine _autoflush: called CC=1 SCAR=1.2
155 0 ▶ my $fh = shift;
Subroutine _autoflush: not called CC=1 SCAR=1.2
156 0 my $previously_selected = select $fh;
157 0 $| = 1;
158 0 select $previously_selected;
159 0 return;
160 }
161  
162 # A copy of a record with its over-long fields clipped to $STRING_MAX_CAP and
163 # the drop marked. Data::Printer's own "string_max" property does this job,
164 # and 0.16 left it to do it -- but string_max only arrived in Data::Printer
165 # 0.99_001 (2018), and every release before that ignores a property it does
166 # not recognize, in silence. A CPAN tester on Data::Printer 0.38 therefore had
167 # the whole of a 200,000-character capture printed to its terminal and copied
168 # into its log. Clipping here holds the ceiling on every version.
169 # The record the caller is handed is untouched: only the printed copy is
170 # clipped, so $t->{stdout} still has the full capture. The mark is
171 # Data::Printer's own wording, so the output does not change on the versions
172 # that were already capping it.
173 #
174 # The copy is built field by field, and an over-long field is never copied in
175 # full: "%clipped = %$r" followed by substr, as 0.17 did it, copied the whole
176 # of stdout and stderr first, and perls before 5.20 have no copy-on-write to
177 # make that cheap: on perl-5.10.1, clipping a record holding a 100 MB stdout
178 # raised peak RSS from 205 MB to 303 MB, for text that was then thrown away.
179 4782 ▶sub _clipped {
Subroutine _clipped: called CC=5 SCAR=21.8
180 0 ▶ my $r = shift;
Subroutine _clipped: not called CC=5 SCAR=21.8
181 0 my %clipped; # shallow: only the top-level fields are ever this long
182 0 foreach my $key (keys %$r) {
183 0 my $value = \$r->{$key};
184 0 ▶ my $dropped = ((defined $$value) && (ref $$value eq '')) # length undef is fatal here
Branch: 2 branches
BranchTrueFalseTotal
defined $$value && ref $$value eq '' ? : 187356 46336 233692
defined $$value && ref $$value eq '' ? : 0 0 0
Condition33%2/6
defined $$value and ref $$value eq ""
!ll&&!rl&&r
046336187356
defined $$value and ref $$value eq ""
!ll&&!rl&&r
000
MC/DC50%1/2
defined $$value and ref $$value eq ""
defined $$value ref $$value eq ""
MC/DC0%0/2
defined $$value and ref $$value eq ""
defined $$value ref $$value eq ""
Truth table66%2/3
A and B
A= defined $$valueB= ref $$value eq ""
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $$valueB= ref $$value eq ""
ABresult
0X0
100
111
185 ? length($$value) - $STRING_MAX_CAP
186 : 0;
187 0 ▶ $clipped{$key} = ($dropped > 0)
Branch: 2 branches
BranchTrueFalseTotal
$dropped > 0 ? : 4 233688 233692
$dropped > 0 ? : 0 0 0
188 ? substr($$value, 0, $STRING_MAX_CAP) . "(...skipping $dropped chars...)"
189 : $$value;
190 }
191 0 return \%clipped;
192 }
193  
194 # Print the result record to the terminal (unless "quiet") and to the log
195 # filehandle (if one was given), and append it to the trace filehandle as one
196 # JSON line (if one was given). "quiet" silences only this routine chatter;
197 # errors still go to STDERR, since a caller that asked for less noise did not
198 # ask to be kept in the dark about a failure.
199 #
200 # In one of parallel()'s workers the record is written holding an flock on
201 # $REPORT_LOCK, so that the records of tasks running at once do not
202 # interleave. Until 0.192 nothing kept them apart, and a long trace line,
203 # which perl writes in several write()s, could be split by another worker's:
204 # the trace was no longer JSON lines, and report() refused it. The lock is
205 # on a file each worker opens for itself, since workers that share one open
206 # file -- the inherited log or trace handle -- share its flock too.
207 447 our $REPORT_LOCK; # undef = not in a worker; else the lock file's path
208 4554 ▶sub _report {
Subroutine _report: called CC=8 SCAR=33.3
209 0 ▶ my ($r, $log_fh, $quiet, $trace_fh) = @_;
Subroutine _report: not called CC=8 SCAR=33.3
210 0 my $clipped = _clipped($r);
211 0 my $lock;
212 0 ▶ if (defined $REPORT_LOCK) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $SimpleFlow::REPORT_LOCK) 0 4554 4554
if (defined $SimpleFlow::REPORT_LOCK) 0 0 0
213 0 ▶ open $lock, '>>', $REPORT_LOCK or die "cannot open \"$REPORT_LOCK\" to write a record: $!";
Branch: 2 branches
BranchTrueFalseTotal
open $lock, ">>", $SimpleFlow::REPORT_LOCK or die qq[cannot open "$SimpleFlow::REPORT_LOCK" to write a record: $!] 0 0 0
open $lock, ">>", $SimpleFlow::REPORT_LOCK or die qq[cannot open "$SimpleFlow::REPORT_LOCK" to write a record: $!] 0 0 0
214 0 ▶ flock $lock, Fcntl::LOCK_EX() or die "cannot lock \"$REPORT_LOCK\" to write a record: $!";
Branch: 2 branches
BranchTrueFalseTotal
flock $lock, 2 or die qq[cannot lock "$SimpleFlow::REPORT_LOCK" to write a record: $!] 0 0 0
flock $lock, 2 or die qq[cannot lock "$SimpleFlow::REPORT_LOCK" to write a record: $!] 0 0 0
215 }
216 # string_max => 0 turns Data::Printer 1.x's own clipping off: the fields
217 # arrive clipped already, and a second pass would print a second
218 # "skipping" mark. Older releases ignore the property either way.
219 0 ▶ p(%$clipped, output => $log_fh, string_max => 0) if defined $log_fh;
Branch: 2 branches
BranchTrueFalseTotal
if defined $log_fh 188 4366 4554
if defined $log_fh 0 0 0
220 0 ▶ p(%$clipped, string_max => 0) unless $quiet;
Branch: 2 branches
BranchTrueFalseTotal
unless $quiet 988 3566 4554
unless $quiet 0 0 0
221 0 ▶ print {$trace_fh} _trace_line($r), "\n" if defined $trace_fh;
Branch: 2 branches
BranchTrueFalseTotal
if defined $trace_fh 154 4400 4554
if defined $trace_fh 0 0 0
222 0 ▶ if (defined $lock) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $lock) 0 4554 4554
if (defined $lock) 0 0 0
223 0 _flush(\*STDOUT); # the log and trace handles are autoflushed already
224 0 close $lock; # and with it the lock
225 }
226 0 return;
227 }
228  
229 # Fields of the record written to the trace as JSON numbers, when they look
230 # like one; everything else is a string. A caller's own value for a boolean
231 # option ("yes", say) is not a number, and is written as a string, so the line
232 # is valid JSON whatever the caller passed.
233 447 my %TRACE_NUMBER = map { $_ => 1 } qw(
234 attempts cpu.system cpu.user die dry_run duration exit lock out.of.date
235 overwrite protect quiet retries retry_delay signal source.line stale
236 start.time time timed.out timeout
237 );
238 447 my $JSON_NUMBER = qr/\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?\z/;
239  
240 # One record as a line of JSON, in the spirit of Nextflow's trace.txt: every
241 # field but the captured stdout and stderr, which can be any size and are in
242 # the record and the log already, plus "time", when the line was written.
243 # JSON::PP is core only from perl 5.14, so this is written out here; it needs
244 # only strings, numbers, null, and arrays and hashes of those.
245 154 ▶sub _trace_line {
Subroutine _trace_line: called CC=1 SCAR=1.2
246 0 ▶ my $r = shift;
Subroutine _trace_line: not called CC=1 SCAR=1.2
247 0 my %line = (%$r, time => Time::HiRes::time());
248 0 delete @line{'stdout', 'stderr'};
249 0 return _json(\%line, 0);
250 }
251 8134 ▶sub _json {
Subroutine _json: called CC=9 SCAR=30.6
252 0 ▶ my ($value, $number) = @_; # $number: 1 = write a number-like scalar as a JSON number
Subroutine _json: not called CC=9 SCAR=30.6
253 0 ▶ return 'null' if not defined $value;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $value 0 8134 8134
unless defined $value 0 0 0
254 0 ▶ if (ref $value eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $value eq "ARRAY") 1244 6890 8134
if (ref $value eq "ARRAY") 0 0 0
255 0 return '[' . join(',', map { _json($_, 0) } @$value) . ']';
256 }
257 0 ▶ if (ref $value eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $value eq "HASH") 474 6416 6890
if (ref $value eq "HASH") 0 0 0
258 # the values of a "*.size" hash are byte counts
259 return '{' . join(',', map {
260 0 _json_string($_) . ':' . _json($value->{$_},
261 0 ▶ ($number || $TRACE_NUMBER{$_} || /\.size\z/) ? 1 : 0)
Branch: 2 branches
BranchTrueFalseTotal
$number || $TRACE_NUMBER{$_} || /\.size\z/ ? : 3516 4340 7856
$number || $TRACE_NUMBER{$_} || /\.size\z/ ? : 0 0 0
Condition50%6/12
$number or $TRACE_NUMBER{$_} or /\.size\z/
l!l&&r!l&&!r
33501664340
$number or $TRACE_NUMBER{$_}
l!l&&r!l&&!r
11632344506
$number or $TRACE_NUMBER{$_} or /\.size\z/
l!l&&r!l&&!r
000
$number or $TRACE_NUMBER{$_}
l!l&&r!l&&!r
000
MC/DC100%3/3
$number or $TRACE_NUMBER{$_} or /\.size\z/
$number $TRACE_NUMBER{$_} /\.size\z/
MC/DC0%0/3
$number or $TRACE_NUMBER{$_} or /\.size\z/
$number $TRACE_NUMBER{$_} /\.size\z/
Truth table100%4/4
A or B or C
A= $numberB= $TRACE_NUMBER{$_}C= /\.size\z/
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/4
A or B or C
A= $numberB= $TRACE_NUMBER{$_}C= /\.size\z/
ABCresult
1XX1
01X1
0011
0000
262 } sort keys %$value) . '}';
263 }
264 0 ▶ return $value if $number && ($value =~ $JSON_NUMBER);
Branch: 2 branches
BranchTrueFalseTotal
if $number and $value =~ /$JSON_NUMBER/ 3350 3066 6416
if $number and $value =~ /$JSON_NUMBER/ 0 0 0
Condition33%2/6
$number and $value =~ /$JSON_NUMBER/
!ll&&!rl&&r
306603350
$number and $value =~ /$JSON_NUMBER/
!ll&&!rl&&r
000
MC/DC50%1/2
$number and $value =~ /$JSON_NUMBER/
$number $value =~ /$JSON_NUMBER/
MC/DC0%0/2
$number and $value =~ /$JSON_NUMBER/
$number $value =~ /$JSON_NUMBER/
Truth table66%2/3
A and B
A= $numberB= $value =~ /$JSON_NUMBER/
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $numberB= $value =~ /$JSON_NUMBER/
ABresult
0X0
100
111
265 0 return _json_string($value);
266 }
267 # The string as JSON, in UTF-8, whatever perl holds it as. A character string
268 # is encoded. A byte string that is valid UTF-8 -- a filename read from the
269 # system, typically -- is taken to be UTF-8 already and written as it is; any
270 # other byte string is taken to be Latin-1 characters, as perl itself treats
271 # it, and encoded, so that "caf\x{e9}" is not written as a lone byte the JSON
272 # cannot hold. The trace filehandle should be opened without an encoding
273 # layer, or all of this is encoded a second time.
274 10922 ▶sub _json_string {
Subroutine _json_string: called CC=3 SCAR=15.5
275 0 ▶ my $string = shift;
Subroutine _json_string: not called CC=3 SCAR=15.5
276 0 ▶ if (not utf8::is_utf8($string)) {
Branch: 2 branches
BranchTrueFalseTotal
unless (utf8::is_utf8($string)) 10922 0 10922
unless (utf8::is_utf8($string)) 0 0 0
277 0 my $decoded = $string;
278 0 ▶ $string = $decoded if utf8::decode($decoded);
Branch: 2 branches
BranchTrueFalseTotal
if utf8::decode($decoded) 10846 76 10922
if utf8::decode($decoded) 0 0 0
279 }
280 0 utf8::encode($string);
281 0 $string =~ s/(["\\])/\\$1/g;
282 0 $string =~ s/([\x00-\x1f])/sprintf('\\u%04x', ord $1)/ge;
283 0 return qq{"$string"};
284 }
285  
286 # What "env_secret" puts in place of a value it hides.
287 447 my $SECRET_SHOWN = '(secret)';
288  
289 # The names "env_secret" holds, sorted and once each, as far as they can be
290 # read: this also runs on arguments not yet validated, for an error message.
291 12018 ▶sub _secret_names {
Subroutine _secret_names: called CC=4 SCAR=18.7
292 0 ▶ my $args = shift;
Subroutine _secret_names: not called CC=4 SCAR=18.7
293 0 my $names = $args->{'env_secret'};
294 0 ▶ return () if ref $names ne 'ARRAY';
Branch: 2 branches
BranchTrueFalseTotal
if ref $names ne "ARRAY" 6772 5246 12018
if ref $names ne "ARRAY" 0 0 0
295 0 my %seen;
296 0 ▶ return sort grep { (defined $_) && (ref $_ eq '') && (not $seen{$_}++) } @$names;
Condition41%5/12
defined $_ && ref $_ eq '' && !$seen{$_}++
!ll&&!rl&&r
8080
defined $_ and ref $_ eq ""
!ll&&!rl&&r
4480
defined $_ && ref $_ eq '' && !$seen{$_}++
!ll&&!rl&&r
000
defined $_ and ref $_ eq ""
!ll&&!rl&&r
000
MC/DC66%2/3
defined $_ && ref $_ eq '' && !$seen{$_}++
defined $_ ref $_ eq "" !$seen{$_}++
MC/DC0%0/3
defined $_ && ref $_ eq '' && !$seen{$_}++
defined $_ ref $_ eq "" !$seen{$_}++
Truth table75%3/4
A and B && not(C)
A= defined $_B= ref $_ eq ""C= !$seen{$_}++
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B && not(C)
A= defined $_B= ref $_ eq ""C= !$seen{$_}++
ABCresult
0XX0
10X0
1100
1111
297 }
298  
299 # A copy of the arguments, or of %DEFAULTS, that is safe to print: the "env"
300 # values that "env_secret" names are hidden. Only "env" is copied deeply.
301 6820 ▶sub _shown_args {
Subroutine _shown_args: called CC=5 SCAR=21.6
302 0 ▶ my $args = shift;
Subroutine _shown_args: not called CC=5 SCAR=21.6
303 0 my %shown = %$args;
304 0 my @secret = _secret_names($args);
305 0 ▶ if ((ref $args->{env} eq 'HASH') && (scalar @secret > 0)) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $args->{"env"} eq "HASH" and scalar @secret > 0) 32 6788 6820
if (ref $args->{"env"} eq "HASH" and scalar @secret > 0) 0 0 0
Condition50%3/6
ref $args->{"env"} eq "HASH" and scalar @secret > 0
!ll&&!rl&&r
1478531032
ref $args->{"env"} eq "HASH" and scalar @secret > 0
!ll&&!rl&&r
000
MC/DC100%2/2
ref $args->{"env"} eq "HASH" and scalar @secret > 0
ref $args->{"env"} eq "HASH" scalar @secret > 0
MC/DC0%0/2
ref $args->{"env"} eq "HASH" and scalar @secret > 0
ref $args->{"env"} eq "HASH" scalar @secret > 0
Truth table100%3/3
A and B
A= ref $args->{"env"} eq "HASH"B= scalar @secret > 0
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= ref $args->{"env"} eq "HASH"B= scalar @secret > 0
ABresult
0X0
100
111
306 0 my %env = %{ $args->{env} };
307 0 foreach my $name (grep { exists $env{$_} } @secret) {
308 0 ▶ $env{$name} = $SECRET_SHOWN if defined $env{$name}; # undef, removing one, gives nothing away
Branch: 2 branches
BranchTrueFalseTotal
if defined $env{$name} 40 0 40
if defined $env{$name} 0 0 0
309 }
310 0 $shown{env} = \%env;
311 }
312 0 return \%shown;
313 }
314  
315 # Print the arguments to STDERR before an error, as every argument error does,
316 # with the secrets hidden.
317 1394 ▶sub _dump_args {
Subroutine _dump_args: called CC=1 SCAR=1.2
318 0 ▶ my $shown = _shown_args(shift);
Subroutine _dump_args: not called CC=1 SCAR=1.2
319 0 p $shown, output => 'STDERR';
320 0 return;
321 }
322  
323 # Turn Devel::Confess on -- stack traces, in colour on a terminal -- for the
324 # dynamic scope of the task() that calls this, which has localised every
325 # variable assigned here. Until 0.19 the module said "use Devel::Confess
326 # 'color'", which installs its __DIE__ and __WARN__ handlers globally and for
327 # good: every program that loaded SimpleFlow had a stack trace appended to its
328 # own die "message\n", so code comparing $@ with a string broke.
329 #
330 # This does what Devel::Confess 0.009004's import() does (Devel/Confess.pm,
331 # "sub import"), but to localised copies: the caller's handler is kept in
332 # %Devel::Confess::OLD_SIG, which _die and _warn call in turn, and the colour
333 # is its "color" option. Those are internals, not API, so if a later release
334 # drops _die or _warn this turns nothing on rather than dying; t/04.fixes.t
335 # block 9 checks that the traces are still there.
336 7172 ▶sub _confess_here {
Subroutine _confess_here: called CC=6 SCAR=25.8
337 0 ▶ return if not ((defined &Devel::Confess::_die) && (defined &Devel::Confess::_warn));
Subroutine _confess_here: not called CC=6 SCAR=25.8
Branch: 2 branches
BranchTrueFalseTotal
unless defined &Devel::Confess::_die and defined &Devel::Confess::_warn 0 7172 7172
unless defined &Devel::Confess::_die and defined &Devel::Confess::_warn 0 0 0
Condition16%1/6
defined &Devel::Confess::_die and defined &Devel::Confess::_warn
!ll&&!rl&&r
007172
defined &Devel::Confess::_die and defined &Devel::Confess::_warn
!ll&&!rl&&r
000
MC/DC0%0/2
defined &Devel::Confess::_die and defined &Devel::Confess::_warn
defined &Devel::Confess::_die defined &Devel::Confess::_warn
MC/DC0%0/2
defined &Devel::Confess::_die and defined &Devel::Confess::_warn
defined &Devel::Confess::_die defined &Devel::Confess::_warn
Truth table33%1/3
A and B
A= defined &Devel::Confess::_dieB= defined &Devel::Confess::_warn
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined &Devel::Confess::_dieB= defined &Devel::Confess::_warn
ABresult
0X0
100
111
338 0 foreach my $sig (['__DIE__', \&Devel::Confess::_die], ['__WARN__', \&Devel::Confess::_warn]) {
339 0 my ($name, $handler) = @$sig;
340 # a caller that enabled Devel::Confess itself already has it here
341 0 ▶ next if (defined $SIG{$name}) && ($SIG{$name} eq $handler);
Branch: 2 branches
BranchTrueFalseTotal
if defined $SIG{$name} and $SIG{$name} eq $handler 200 14144 14344
if defined $SIG{$name} and $SIG{$name} eq $handler 0 0 0
Condition50%3/6
defined $SIG{$name} and $SIG{$name} eq $handler
!ll&&!rl&&r
13938206200
defined $SIG{$name} and $SIG{$name} eq $handler
!ll&&!rl&&r
000
MC/DC100%2/2
defined $SIG{$name} and $SIG{$name} eq $handler
defined $SIG{$name} $SIG{$name} eq $handler
MC/DC0%0/2
defined $SIG{$name} and $SIG{$name} eq $handler
defined $SIG{$name} $SIG{$name} eq $handler
Truth table100%3/3
A and B
A= defined $SIG{$name}B= $SIG{$name} eq $handler
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $SIG{$name}B= $SIG{$name} eq $handler
ABresult
0X0
100
111
342 0 $Devel::Confess::OLD_SIG{$name} = $SIG{$name};
343 0 $SIG{$name} = $handler;
344 }
345 0 $Devel::Confess::OPTIONS{color} = 1;
346 0 return;
347 }
348  
349 # Newest and oldest modification times among the named files, or undef when
350 # none of them exist. stat's mtime is used rather than -M because -M is
351 # measured from the interpreter's start time, which makes it useless for
352 # comparing against files written during the run. It is Time::HiRes's stat,
353 # which has the sub-second part: core stat's whole seconds made an input
354 # rewritten in the same second as its output look no newer, and until 0.19
355 # "stale" kept the out-of-date output.
356 # The stat is copied into an array before [9] is taken, not sliced where it
357 # is called: Time::HiRes 1.9719, which perl 5.10.1 and 5.12.5 ship, returns
358 # the wrong value for a direct slice -- (Time::HiRes::stat($f))[9] is 9 there,
359 # not the mtime, measured on both.
360 600 ▶sub _mtime {
Subroutine _mtime: called CC=1 SCAR=1.2
361 0 ▶ my @stat = Time::HiRes::stat(shift);
Subroutine _mtime: not called CC=1 SCAR=1.2
362 0 return $stat[9];
363 }
364 190 ▶sub _newest_mtime {
Subroutine _newest_mtime: called CC=3 SCAR=15.1
365 0 ▶ my @mtimes = map { -d $_ ? _tree_mtime($_) : _mtime($_) } grep { -e $_ } @_;
Subroutine _newest_mtime: not called CC=3 SCAR=15.1
Branch: 2 branches
BranchTrueFalseTotal
-d $_ ? : 24 166 190
-d $_ ? : 0 0 0
366 0 ▶ return undef if scalar @mtimes == 0;
Branch: 2 branches
BranchTrueFalseTotal
if scalar @mtimes == 0 0 190 190
if scalar @mtimes == 0 0 0 0
367 0 return max(@mtimes);
368 }
369 190 ▶sub _oldest_mtime {
Subroutine _oldest_mtime: called CC=3 SCAR=15.1
370 0 ▶ my @mtimes = map { -d $_ ? _tree_mtime($_) : _mtime($_) } grep { -e $_ } @_;
Subroutine _oldest_mtime: not called CC=3 SCAR=15.1
Branch: 2 branches
BranchTrueFalseTotal
-d $_ ? : 86 104 190
-d $_ ? : 0 0 0
371 0 ▶ return undef if scalar @mtimes == 0;
Branch: 2 branches
BranchTrueFalseTotal
if scalar @mtimes == 0 0 190 190
if scalar @mtimes == 0 0 0 0
372 0 return min(@mtimes);
373 }
374 # The newest mtime of a directory and anything in it: when a directory output
375 # was last written to, which is what "stale" compares an input against. The
376 # directory's own mtime changes only when an entry is added or removed, not
377 # when a file in it is rewritten.
378 110 ▶sub _tree_mtime {
Subroutine _tree_mtime: called CC=1 SCAR=1.0
379 0 ▶ my $top = shift;
Subroutine _tree_mtime: not called CC=1 SCAR=1.0
380 0 my $newest = _mtime($top);
381 # File::Find warns, through its own category, on a directory it cannot
382 # read; under this module's FATAL warnings that would be a die
383 447 ▶ no warnings 'File::Find';
Subroutine BEGIN: called CC=1 SCAR=0.0
384 File::Find::find({
385 no_chdir => 1,
386 220 ▶ wanted => sub {
Subroutine __ANON__: called CC=3 SCAR=15.4
387 0 ▶ my $mtime = _mtime($File::Find::name);
Subroutine __ANON__: not called CC=3 SCAR=15.4
388 0 ▶ $newest = $mtime if (defined $mtime) && ($mtime > $newest);
Branch: 2 branches
BranchTrueFalseTotal
if defined $mtime and $mtime > $newest 66 154 220
if defined $mtime and $mtime > $newest 0 0 0
Condition33%2/6
defined $mtime and $mtime > $newest
!ll&&!rl&&r
015466
defined $mtime and $mtime > $newest
!ll&&!rl&&r
000
MC/DC50%1/2
defined $mtime and $mtime > $newest
defined $mtime $mtime > $newest
MC/DC0%0/2
defined $mtime and $mtime > $newest
defined $mtime $mtime > $newest
Truth table66%2/3
A and B
A= defined $mtimeB= $mtime > $newest
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $mtimeB= $mtime > $newest
ABresult
0X0
100
111
389 },
390 0 }, $top);
391 0 return $newest;
392 }
393  
394 # Fold the "<kind>_file" (a single name) and "<kind>_files" (a name or an
395 # array ref) forms into one list, and reject names that cannot meaningfully be
396 # filetested. undef and '' are caught HERE, before any -f: "-f undef" is a
397 # fatal warning under "warnings FATAL => 'all'" and "-f ''" is merely false,
398 # so until 0.16 a bad input name surfaced either as a crash inside SimpleFlow
399 # or as the misleading "missing or unreadable", never as the argument error
400 # it actually is.
401 21538 ▶sub _normalise_files {
Subroutine _normalise_files: called CC=12 SCAR=34.4
402 0 ▶ my ($args, $kind, $noun) = @_; # $noun: 'file' (the default) or 'dir'
Subroutine _normalise_files: not called CC=12 SCAR=34.4
403 0 ▶ $noun //= 'file';
Condition50%2/4
$noun //= "file"
l!l
1062010918
$noun //= "file"
l!l
00
MC/DC100%1/1
$noun //= "file"
$noun
MC/DC0%0/1
$noun //= "file"
$noun
Truth table100%2/2
A
A= $noun
Aresult
11
00
Truth table0%0/2
A
A= $noun
Aresult
11
00
404 0 my ($single, $plural) = ("${kind}_$noun", "${kind}_${noun}s");
405 # The two forms are mutually exclusive: mixing them is almost always a
406 # mistake (which one holds the truth?), so refuse it outright.
407 0 ▶ if ((defined $args->{$single}) && (defined $args->{$plural})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $args->{$single} and defined $args->{$plural}) 76 21462 21538
if (defined $args->{$single} and defined $args->{$plural}) 0 0 0
Condition50%3/6
defined $args->{$single} and defined $args->{$plural}
!ll&&!rl&&r
18630283276
defined $args->{$single} and defined $args->{$plural}
!ll&&!rl&&r
000
MC/DC100%2/2
defined $args->{$single} and defined $args->{$plural}
defined $args->{$single} defined $args->{$plural}
MC/DC0%0/2
defined $args->{$single} and defined $args->{$plural}
defined $args->{$single} defined $args->{$plural}
Truth table100%3/3
A and B
A= defined $args->{$single}B= defined $args->{$plural}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $args->{$single}B= defined $args->{$plural}
ABresult
0X0
100
111
408 0 _dump_args($args);
409 0 die "\"$single\" and \"$plural\" cannot both be given; use one or the other";
410 }
411 0 my @files;
412 0 my $given = $plural;
413 0 ▶ if (defined $args->{$plural}) {
Branch: 4 branches
BranchTrueFalseTotal
if (defined $args->{$plural}) { } 874 20588 21462
elsif (defined $args->{$single}) { } 2832 17756 20588
if (defined $args->{$plural}) { } 0 0 0
elsif (defined $args->{$single}) { } 0 0 0
414 0 my $ref = ref $args->{$plural};
415 0 ▶ if ($ref eq 'ARRAY') {
Branch: 4 branches
BranchTrueFalseTotal
if ($ref eq 'ARRAY') { } 388 486 874
elsif ($ref eq '') { } 474 12 486
if ($ref eq 'ARRAY') { } 0 0 0
elsif ($ref eq '') { } 0 0 0
416 0 @files = @{ $args->{$plural} };
417 } elsif ($ref eq '') { # a scalar
418 0 @files = ($args->{$plural});
419 } else {
420 0 _dump_args($args);
421 0 die "ref type \"$ref\" is not allowed for \"$plural\"";
422 }
423 } elsif (defined $args->{$single}) {
424 0 $given = $single;
425 0 my $ref = ref $args->{$single};
426 0 ▶ if ($ref ne '') { # a single file only, never a ref
Branch: 2 branches
BranchTrueFalseTotal
if ($ref ne "") 30 2802 2832
if ($ref ne "") 0 0 0
427 0 _dump_args($args);
428 0 die "$ref isn't allowed for \"$single\"; it takes a single filename (use \"$plural\" for a list)";
429 }
430 0 @files = ($args->{$single});
431 }
432 0 ▶ my @bad = grep { (not defined $files[$_]) || (length $files[$_] == 0) } 0 .. $#files;
Condition50%3/6
!defined($files[$_]) || length $files[$_] == 0
l!l&&r!l&&!r
301963744
!defined($files[$_]) || length $files[$_] == 0
l!l&&r!l&&!r
000
MC/DC100%2/2
!defined($files[$_]) || length $files[$_] == 0
!defined($files[$_]) length $files[$_] == 0
MC/DC0%0/2
!defined($files[$_]) || length $files[$_] == 0
!defined($files[$_]) length $files[$_] == 0
Truth table100%3/3
not(A) || B
A= !defined($files[$_])B= length $files[$_] == 0
ABresult
1X1
011
000
Truth table0%0/3
not(A) || B
A= !defined($files[$_])B= length $files[$_] == 0
ABresult
1X1
011
000
433 0 ▶ if (scalar @bad > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @bad > 0) 226 21194 21420
if (scalar @bad > 0) 0 0 0
434 0 _dump_args($args);
435 0 ▶ die 'undefined or 0-length filenames are not allowed (found in "'
Branch: 2 branches
BranchTrueFalseTotal
scalar @bad == 1 ? : 226 0 226
scalar @bad == 1 ? : 0 0 0
436 . $given . '" at ' . ((scalar @bad == 1) ? 'index ' : 'indices ')
437 . join(', ', @bad) . ')';
438 }
439 0 return @files;
440 }
441  
442 # Move each existing output of a failed step to "<file>.failed" and return
443 # the new names. Until 0.19 a failed step's outputs were left where they were:
444 # a file half-written before a non-zero exit, a kill or a timeout then
445 # satisfied the next run's "already done" test, and the truncated file became
446 # the result for good. Snakemake deletes a failed job's outputs for the same
447 # reason; moving them keeps the partial contents for debugging. A move that
448 # fails is warned about rather than fatal, since the step has failed already
449 # and its own message is the one the caller needs.
450 #
451 # Until 0.192 each name was moved as it came, and three kinds of list lost
452 # data. A name given twice had its .failed deleted, as "left from before", by
453 # its own second pass. An output named like another's .failed, as in ['out',
454 # 'out.failed'], was deleted to make room for the other. And a file inside a
455 # directory output was renamed in place, then carried off with the directory,
456 # so the name reported for it did not exist. So the list is cut down first,
457 # to one entry for each path, and to none for a path inside a directory that
458 # is moved itself, which takes it along under its own name; and the longest
459 # names are moved first, so that "out.failed" is out of the way before "out"
460 # is moved onto it.
461 2116 ▶sub _move_aside {
Subroutine _move_aside: called CC=9 SCAR=32.4
462 0 ▶ my %seen;
Subroutine _move_aside: not called CC=9 SCAR=32.4
463 0 my @unique = grep { not $seen{_canonical($_)}++ } grep { -e $_ } @_;
464 0 ▶ my @dirs = map { _canonical($_) } grep { (-d $_) && (not -l $_) } @unique;
Condition33%2/6
-d $_ && !(-l $_)
!ll&&!rl&&r
6180154
-d $_ && !(-l $_)
!ll&&!rl&&r
000
MC/DC50%1/2
-d $_ && !(-l $_)
-d $_ !(-l $_)
MC/DC0%0/2
-d $_ && !(-l $_)
-d $_ !(-l $_)
Truth table66%2/3
A && not(B)
A= -d $_B= !(-l $_)
ABresult
0X0
100
111
Truth table0%0/3
A && not(B)
A= -d $_B= !(-l $_)
ABresult
0X0
100
111
465 my @movable = grep {
466 0 my $path = _canonical($_);
467 0 not grep { _is_within($path, $_) } @dirs;
468 } @unique;
469 0 my @moved;
470 0 ▶ foreach my $file (sort { (length $b <=> length $a) || ($a cmp $b) } @movable) {
Condition16%1/6
length $b <=> length $a || $a cmp $b
l!l&&r!l&&!r
8400
length $b <=> length $a || $a cmp $b
l!l&&r!l&&!r
000
MC/DC0%0/2
length $b <=> length $a || $a cmp $b
length $b <=> length $a $a cmp $b
MC/DC0%0/2
length $b <=> length $a || $a cmp $b
length $b <=> length $a $a cmp $b
Truth table33%1/3
A || B
A= length $b <=> length $aB= $a cmp $b
ABresult
1X1
011
000
Truth table0%0/3
A || B
A= length $b <=> length $aB= $a cmp $b
ABresult
1X1
011
000
471 0 my $aside = "$file.failed";
472 # a .failed left by an earlier failure is removed first, so this
473 # does not rest on rename() replacing a file on every platform, and
474 # a directory output's .failed is a directory, which unlink cannot
475 # remove
476 0 ▶ if ((-d $aside) && (not -l $aside)) {
Branch: 4 branches
BranchTrueFalseTotal
if (-d $aside and not -l $aside) { } 12 678 690
elsif (-e $aside or -l $aside) { } 4 674 678
if (-d $aside and not -l $aside) { } 0 0 0
elsif (-e $aside or -l $aside) { } 0 0 0
Condition33%2/6
-d $aside and not -l $aside
!ll&&!rl&&r
678012
-d $aside and not -l $aside
!ll&&!rl&&r
000
MC/DC50%1/2
-d $aside and not -l $aside
-d $aside not -l $aside
MC/DC0%0/2
-d $aside and not -l $aside
-d $aside not -l $aside
Truth table66%2/3
A and not(B)
A= -d $asideB= not -l $aside
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= -d $asideB= not -l $aside
ABresult
0X0
100
111
477 0 File::Path::rmtree($aside);
478 ▶ } elsif ((-e $aside) || (-l $aside)) {
Condition33%2/6
-e $aside or -l $aside
l!l&&r!l&&!r
40674
-e $aside or -l $aside
l!l&&r!l&&!r
000
MC/DC50%1/2
-e $aside or -l $aside
-e $aside -l $aside
MC/DC0%0/2
-e $aside or -l $aside
-e $aside -l $aside
Truth table66%2/3
A or B
A= -e $asideB= -l $aside
ABresult
1X1
011
000
Truth table0%0/3
A or B
A= -e $asideB= -l $aside
ABresult
1X1
011
000
479 0 unlink $aside;
480 }
481 0 ▶ if (rename $file, $aside) {
Branch: 2 branches
BranchTrueFalseTotal
if (rename $file, $aside) { } 690 0 690
if (rename $file, $aside) { } 0 0 0
482 0 push @moved, $aside;
483 } else {
484 0 warn "cannot move \"$file\", an output of a failed step, to \"$aside\": $!; the next run will take it as done";
485 }
486 }
487 0 return sort @moved;
488 }
489  
490 # A path made absolute and tidied, so that "out" and "./out" compare equal.
491 # Only the text is compared: a symbolic link and its target are two paths.
492 2056 ▶sub _canonical {
Subroutine _canonical: called CC=1 SCAR=1.2
493 0 ▶ return File::Spec->canonpath(File::Spec->rel2abs(shift));
Subroutine _canonical: not called CC=1 SCAR=1.2
494 }
495  
496 # True when $path is strictly inside directory $dir; both are _canonical.
497 236 ▶sub _is_within {
Subroutine _is_within: called CC=4 SCAR=18.9
498 0 ▶ my ($path, $dir) = @_;
Subroutine _is_within: not called CC=4 SCAR=18.9
499 0 my @path = File::Spec->splitdir($path);
500 0 my @dir = File::Spec->splitdir($dir);
501 0 ▶ return 0 if scalar @path <= scalar @dir;
Branch: 2 branches
BranchTrueFalseTotal
if scalar @path <= scalar @dir 154 82 236
if scalar @path <= scalar @dir 0 0 0
502 0 foreach my $i (0 .. $#dir) {
503 0 ▶ return 0 if $path[$i] ne $dir[$i];
Branch: 2 branches
BranchTrueFalseTotal
if $path[$i] ne $dir[$i] 0 328 328
if $path[$i] ne $dir[$i] 0 0 0
504 }
505 0 return 1;
506 }
507  
508 # Remove the write permission from each output, and from everything inside a
509 # directory output, as Snakemake's protected() does, so that a finished result
510 # is not overwritten by accident. Symbolic links are left alone: chmod would
511 # follow one to whatever it points at, which is not the step's to protect.
512 #
513 # On POSIX each path is opened with O_NOFOLLOW and changed through the handle,
514 # so that the thing tested is the thing changed. Until 0.192 the path was
515 # tested with -l and then chmod-ed by name, and something swapped in between
516 # -- a symbolic link, by anyone who can write to the output tree -- had its
517 # target's permission changed instead. A path that cannot be opened, such as
518 # a file without read permission, is still done by name; so is everything on
519 # MSWin32, which has neither O_NOFOLLOW nor fchmod. O_NONBLOCK keeps a FIFO
520 # among the outputs from blocking the open.
521 447 ▶my $O_NOFOLLOW = eval { Fcntl::O_NOFOLLOW() } // 0; # 0 = this system has none
Condition50%1/2
eval { do { 131072 } } // 0
l!l
4470
MC/DC0%0/1
eval { do { 131072 } } // 0
eval { do { 131072 } }
Truth table50%1/2
A
A= eval { do { 131072 } }
Aresult
11
00
522 447 ▶my $O_NONBLOCK = eval { Fcntl::O_NONBLOCK() } // 0; # 0 = this system has none
Condition50%1/2
eval { do { 2048 } } // 0
l!l
4470
MC/DC0%0/1
eval { do { 2048 } } // 0
eval { do { 2048 } }
Truth table50%1/2
A
A= eval { do { 2048 } }
Aresult
11
00
523 108 ▶sub _protect {
Subroutine _protect: called CC=12 SCAR=41.3
524 0 ▶ foreach my $output (@_) {
Subroutine _protect: not called CC=12 SCAR=41.3
525 0 my @paths = ($output);
526 0 ▶ if ((-d $output) && (not -l $output)) {
Branch: 2 branches
BranchTrueFalseTotal
if (-d $output and not -l $output) 52 56 108
if (-d $output and not -l $output) 0 0 0
Condition33%2/6
-d $output and not -l $output
!ll&&!rl&&r
56052
-d $output and not -l $output
!ll&&!rl&&r
000
MC/DC50%1/2
-d $output and not -l $output
-d $output not -l $output
MC/DC0%0/2
-d $output and not -l $output
-d $output not -l $output
Truth table66%2/3
A and not(B)
A= -d $outputB= not -l $output
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= -d $outputB= not -l $output
ABresult
0X0
100
111
527 447 ▶ no warnings 'File::Find'; # see _tree_mtime
Subroutine BEGIN: called CC=1 SCAR=0.0
528 0 ▶ File::Find::find({ no_chdir => 1, wanted => sub { push @paths, $File::Find::name } }, $output);
Subroutine __ANON__: called CC=1 SCAR=0.4
529 }
530 0 foreach my $path (@paths) {
531 0 ▶ if (($^O ne 'MSWin32') && $O_NOFOLLOW
Branch: 2 branches
BranchTrueFalseTotal
if ($^O ne "MSWin32" and $O_NOFOLLOW and sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK) 212 0 212
if ($^O ne "MSWin32" and $O_NOFOLLOW and sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK) 0 0 0
Condition16%2/12
$^O ne "MSWin32" and $O_NOFOLLOW and sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK
!ll&&!rl&&r
00212
$^O ne "MSWin32" and $O_NOFOLLOW
!ll&&!rl&&r
00212
$^O ne "MSWin32" and $O_NOFOLLOW and sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK
!ll&&!rl&&r
000
$^O ne "MSWin32" and $O_NOFOLLOW
!ll&&!rl&&r
000
MC/DC0%0/3
$^O ne "MSWin32" and $O_NOFOLLOW and sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK
$^O ne "MSWin32" $O_NOFOLLOW sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK
MC/DC0%0/3
$^O ne "MSWin32" and $O_NOFOLLOW and sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK
$^O ne "MSWin32" $O_NOFOLLOW sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK
Truth table25%1/4
A and B and C
A= $^O ne "MSWin32"B= $O_NOFOLLOWC= sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B and C
A= $^O ne "MSWin32"B= $O_NOFOLLOWC= sysopen my $fh, $path, 0 | $O_NOFOLLOW | $O_NONBLOCK
ABCresult
0XX0
10X0
1100
1111
532 && (sysopen my $fh, $path, Fcntl::O_RDONLY() | $O_NOFOLLOW | $O_NONBLOCK)) {
533 0 my $mode = (stat $fh)[2];
534 0 ▶ chmod(($mode & 07777) & ~0222, $fh)
Branch: 2 branches
BranchTrueFalseTotal
chmod $mode & 4095 & '18446744073709551469', $fh or warn qq[cannot make "$path" read-only for "protect": $!] 212 0 212
chmod $mode & 4095 & '18446744073709551469', $fh or warn qq[cannot make "$path" read-only for "protect": $!] 0 0 0
535 or warn "cannot make \"$path\" read-only for \"protect\": $!";
536 0 next;
537 }
538 0 ▶ next if -l $path;
Branch: 2 branches
BranchTrueFalseTotal
if -l $path 0 0 0
if -l $path 0 0 0
539 0 my $mode = (stat $path)[2];
540 0 ▶ next if not defined $mode;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $mode 0 0 0
unless defined $mode 0 0 0
541 0 ▶ chmod(($mode & 07777) & ~0222, $path)
Branch: 2 branches
BranchTrueFalseTotal
chmod $mode & 4095 & '18446744073709551469', $path or warn qq[cannot make "$path" read-only for "protect": $!] 0 0 0
chmod $mode & 4095 & '18446744073709551469', $path or warn qq[cannot make "$path" read-only for "protect": $!] 0 0 0
542 or warn "cannot make \"$path\" read-only for \"protect\": $!";
543 }
544 }
545 0 return;
546 }
547  
548 # Make $dir, where SimpleFlow keeps its lock files and command records, unless
549 # it is there, and refuse one that is a symbolic link. Until 0.192 a link was
550 # followed, and someone who could write to the working directory could point
551 # ".simpleflow" anywhere and have the files made there. The files in it are
552 # opened with O_NOFOLLOW, for the same reason. These guard against a link,
553 # not against a directory others can write to: the working directory, and the
554 # outputs, are to be writable only by those trusted to run the pipeline.
555 1006 ▶sub _metadata_dir {
Subroutine _metadata_dir: called CC=5 SCAR=17.8
556 1006 my ($dir, $what) = @_; # $what: what the directory is for, for the message
557 1006 ▶ if ((not -d $dir) && (not mkdir $dir) && (not -d $dir)) { # another run may make it first
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir or mkdir $dir or -d $dir) 0 1006 1006
Condition50%3/6
-d $dir or mkdir $dir or -d $dir
l!l&&r!l&&!r
100600
-d $dir or mkdir $dir
l!l&&r!l&&!r
5804260
MC/DC0%0/3
-d $dir or mkdir $dir or -d $dir
-d $dir mkdir $dir -d $dir
Truth table50%2/4
A or B or C
A= -d $dirB= mkdir $dirC= -d $dir
ABCresult
1XX1
01X1
0011
0000
558 0 die "cannot make \"$dir\" in " . getcwd() . " for $what: $!";
559 }
560 1006 ▶ die "\"$dir\" in " . getcwd() . " is a symbolic link, which is not followed for $what; make it a directory"
Branch: 1 branch
BranchTrueFalseTotal
if -l $dir 16 990 1006
561 if -l $dir;
562 990 return;
563 }
564  
565 # Take an exclusive lock for each declared output of a step, and return the
566 # handles holding them; the locks go when the handles do, however task()
567 # returns. A second run of the same pipeline that reaches the step meanwhile
568 # waits here, and then finds the outputs made. The lock files are in
569 # ".simpleflow" in the working directory, one per path, named for it, and are
570 # left there afterwards: removing a lock file another process is waiting on
571 # would let a third take a lock on a new file of the same name, and the two
572 # would both run. Two runs in different working directories do not see each
573 # other's locks, as with Snakemake's.
574 #
575 # Until 0.192 the lock was named for the output's absolute path as written,
576 # so two names for one file -- "out" and "sub/../out", or through a linked
577 # directory -- took two locks, and a directory output did not exclude a step
578 # whose output was a file inside it. Now an output is named for its real
579 # directory (Cwd::realpath) and its own name, and, when it is itself a
580 # symbolic link, for what that resolves to as well; and a step takes a shared
581 # lock on every directory above each output, which a step whose output is that
582 # directory locks exclusively. Hard links, which have no one name, are still
583 # two files here.
584 150 ▶sub _lock_outputs {
Subroutine _lock_outputs: called CC=11 SCAR=24.2
585 150 my ($cmd_string, @outputs) = @_;
586 150 my %mode; # path => Fcntl::LOCK_EX() for an output, LOCK_SH() for a directory above one
587 150 $mode{$_} = Fcntl::LOCK_EX() foreach map { _lock_names($_) } @outputs;
588 150 foreach my $locked (keys %mode) {
589 150 ▶ $mode{$_} //= Fcntl::LOCK_SH() foreach _ancestors($locked);
Condition50%1/2
$mode{$_} //= 1
l!l
0532
MC/DC0%0/1
$mode{$_} //= 1
$mode{$_}
Truth table50%1/2
A
A= $mode{$_}
Aresult
11
00
590 }
591 150 ▶ return () if scalar keys %mode == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %mode == 0 0 150 150
592 150 my $lock_dir = '.simpleflow';
593 150 _metadata_dir($lock_dir, 'the lock files of "lock"');
594 134 my @held;
595 # in sorted order, so that two runs cannot each hold a lock the other wants
596 134 foreach my $path (sort keys %mode) {
597 # md5_hex takes bytes, and until 0.192 a name with a character above
598 # 255 died "Wide character in subroutine entry" here. Encoded as
599 # _signature_file encodes it, which is also how perl itself hands
600 # such a name to the system.
601 618 my $bytes = $path;
602 618 ▶ utf8::encode($bytes) if utf8::is_utf8($bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 144 474 618
603 618 my $lock_file = File::Spec->catfile($lock_dir, md5_hex($bytes) . '.lock');
604 618 ▶ sysopen(my $fh, $lock_file, Fcntl::O_WRONLY() | Fcntl::O_APPEND() | Fcntl::O_CREAT() | $O_NOFOLLOW)
Branch: 1 branch
BranchTrueFalseTotal
sysopen my $fh, $lock_file, 1089 | $O_NOFOLLOW or die qq[cannot open "$lock_file", the lock file for "$path": $!] 618 0 618
605 or die "cannot open \"$lock_file\", the lock file for \"$path\": $!";
606 618 ▶ if (not flock $fh, $mode{$path} | Fcntl::LOCK_NB()) {
Branch: 1 branch
BranchTrueFalseTotal
unless (flock $fh, $mode{$path} | 4) 58 560 618
607 58 say STDERR "waiting for another run, which holds a lock on \"$path\", to finish before running \"$cmd_string\"";
608 58 ▶ flock $fh, $mode{$path} or die "cannot lock \"$lock_file\" for \"$path\": $!";
Branch: 1 branch
BranchTrueFalseTotal
flock $fh, $mode{$path} or die qq[cannot lock "$lock_file" for "$path": $!] 58 0 58
609 }
610 618 push @held, $fh;
611 }
612 134 return @held;
613 }
614  
615 # The names an output is locked under: its real directory and its own name,
616 # and, for a symbolic link, what it resolves to.
617 150 ▶sub _lock_names {
Subroutine _lock_names: called CC=6 SCAR=23.5
618 150 my $absolute = File::Spec->canonpath(File::Spec->rel2abs(shift));
619 150 my ($volume, $dirs, $name) = File::Spec->splitpath($absolute);
620 150 my $parent = File::Spec->catpath($volume, $dirs, '');
621 150 ▶ my $real_parent = (-d $parent) ? _realpath($parent) : undef;
Branch: 1 branch
BranchTrueFalseTotal
-d $parent ? : 150 0 150
622 150 ▶ my @names = (defined $real_parent) ? (File::Spec->catfile($real_parent, $name)) : ($absolute);
Branch: 1 branch
BranchTrueFalseTotal
defined $real_parent ? : 150 0 150
623 150 ▶ if (-l $absolute) {
Branch: 1 branch
BranchTrueFalseTotal
if (-l $absolute) 0 150 150
624 0 my $target = _realpath($absolute);
625 0 ▶ push @names, $target if (defined $target) && ($target ne $names[0]);
Branch: 1 branch
BranchTrueFalseTotal
if defined $target and $target ne $names[0] 0 0 0
Condition0%0/3
defined $target and $target ne $names[0]
!ll&&!rl&&r
000
MC/DC0%0/2
defined $target and $target ne $names[0]
defined $target $target ne $names[0]
Truth table0%0/3
A and B
A= defined $targetB= $target ne $names[0]
ABresult
0X0
100
111
626 }
627 150 return @names;
628 }
629 # Cwd::realpath, or undef where it cannot resolve the path; some versions die
630 # rather than return undef.
631 406 ▶sub _realpath {
Subroutine _realpath: called CC=1 SCAR=0.0
632 406 my $path = shift;
633 447 ▶ no warnings; # a path it cannot resolve is an undef here, not a warning
Subroutine BEGIN: called CC=1 SCAR=0.0
634 406 return eval { Cwd::realpath($path) };
635 }
636 # Every directory above $path, outermost first.
637 150 ▶sub _ancestors {
Subroutine _ancestors: called CC=1 SCAR=0.0
638 150 my @parts = File::Spec->splitdir(shift);
639 150 return grep { $_ ne '' } map { File::Spec->catdir(@parts[0 .. $_ - 1]) } 1 .. $#parts;
640 }
641  
642 # Run $cmd in a child of its own and wait for it, as system() would, and
643 # return its raw wait status, a flag saying whether $timeout (seconds; 0 for
644 # none) was hit, why the command could not be launched ('' if it was), and
645 # the name of any signal that interrupted the wait, or undef. POSIX-only; on
646 # MSWin32 task() uses system(), and refuses "timeout".
647 #
648 # system() itself is not used, for two reasons. A $SIG{ALRM} that fires while
649 # system() is blocked in waitpid unwinds the Perl stack but leaves the child
650 # running as an orphan. And system() shields its caller from INT and QUIT only:
651 # a TERM or HUP sent to perl alone -- by a batch scheduler, or "kill <pid>" --
652 # killed perl and left the command running, until 0.19. Here each of those is
653 # passed on to the command, which is waited for, and the signal is then
654 # re-raised by task() once the record is written.
655 #
656 # The child leads a process group of its own, so that a signal can reach the
657 # command as a whole: a shell command is usually a pipeline, not a single
658 # process, and signalling only the shell leaves its children behind. Until
659 # 0.192 that was so only under a timeout; without one the child stayed in
660 # perl's group, a TERM was passed to the shell alone, and the rest of the
661 # pipeline ran on as orphans. perl's own group cannot be signalled instead:
662 # it holds whatever else the caller's shell started with perl, such as a
663 # "tee" its output is piped into.
664 #
665 # So perl stands in for a shell's job control. The command's group is not the
666 # terminal's foreground group, and a Ctrl-C or Ctrl-Z there reaches perl
667 # alone. With a timeout, an interrupt (HUP, INT, QUIT, TERM) kills the group,
668 # as the timeout does. Without one, it is passed on to the group and the
669 # command waited for; INT and QUIT are then not re-raised, as system() does
670 # not, and HUP and TERM are. A Ctrl-Z (TSTP) stops the group and perl with it,
671 # and both carry on when perl is continued.
672 #
673 # $foreground is true when the command's stdin is the caller's terminal. The
674 # command is then handed the terminal's foreground, as a shell hands it to a
675 # job, and perl takes it back afterwards; a Ctrl-C or Ctrl-Z then reaches the
676 # command alone. Until 0.19 a timed command reading the terminal was stopped
677 # by SIGTTIN until the timeout killed it, and reported as timed out. A command
678 # that opens the terminal itself -- ssh or sudo asking for a password, with
679 # stdin on the null device -- is stopped by SIGTTIN or SIGTTOU too, and is
680 # given the foreground then, as "fg" would. Stopped from the terminal (Ctrl-Z),
681 # a command is suspended as a shell would suspend a job: perl stops too, and on
682 # being continued gives the command back the terminal, if it had it, and
683 # continues it. The timeout does not run while it is suspended.
684 #
685 # A failed exec cannot report its errno through the exit status, so the child
686 # writes it down a pipe that exec closes on success -- the method perl's own
687 # system() uses (pp_sys.c, pp_system) -- and the command is then reported as
688 # system() would report it: exit -1, with the reason.
689 4478 ▶sub _run_forked {
Subroutine _run_forked: called CC=38 SCAR=46.9
690 4478 my ($cmd, $timeout, $foreground) = @_;
691 4478 ▶ my $timed = ($timeout > 0) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$timeout > 0 ? : 224 4254 4478
692 4478 ▶ my $cmd_string = (ref $cmd eq 'ARRAY') ? join(' ', @$cmd) : $cmd;
Branch: 1 branch
BranchTrueFalseTotal
ref $cmd eq 'ARRAY' ? : 3708 770 4478
693 # The caller's own pending alarm, if any: "alarm $timeout" below would
694 # replace it and "alarm 0" cancel it, as both did until 0.19. It is put
695 # back at the end, less the time spent here.
696 4478 ▶ my $caller_alarm = $timed ? alarm(0) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$timed ? : 224 4254 4478
697 4478 my $started = Time::HiRes::time();
698 4478 my $tty = _controlling_terminal(); # undef = perl has none
699 # Only a perl in the terminal's foreground can hand it on; one in the
700 # background would take it from the job that has it.
701 4478 ▶ $foreground = ($foreground && _is_foreground($tty)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$foreground && _is_foreground($tty) ? : 0 4478 4478
Condition33%1/3
$foreground and _is_foreground($tty)
!ll&&!rl&&r
447800
MC/DC0%0/2
$foreground and _is_foreground($tty)
$foreground _is_foreground($tty)
Truth table33%1/3
A and B
A= $foregroundB= _is_foreground($tty)
ABresult
0X0
100
111
702 # The write end must close itself in the child when the exec succeeds.
703 # perl marks a new descriptor close-on-exec only above $^F, and until
704 # 0.192 nothing else did, so a caller that had raised $^F handed the
705 # command the write end: the sysread below then waited for the command to
706 # end, before the alarm was set, and "timeout" never fired.
707 4478 ▶ pipe(my $exec_failed_read, my $exec_failed_write)
Branch: 1 branch
BranchTrueFalseTotal
pipe my $exec_failed_read, my $exec_failed_write or die qq[cannot make a pipe to run "$cmd_string": $!] 4478 0 4478
708 or die "cannot make a pipe to run \"$cmd_string\": $!";
709 4478 ▶ fcntl($exec_failed_write, Fcntl::F_SETFD(), Fcntl::FD_CLOEXEC())
Branch: 1 branch
BranchTrueFalseTotal
fcntl $exec_failed_write, 2, 1 or die qq[cannot mark a pipe close-on-exec to run "$cmd_string": $!] 4478 0 4478
710 or die "cannot mark a pipe close-on-exec to run \"$cmd_string\": $!";
711 # Held back from before the fork until the handlers below are in place.
712 # The command can send one as soon as it has started, and until 0.191 one
713 # that arrived before the handlers went to the caller's alone: the command
714 # was neither killed nor passed it, and ran on to be reported as done. A
715 # CPAN smoker (perl 5.16.3, Alpine) lost such a race in t/07.coverage.t.
716 4478 my $held = POSIX::SigSet->new(POSIX::SIGHUP(), POSIX::SIGINT(), POSIX::SIGQUIT(), POSIX::SIGTERM(), POSIX::SIGTSTP());
717 4478 my $caller_mask = POSIX::SigSet->new();
718 4478 ▶ POSIX::sigprocmask(POSIX::SIG_BLOCK(), $held, $caller_mask)
Branch: 1 branch
BranchTrueFalseTotal
POSIX::sigprocmask(0, $held, $caller_mask) or die qq[cannot block signals to run "$cmd_string": $!] 4478 0 4478
719 or die "cannot block signals to run \"$cmd_string\": $!";
720 4478 my $pid = fork();
721 4478 ▶ if (not defined $pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $pid) 0 4478 4478
722 0 my $error = $!;
723 0 POSIX::sigprocmask(POSIX::SIG_SETMASK(), $caller_mask);
724 0 _restore_alarm($caller_alarm, $started);
725 0 die "fork() failed, so the command cannot be run: $error";
726 }
727 4478 ▶ if ($pid == 0) { # the child
Branch: 1 branch
BranchTrueFalseTotal
if ($pid == 0) 400 4078 4478
728 400 close $exec_failed_read;
729 400 setpgrp(0, 0); # lead a new process group, so that a signal reaches the whole pipeline
730 400 ▶ _take_terminal($tty, $$) if $foreground;
Branch: 1 branch
BranchTrueFalseTotal
if $foreground 0 400 400
731 # A failed exec warns "Can't exec", which "warnings FATAL" turns into
732 # a die -- and a die here unwinds into the caller's evals as a second
733 # copy of the caller's program. Until 0.18 exactly that happened.
734 447 ▶ no warnings 'exec';
Subroutine BEGIN: called CC=1 SCAR=0.0
735 # A blocked mask survives exec. The caller's handlers become the
736 # default across it, and one it ignores stays ignored, which is what
737 # system() leaves its child with.
738 400 POSIX::sigprocmask(POSIX::SIG_SETMASK(), $caller_mask);
739 my $exec_ok = (ref $cmd eq 'ARRAY')
740 400 ▶ ? exec({ $cmd->[0] } @{ $cmd }) # the block form never uses the shell, even for one word
Branch: 1 branch
BranchTrueFalseTotal
ref $cmd eq 'ARRAY' ? : 314 86 400
741 : exec($cmd);
742 # Only reached when exec itself failed. _exit, not exit: exit would
743 # run END blocks and flush the parent's buffers a second time.
744 0 syswrite $exec_failed_write, ($! + 0);
745 0 POSIX::_exit(127); # 127 is the shell's own "command not found" status
746 }
747 4078 close $exec_failed_write;
748 # From both sides, as a shell does, since either may run first; the one
749 # that runs before the child's setpgrp fails harmlessly.
750 4078 ▶ _take_terminal($tty, $pid) if $foreground;
Branch: 1 branch
BranchTrueFalseTotal
if $foreground 0 4078 4078
751 4078 my $has_terminal = $foreground; # 1 = the command's group has the terminal's foreground
752 # Returns at once with nothing when the exec succeeded, and with the
753 # child's errno when it did not.
754 4078 my $got = sysread $exec_failed_read, my $errno, 16;
755 4078 close $exec_failed_read;
756 4078 ▶ if ((defined $got) && ($got > 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $got and $got > 0) 16 4062 4078
Condition66%2/3
defined $got and $got > 0
!ll&&!rl&&r
0406216
MC/DC50%1/2
defined $got and $got > 0
defined $got $got > 0
Truth table66%2/3
A and B
A= defined $gotB= $got > 0
ABresult
0X0
100
111
757 16 waitpid $pid, 0;
758 16 POSIX::sigprocmask(POSIX::SIG_SETMASK(), $caller_mask); # one held meanwhile goes to the caller
759 16 ▶ _take_terminal($tty, getpgrp()) if $has_terminal;
Branch: 1 branch
BranchTrueFalseTotal
if $has_terminal 0 16 16
760 16 _restore_alarm($caller_alarm, $started);
761 16 local $! = $errno + 0;
762 16 return (-1, 0, "$!", undef);
763 }
764 # Signals that would otherwise reach perl alone. One the caller ignores
765 # stays ignored, by perl and, since it is inherited, by the command.
766 4062 my @interrupts = grep { not _ignored($_) } qw(HUP INT QUIT TERM);
767 4062 my $timed_out = 0;
768 4062 my $interrupted; # undef, or the name of the signal to re-raise
769 4062 my $cut_short = 0; # 1 = the wait was ended by one of the two dies below
770 4062 my $status;
771 # Stop the command and perl with it, as a shell stops a job, with the
772 # clock stopped; on being continued, give the command the terminal if it
773 # wants it and perl has it to give, and continue it. $wants_terminal: the
774 # command had the terminal, or stopped asking for it.
775 0 ▶ my $suspend = sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
776 0 my $wants_terminal = shift;
777 0 ▶ my $left = $timed ? Time::HiRes::alarm(0) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$timed ? : 0 0 0
778 0 ▶ _take_terminal($tty, getpgrp()) if $has_terminal;
Branch: 1 branch
BranchTrueFalseTotal
if $has_terminal 0 0 0
779 0 $has_terminal = 0;
780 0 kill 'STOP', $$;
781 0 ▶ if ($wants_terminal && _is_foreground($tty)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wants_terminal and _is_foreground($tty)) 0 0 0
Condition0%0/3
$wants_terminal and _is_foreground($tty)
!ll&&!rl&&r
000
MC/DC0%0/2
$wants_terminal and _is_foreground($tty)
$wants_terminal _is_foreground($tty)
Truth table0%0/3
A and B
A= $wants_terminalB= _is_foreground($tty)
ABresult
0X0
100
111
782 0 _take_terminal($tty, $pid);
783 0 $has_terminal = 1;
784 }
785 0 kill 'CONT', -$pid;
786 0 ▶ Time::HiRes::alarm($left) if $left > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $left > 0 0 0 0
787 4062 };
788 eval {
789 # only with a timeout: otherwise an alarm is the caller's own business
790 4062 ▶ local $SIG{ALRM} = sub { $timed_out = 1; $cut_short = 1; die "SF_TIMEOUT\n" } if $timed;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if $timed 188 3874 4062
791 # With a timeout the command is killed below, so the wait is cut
792 # short. Otherwise its group is sent the same signal, and it is waited
793 # for as before: perl's waitpid resumes after a handler that returns.
794 local @SIG{@interrupts} = $timed
795 10 ▶ ? (sub { $interrupted = shift; $cut_short = 1; die "SF_INTERRUPTED\n" }) x @interrupts
Subroutine __ANON__: called CC=1 SCAR=0.0
796 52 ▶ : (sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
797 52 my $signal = shift;
798 52 ▶ $interrupted = $signal if ($signal eq 'HUP') || ($signal eq 'TERM');
Branch: 1 branch
BranchTrueFalseTotal
if $signal eq "HUP" or $signal eq "TERM" 34 18 52
Condition66%2/3
$signal eq "HUP" or $signal eq "TERM"
l!l&&r!l&&!r
03418
MC/DC50%1/2
$signal eq "HUP" or $signal eq "TERM"
$signal eq "HUP" $signal eq "TERM"
Truth table66%2/3
A or B
A= $signal eq "HUP"B= $signal eq "TERM"
ABresult
1X1
011
000
799 52 kill $signal, -$pid;
800 4062 ▶ }) x @interrupts;
Branch: 1 branch
BranchTrueFalseTotal
$timed ? : 188 3874 4062
801 # A Ctrl-Z at the terminal, which reaches perl alone unless the
802 # command has the terminal
803 0 ▶ local $SIG{TSTP} = sub { kill 'STOP', -$pid; $suspend->($has_terminal) } if not _ignored('TSTP');
Subroutine __ANON__: not called CC=1 SCAR=0.6
Branch: 1 branch
BranchTrueFalseTotal
unless _ignored("TSTP") 2069 1993 4062
804 # one held since the fork is delivered here, to the handlers above
805 4062 POSIX::sigprocmask(POSIX::SIG_SETMASK(), $caller_mask);
806 4060 ▶ alarm $timeout if $timed;
Branch: 1 branch
BranchTrueFalseTotal
if $timed 186 3874 4060
807 4060 while (1) {
808 4060 my $waited = waitpid $pid, POSIX::WUNTRACED();
809 3942 $status = $?;
810 3942 ▶ last if not (($waited == $pid) && POSIX::WIFSTOPPED(${^CHILD_ERROR_NATIVE}));
Branch: 1 branch
BranchTrueFalseTotal
unless $waited == $pid and POSIX::WIFSTOPPED(${^CHILD_ERROR_NATIVE}) 3942 0 3942
Condition33%1/3
$waited == $pid and POSIX::WIFSTOPPED(${^CHILD_ERROR_NATIVE})
!ll&&!rl&&r
039420
MC/DC0%0/2
$waited == $pid and POSIX::WIFSTOPPED(${^CHILD_ERROR_NATIVE})
$waited == $pid POSIX::WIFSTOPPED(${^CHILD_ERROR_NATIVE})
Truth table33%1/3
A and B
A= $waited == $pidB= POSIX::WIFSTOPPED(${^CHILD_ERROR_NATIVE})
ABresult
0X0
100
111
811 0 my $stop = POSIX::WSTOPSIG(${^CHILD_ERROR_NATIVE});
812 # by a STOP from something other than the terminal, which is the
813 # sender's to continue
814 0 ▶ next if $stop == POSIX::SIGSTOP();
Branch: 1 branch
BranchTrueFalseTotal
if $stop == 19 0 0 0
815 0 ▶ my $wants_terminal = (($stop == POSIX::SIGTTIN()) || ($stop == POSIX::SIGTTOU())) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$stop == 21 || $stop == 22 ? : 0 0 0
Condition0%0/3
$stop == 21 or $stop == 22
l!l&&r!l&&!r
000
MC/DC0%0/2
$stop == 21 or $stop == 22
$stop == 21 $stop == 22
Truth table0%0/3
A or B
A= $stop == 21B= $stop == 22
ABresult
1X1
011
000
816 0 ▶ if ($wants_terminal && _is_foreground($tty)) { # perl has it to give, as "fg" would
Branch: 1 branch
BranchTrueFalseTotal
if ($wants_terminal and _is_foreground($tty)) 0 0 0
Condition0%0/3
$wants_terminal and _is_foreground($tty)
!ll&&!rl&&r
000
MC/DC0%0/2
$wants_terminal and _is_foreground($tty)
$wants_terminal _is_foreground($tty)
Truth table0%0/3
A and B
A= $wants_terminalB= _is_foreground($tty)
ABresult
0X0
100
111
817 0 _take_terminal($tty, $pid);
818 0 $has_terminal = 1;
819 0 kill 'CONT', -$pid;
820 0 next;
821 }
822 # a Ctrl-Z while it had the terminal, or the terminal wanted while
823 # perl is in the background
824 0 ▶ $suspend->($wants_terminal || $has_terminal);
Condition0%0/3
$wants_terminal || $has_terminal
l!l&&r!l&&!r
000
MC/DC0%0/2
$wants_terminal || $has_terminal
$wants_terminal $has_terminal
Truth table0%0/3
A || B
A= $wants_terminalB= $has_terminal
ABresult
1X1
011
000
825 }
826 3942 ▶ alarm 0 if $timed;
Branch: 1 branch
BranchTrueFalseTotal
if $timed 84 3858 3942
827 3942 1;
828 4062 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $SIG{"ALRM"} = sub { $timed_out = 1; $cut_short = 1; die "SF_TIMEOUT\n"; } if $timed; local(@SIG{@interrupts}) = $timed ? (sub { $interrupted = shift(); $cut_short = 1; die "SF_INTERRUPTED\n"; } ) x @interrupts : (sub { my $signal = shift(); $interrupted = $signal if $signal eq "HUP" or $signal eq "TERM"; kill $signal, -$pid; } ) x @interrupts; local $SIG{"TSTP"} = sub { kill "STOP", -$pid; &$suspend($has_terminal); } unless _ignored("TSTP"); POSIX::sigprocmask(2, $caller_mask); alarm $timeout if $timed; while (1) { my $waited = waitpid($pid, 2); $status = $?; last unless $waited == $pid and POSIX::WIFSTOPPED(${^CHILD_ERROR_NATIVE}); my $stop = POSIX::WSTOPSIG(${^CHILD_ERROR_NATIVE}); next if $stop == 19; my $wants_terminal = $stop == 21 || $stop == 22 ? 1 : 0; if ($wants_terminal and _is_foreground($tty)) { _take_terminal($tty, $pid); $has_terminal = 1; kill "CONT", -$pid; next; } ; &$suspend($wants_terminal || $has_terminal); } ; alarm 0 if $timed; 1 } } or do { my $error = $@; my $reaped_status = $?; alarm 0 if $timed; my $waited = waitpid($pid, 1); if ($waited == -1) { $timed_out = 0; $status = $reaped_status; } elsif ($waited == $pid) { $timed_out = 0; $status = $?; } else { kill "KILL", -$pid; waitpid $pid, 0; $status = $?; $timed_out = 0 if defined $interrupted; } ; unless ($cut_short) { _take_terminal($tty, getpgrp()) if $has_terminal; _restore_alarm($caller_alarm, $started); die $error; } } 3942 120 4062
829 120 my $error = $@;
830 120 my $reaped_status = $?; # holds the child's status if waitpid above had already returned
831 120 ▶ alarm 0 if $timed;
Branch: 1 branch
BranchTrueFalseTotal
if $timed 104 16 120
832 # The alarm can land after waitpid has reaped the child but before
833 # "alarm 0" cancels it. The child then finished within its limit, a
834 # second waitpid would return -1 and overwrite its real status, and
835 # its pid is free for the kernel to hand to an unrelated process. So
836 # the group is killed only if the child has not already been reaped.
837 # An interrupt can land in the same window, and is treated the same.
838 120 my $waited = waitpid $pid, POSIX::WNOHANG();
839 120 ▶ if ($waited == -1) { # already reaped by the waitpid inside the eval
Branch: 2 branches
BranchTrueFalseTotal
if ($waited == -1) { } 0 120 120
elsif ($waited == $pid) { } 0 120 120
840 0 $timed_out = 0;
841 0 $status = $reaped_status;
842 } elsif ($waited == $pid) { # exited of its own accord at the deadline
843 0 $timed_out = 0;
844 0 $status = $?;
845 } else { # 0: still running, or stopped, which KILL ends as well
846 120 kill 'KILL', -$pid; # negative pid: the process group, not just the shell
847 120 waitpid $pid, 0;
848 120 $status = $?;
849 120 ▶ $timed_out = 0 if defined $interrupted; # it was the interrupt that killed it
Branch: 1 branch
BranchTrueFalseTotal
if defined $interrupted 10 110 120
850 }
851 # Anything but the two dies above -- a caller's own handler that
852 # died, for an alarm of its own, say -- is passed on as it is, once
853 # the command is gone. Until 0.192 the command was left running,
854 # unwaited for. A flag, not the text of $@, tells them apart, since
855 # Devel::Confess appends a stack trace to that.
856 120 ▶ if (not $cut_short) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cut_short) 16 104 120
857 16 ▶ _take_terminal($tty, getpgrp()) if $has_terminal;
Branch: 1 branch
BranchTrueFalseTotal
if $has_terminal 0 16 16
858 16 _restore_alarm($caller_alarm, $started);
859 16 die $error;
860 }
861 };
862 4046 ▶ _take_terminal($tty, getpgrp()) if $has_terminal;
Branch: 1 branch
BranchTrueFalseTotal
if $has_terminal 0 4046 4046
863 4046 _restore_alarm($caller_alarm, $started);
864 4046 return ($status, $timed_out, '', $interrupted);
865 }
866  
867 # True when the caller ignores signal $name; task() leaves such a signal
868 # ignored, as system() does.
869 20310 ▶sub _ignored {
Subroutine _ignored: called CC=3 SCAR=11.0
870 20310 my $name = shift;
871 20310 ▶ return ((defined $SIG{$name}) && ($SIG{$name} eq 'IGNORE')) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $SIG{$name} && $SIG{$name} eq 'IGNORE' ? : 10007 10303 20310
Condition100%3/3
defined $SIG{$name} and $SIG{$name} eq "IGNORE"
!ll&&!rl&&r
102356810007
MC/DC100%2/2
defined $SIG{$name} and $SIG{$name} eq "IGNORE"
defined $SIG{$name} $SIG{$name} eq "IGNORE"
Truth table100%3/3
A and B
A= defined $SIG{$name}B= $SIG{$name} eq "IGNORE"
ABresult
0X0
100
111
872 }
873  
874 # A handle on perl's controlling terminal, or undef when it has none, as in a
875 # batch job or a daemon. Marked close-on-exec, so that the command does not
876 # inherit it whatever $^F is.
877 4478 ▶sub _controlling_terminal {
Subroutine _controlling_terminal: called CC=4 SCAR=20.1
878 4478 ▶ return undef if $^O eq 'MSWin32';
Branch: 1 branch
BranchTrueFalseTotal
if $^O eq "MSWin32" 0 4478 4478
879 4478 ▶ open my $tty, '+<', '/dev/tty' or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open my $tty, "+<", "/dev/tty" or return undef 0 4478 4478
880 0 ▶ fcntl($tty, Fcntl::F_SETFD(), Fcntl::FD_CLOEXEC()) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
fcntl $tty, 2, 1 or return undef 0 0 0
881 0 return $tty;
882 }
883  
884 # True when perl's process group is the terminal's foreground group.
885 0 ▶sub _is_foreground {
Subroutine _is_foreground: not called CC=3 SCAR=24.8
886 0 my $tty = shift;
887 0 ▶ return 0 if not defined $tty;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tty 0 0 0
888 0 ▶ return (POSIX::tcgetpgrp(fileno $tty) == getpgrp()) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
POSIX::tcgetpgrp(fileno $tty) == getpgrp() ? : 0 0 0
889 }
890  
891 # Make process group $pgrp the foreground group of the terminal $tty. A
892 # process outside the foreground group that tries this is sent SIGTTOU, which
893 # stops it, so SIGTTOU is ignored for the call, as shells do. A failure leaves
894 # things as they were.
895 0 ▶sub _take_terminal {
Subroutine _take_terminal: not called CC=2 SCAR=17.9
896 0 my ($tty, $pgrp) = @_;
897 0 ▶ return if not defined $tty;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tty 0 0 0
898 0 local $SIG{TTOU} = 'IGNORE';
899 0 POSIX::tcsetpgrp(fileno $tty, $pgrp);
900 0 return;
901 }
902  
903 # Put back an alarm the caller had pending when _run_forked began:
904 # $pending seconds were left at $since. One that fell due in the meantime is
905 # delivered now, to the caller's own $SIG{ALRM}, since that is back in place.
906 4078 ▶sub _restore_alarm {
Subroutine _restore_alarm: called CC=3 SCAR=11.0
907 4078 my ($pending, $since) = @_;
908 4078 ▶ return if $pending == 0; # none was set
Branch: 1 branch
BranchTrueFalseTotal
if $pending == 0 4044 34 4078
909 34 my $left = $pending - (Time::HiRes::time() - $since);
910 34 ▶ if ($left > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($left > 0) { } 18 16 34
911 18 alarm POSIX::ceil($left);
912 } else {
913 16 kill 'ALRM', $$;
914 }
915 34 return;
916 }
917  
918 # Flush a handle's buffer without IO::Handle: setting $| true flushes at once,
919 # and its previous value is put back so the caller's autoflush is untouched.
920 17630 ▶sub _flush {
Subroutine _flush: called CC=1 SCAR=0.0
921 17630 my $fh = shift;
922 17630 my $previously_selected = select $fh;
923 17630 my $autoflush = $|;
924 17630 $| = 1;
925 17630 $| = $autoflush;
926 17630 select $previously_selected;
927 17630 return;
928 }
929  
930 # Read the whole of $fh into the scalar $$into, through the translation
931 # layers the caller's own handle had. read() appends into the target buffer,
932 # and the first call asks for the whole file, so the text is allocated once,
933 # in the record, and never copied.
934 7640 ▶sub _slurp_into {
Subroutine _slurp_into: called CC=5 SCAR=16.1
935 7640 my ($fh, $layers, $into) = @_;
936 7640 ▶ seek $fh, 0, 0 or die "cannot rewind a capture file: $!";
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, 0, 0 or die "cannot rewind a capture file: $!" 7640 0 7640
937 7640 binmode $fh; # :raw, then only the layers that translate text
938 # Only these: a caller's STDOUT may be an in-memory "scalar" handle, and
939 # :unix, :perlio and the like are the plumbing a temporary file already has.
940 7640 my @translating = grep { /^(?:crlf|utf8|encoding\(.*\))$/ } @$layers;
941 7640 ▶ binmode $fh, ':' . join(':', @translating) if scalar @translating > 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @translating > 0 2 7638 7640
942 7640 $$into = '';
943 # A length of 0 would read nothing at all, and a child the command put in
944 # the background may still be writing to a file that measured empty; the
945 # 64 KiB floor keeps the loop reading to the real end.
946 7640 my $chunk = max(-s $fh, 65536);
947 7640 while (1) {
948 8034 my $got = read $fh, $$into, $chunk, length $$into;
949 8034 ▶ die "cannot read a capture file: $!" if not defined $got;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $got 0 8034 8034
950 8034 ▶ last if $got == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $got == 0 7640 394 8034
951 }
952 7640 return;
953 }
954  
955 # Run $code with file descriptors 1 and 2 on temporary files, and read what
956 # landed there into $$stdout and $$stderr. Returns what $code returned.
957 #
958 # $to_file, if given, maps a descriptor (1 or 2) to a file the command's
959 # output is appended to instead, for "stdout_file" and "stderr_file"; its
960 # scalar is then left empty, since the point of those options is not to hold
961 # a large output in memory. One file named for both is opened once, so the
962 # two streams interleave in it as they would on a terminal.
963 #
964 # This replaces Capture::Tiny, which 0.17 and earlier used, for memory: it
965 # slurps each capture into a lexical and hands it back through several list
966 # copies, and perls before 5.20 have no copy-on-write to make those free.
967 # Measured with a command printing 100 MB on perl-5.10.1: task() peaked at
968 # 498 MB RSS and took 0.53 s with Capture::Tiny 0.50, and peaks at 108 MB
969 # and takes 0.17 s with this.
970 #
971 # The redirection is done on the descriptors, with POSIX::dup2, not on the
972 # STDOUT and STDERR globs, since descriptors are what a child inherits. So a
973 # caller that has pointed STDOUT at an in-memory scalar still has the
974 # command's output captured; under Capture::Tiny it went straight to the
975 # real fd 1.
976 4478 ▶sub _capture {
Subroutine _capture: called CC=18 SCAR=29.1
977 4478 my ($stdout, $stderr, $code, $to_file) = @_;
978 4478 ▶ $to_file //= {};
Condition50%1/2
$to_file //= {}
l!l
44780
MC/DC0%0/1
$to_file //= {}
$to_file
Truth table50%1/2
A
A= $to_file
Aresult
11
00
979 # A caller may have closed 0, 1 or 2. Each hole is plugged with the null
980 # device, so that the temporary files below cannot land on a standard
981 # descriptor and be closed out from under us when it is restored.
982 # POSIX::open returns the lowest free descriptor, which is $fd itself,
983 # since every lower one is already open by the time the loop reaches it.
984 4478 my @plugs;
985 4478 foreach my $fd (0 .. 2) {
986 13434 my $probe = POSIX::dup($fd);
987 13434 ▶ if (defined $probe) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $probe) 13422 12 13434
988 13422 POSIX::close($probe);
989 13422 next;
990 }
991 12 my $plug = POSIX::open(File::Spec->devnull, POSIX::O_RDWR());
992 12 ▶ die "cannot plug closed descriptor $fd with " . File::Spec->devnull . ": $!" if not defined $plug;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $plug 0 12 12
993 12 push @plugs, $plug;
994 }
995 4478 my %layers = (
996 1 => [PerlIO::get_layers(\*STDOUT, output => 1)],
997 2 => [PerlIO::get_layers(\*STDERR, output => 1)],
998 );
999 4478 my (%file, %named);
1000 4478 foreach my $fd (1, 2) {
1001 8956 my $path = $to_file->{$fd};
1002 8956 ▶ if (not defined $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $path) 8452 504 8956
1003 8452 $file{$fd} = File::Temp->new;
1004 8452 next;
1005 }
1006 504 ▶ if (not defined $named{$path}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $named{$path}) 382 122 504
1007 382 ▶ open $named{$path}, '>>', $path
Branch: 2 branches
BranchTrueFalseTotal
open $named{$path}, ">>", $path or die qq[cannot open "$path" for the command's ] . ($fd == 1 ? "stdout" : "stderr") . ": $!" 382 0 382
$fd == 1 ? : 0 0 0
1008 or die "cannot open \"$path\" for the command's " . (($fd == 1) ? 'stdout' : 'stderr') . ": $!";
1009 }
1010 504 $file{$fd} = $named{$path};
1011 }
1012 # Anything the caller printed but perl has not yet written goes to the
1013 # terminal now, not into the command's capture.
1014 4478 _flush(\*STDOUT);
1015 4478 _flush(\*STDERR);
1016 4478 my %saved;
1017 my @result;
1018 4478 my $ok = eval {
1019 4478 foreach my $fd (1, 2) {
1020 8956 $saved{$fd} = POSIX::dup($fd);
1021 8956 ▶ die "cannot save descriptor $fd: $!" if not defined $saved{$fd};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $saved{$fd} 0 8956 8956
1022 8956 ▶ defined POSIX::dup2(fileno $file{$fd}, $fd)
Branch: 1 branch
BranchTrueFalseTotal
defined POSIX::dup2(fileno $file{$fd}, $fd) or die "cannot redirect descriptor $fd to a capture file: $!" 8956 0 8956
1023 or die "cannot redirect descriptor $fd to a capture file: $!";
1024 }
1025 4478 @result = $code->();
1026 4062 1;
1027 };
1028 4078 my $error = $@;
1029 # as Capture::Tiny did, anything perl itself printed while redirected
1030 # belongs to the capture
1031 4078 _flush(\*STDOUT);
1032 4078 _flush(\*STDERR);
1033 4078 foreach my $fd (sort keys %saved) {
1034 8156 POSIX::dup2($saved{$fd}, $fd);
1035 8156 POSIX::close($saved{$fd});
1036 }
1037 4078 POSIX::close($_) foreach @plugs;
1038 4078 ▶ die $error if not $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 16 4062 4078
1039 4062 ▶ _slurp_into($file{1}, $layers{1}, $stdout) if not defined $to_file->{1};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $to_file->{1} 3816 246 4062
1040 4062 ▶ _slurp_into($file{2}, $layers{2}, $stderr) if not defined $to_file->{2};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $to_file->{2} 3824 238 4062
1041 4062 return @result;
1042 }
1043  
1044 # Run the command once, as task() has set it up, and fill in the fields of
1045 # the record that describe that run: exit, signal, stdout, stderr, timed.out,
1046 # duration, start.time and the CPU times. Returns the name of a signal that
1047 # interrupted a timed run, or undef, and why the command could not be
1048 # launched, or ''.
1049 4478 ▶sub _run_once {
Subroutine _run_once: called CC=38 SCAR=39.1
1050 4478 my ($r, $cmd, $cmd_ref, $cmd_string, $env) = @_; # $env: the real values, which $r->{env} may hide
1051 # _capture redirects fd 1 and fd 2 and nothing else, as Capture::Tiny did
1052 # before it, so before 0.17 the command inherited the caller's fd 0. A
1053 # command that prompts -- "rm" over a write-protected file, "cp -i", git
1054 # asking for a password -- then wrote its question into the captured
1055 # stderr, where nobody could see it, and blocked on the terminal for an
1056 # answer that was never coming. With no "timeout" that hang was
1057 # unbounded; with one, the record blamed the clock (timed.out => 1,
1058 # signal => 9) for what was really a question. fd 0 therefore points at
1059 # the null device for the duration of the run; _run_forked's child
1060 # inherits fd 0 across the fork and exec just as system()'s does.
1061 #
1062 # STDIN itself is reopened rather than localised. The child inherits the
1063 # descriptor, and "open local *STDIN" attaches the glob to some other fd
1064 # while fd 0 goes on pointing at the terminal; reopening STDIN closes
1065 # fd 0, so the new open reclaims it as the lowest free descriptor.
1066 #
1067 # That holds only when STDIN is fd 0, or closed. A caller's STDIN can be
1068 # an in-memory scalar, whose fileno is -1, or some other descriptor; until
1069 # 0.192 such a STDIN was saved with "<&" as well, which perl 5.44.0 could
1070 # not reopen, and task() died "cannot restore STDIN" after the command
1071 # had run. Then the glob is not the command's stdin anyway, so it is left
1072 # alone, and fd 0 itself is pointed at the null device and put back.
1073 4478 my $stdin_fd = fileno STDIN; # undef = closed, -1 = no descriptor, else the descriptor
1074 4478 ▶ my $stdin_is_fd0 = ((not defined $stdin_fd) || ($stdin_fd == 0)) ? 1 : 0; # 1 = reopen the glob
Branch: 1 branch
BranchTrueFalseTotal
!defined($stdin_fd) || $stdin_fd == 0 ? : 4448 30 4478
Condition100%3/3
not defined $stdin_fd or $stdin_fd == 0
l!l&&r!l&&!r
8444030
MC/DC100%2/2
not defined $stdin_fd or $stdin_fd == 0
not defined $stdin_fd $stdin_fd == 0
Truth table100%3/3
not(A) or B
A= not defined $stdin_fdB= $stdin_fd == 0
ABresult
1X1
011
000
1075 4478 my ($saved_stdin, $saved_fd0); # $saved_fd0: undef = fd 0 was closed
1076 4478 ▶ if (($r->{stdin} eq 'devnull') && $stdin_is_fd0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($r->{'stdin'} eq 'devnull' and $stdin_is_fd0) { } 4440 38 4478
elsif ($r->{'stdin'} eq 'devnull') { } 30 8 38
Condition100%3/3
$r->{"stdin"} eq "devnull" and $stdin_is_fd0
!ll&&!rl&&r
8304440
MC/DC100%2/2
$r->{"stdin"} eq "devnull" and $stdin_is_fd0
$r->{"stdin"} eq "devnull" $stdin_is_fd0
Truth table100%3/3
A and B
A= $r->{"stdin"} eq "devnull"B= $stdin_is_fd0
ABresult
0X0
100
111
1077 # a caller may legitimately have closed STDIN: there is then nothing
1078 # to save, and it is closed again below rather than restored
1079 4440 ▶ if (defined $stdin_fd) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $stdin_fd) 4436 4 4440
1080 4436 ▶ open $saved_stdin, '<&', \*STDIN
Branch: 1 branch
BranchTrueFalseTotal
open $saved_stdin, "<&", \*STDIN or die qq[cannot save STDIN before running "$cmd_string": $!] 4436 0 4436
1081 or die "cannot save STDIN before running \"$cmd_string\": $!";
1082 }
1083 4440 ▶ open STDIN, '<', File::Spec->devnull
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<", "File::Spec"->devnull or die 'cannot reopen STDIN on ' . "File::Spec"->devnull . ": $!" 4440 0 4440
1084 or die 'cannot reopen STDIN on ' . File::Spec->devnull . ": $!";
1085 } elsif ($r->{stdin} eq 'devnull') {
1086 30 $saved_fd0 = POSIX::dup(0);
1087 30 my $null = POSIX::open(File::Spec->devnull, POSIX::O_RDONLY());
1088 30 ▶ die 'cannot open ' . File::Spec->devnull . " for the command's stdin: $!" if not defined $null;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $null 0 30 30
1089 30 ▶ if ($null != 0) { # 0 itself when fd 0 was closed, as the lowest free descriptor
Branch: 1 branch
BranchTrueFalseTotal
if ($null != 0) 0 30 30
1090 0 ▶ defined POSIX::dup2($null, 0) or die 'cannot point descriptor 0 at ' . File::Spec->devnull . ": $!";
Branch: 1 branch
BranchTrueFalseTotal
defined POSIX::dup2($null, 0) or die 'cannot point descriptor 0 at ' . "File::Spec"->devnull . ": $!" 0 0 0
1091 0 POSIX::close($null);
1092 }
1093 }
1094 # "env": the command's environment is the caller's with these changes,
1095 # and the caller's is put back when this returns. %ENV is localised only
1096 # when there is something to change, so that a task without "env" does
1097 # not touch the environment at all.
1098 4478 ▶ local %ENV = %ENV if (scalar keys %$env > 0) || ($r->{threads} > 0);
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %$env > 0 or $r->{"threads"} > 0 228 4250 4478
Condition100%3/3
scalar keys %$env > 0 or $r->{"threads"} > 0
l!l&&r!l&&!r
144844250
MC/DC100%2/2
scalar keys %$env > 0 or $r->{"threads"} > 0
scalar keys %$env > 0 $r->{"threads"} > 0
Truth table100%3/3
A or B
A= scalar keys %$env > 0B= $r->{"threads"} > 0
ABresult
1X1
011
000
1099 4478 foreach my $name (keys %$env) {
1100 274 ▶ if (defined $env->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $env->{$name}) { } 204 70 274
1101 204 $ENV{$name} = $env->{$name};
1102 } else {
1103 70 delete $ENV{$name}; # undef: the command runs without it
1104 }
1105 }
1106 # "threads", told to the command, as Snakemake's {threads} is: the command
1107 # decides what to do with it, since only it knows its own option for it
1108 4478 ▶ $ENV{SIMPLEFLOW_THREADS} = $r->{threads} if $r->{threads} > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"threads"} > 0 84 4394 4478
1109 4478 my %to_file;
1110 4478 ▶ $to_file{1} = $r->{'stdout_file'} if $r->{'stdout_file'} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"stdout_file"} ne "" 256 4222 4478
1111 4478 ▶ $to_file{2} = $r->{'stderr_file'} if $r->{'stderr_file'} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"stderr_file"} ne "" 248 4230 4478
1112 4478 my @cpu_before = times;
1113 4478 my $t0 = Time::HiRes::time();
1114 4478 $r->{'start.time'} = $t0;
1115 4478 my @run_result;
1116 # Wrapped in eval so that fd 0 is restored even when the run dies --
1117 # _run_forked dies if fork() fails -- rather than leaving a caller
1118 # that traps the exception without its stdin.
1119 4478 my $run_ok = eval {
1120 4478 ▶ @run_result = _capture(\$r->{stdout}, \$r->{stderr}, sub {
Subroutine __ANON__: called CC=6 SCAR=25.6
1121 # The command gets the terminal's foreground only when it has the
1122 # terminal as its stdin, the one case where it could need it.
1123 return _run_forked($cmd, $r->{timeout},
1124 4478 ▶ (($r->{stdin} eq 'inherit') && (-t STDIN)) ? 1 : 0) if $^O ne 'MSWin32';
Branch: 2 branches
BranchTrueFalseTotal
if $^O ne "MSWin32" 4478 0 4478
$r->{'stdin'} eq 'inherit' && -t STDIN ? : 0 4478 4478
Condition66%2/3
$r->{"stdin"} eq "inherit" and -t STDIN
!ll&&!rl&&r
447080
MC/DC0%0/2
$r->{"stdin"} eq "inherit" and -t STDIN
$r->{"stdin"} eq "inherit" -t STDIN
Truth table66%2/3
A and B
A= $r->{"stdin"} eq "inherit"B= -t STDIN
ABresult
0X0
100
111
1125 # MSWin32: system(), which forks before it execs, and when the exec
1126 # fails its child warns "Can't exec" -- which "warnings FATAL"
1127 # makes a die, in the forked child, inside this eval. Until 0.18
1128 # that child unwound out of task() and ran the rest of the
1129 # caller's program as a second copy, while the parent read the
1130 # copy's exit status: a command that did not exist was reported
1131 # as exit 0, "done".
1132 447 ▶ no warnings 'exec';
Subroutine BEGIN: called CC=1 SCAR=0.0
1133 # The block form never uses the shell, even for a one-element list.
1134 # Until 0.18 plain system(@list) was used, and perl hands a list of
1135 # one to the shell: cmd => ['echo hi; rm x'] ran both commands.
1136 my $raw_status = ($cmd_ref eq 'ARRAY')
1137 0 ▶ ? system({ $cmd->[0] } @{ $cmd })
Branch: 1 branch
BranchTrueFalseTotal
$cmd_ref eq 'ARRAY' ? : 0 0 0
1138 : system($cmd);
1139 # $! says why a -1 happened, and is read here, before _capture's
1140 # own system calls can overwrite it. Until 0.19 it was thrown away.
1141 0 ▶ return ($raw_status, 0, ($raw_status == -1) ? "$!" : '');
Branch: 1 branch
BranchTrueFalseTotal
$raw_status == -1 ? : 0 0 0
1142 4478 }, \%to_file);
1143 4062 1;
1144 };
1145 4078 my $run_error = $@;
1146 4078 my $t1 = Time::HiRes::time();
1147 4078 my @cpu_after = times;
1148 4078 ▶ if (($r->{stdin} eq 'devnull') && (not $stdin_is_fd0)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($r->{'stdin'} eq 'devnull' and not $stdin_is_fd0) { } 28 4050 4078
elsif ($r->{'stdin'} eq 'devnull') { } 4046 4 4050
Condition100%3/3
$r->{"stdin"} eq "devnull" and not $stdin_is_fd0
!ll&&!rl&&r
4404628
MC/DC100%2/2
$r->{"stdin"} eq "devnull" and not $stdin_is_fd0
$r->{"stdin"} eq "devnull" not $stdin_is_fd0
Truth table100%3/3
A and not(B)
A= $r->{"stdin"} eq "devnull"B= not $stdin_is_fd0
ABresult
0X0
100
111
1149 28 ▶ if (defined $saved_fd0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $saved_fd0) { } 0 28 28
1150 0 ▶ defined POSIX::dup2($saved_fd0, 0)
Branch: 1 branch
BranchTrueFalseTotal
defined POSIX::dup2($saved_fd0, 0) or die qq[cannot restore descriptor 0 after running "$cmd_string": $!] 0 0 0
1151 or die "cannot restore descriptor 0 after running \"$cmd_string\": $!";
1152 0 POSIX::close($saved_fd0);
1153 } else {
1154 28 POSIX::close(0); # it was closed when we were called; leave it that way
1155 }
1156 } elsif ($r->{stdin} eq 'devnull') {
1157 4046 ▶ if (defined $saved_stdin) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $saved_stdin) { } 4044 2 4046
1158 4044 ▶ open STDIN, '<&', $saved_stdin
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<&", $saved_stdin or die qq[cannot restore STDIN after running "$cmd_string": $!] 4044 0 4044
1159 or die "cannot restore STDIN after running \"$cmd_string\": $!";
1160 4044 close $saved_stdin;
1161 } else {
1162 2 close STDIN; # it was closed when we were called; leave it that way
1163 }
1164 }
1165 4078 ▶ die $run_error if not $run_ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $run_ok 16 4062 4078
1166 4062 $r->{duration} = $t1 - $t0;
1167 # The children's user and system time, which counts every descendant the
1168 # command waited for. times() counts in clock ticks, 1/100 s on Linux
1169 # (sysconf(_SC_CLK_TCK) is 100 on perl 5.10.1 and 5.44.0 here), so the
1170 # difference is rounded to the millisecond to drop the float noise of
1171 # subtracting two tick counts, without losing anything a tick can say.
1172 4062 $r->{'cpu.user'} = sprintf('%.3f', $cpu_after[2] - $cpu_before[2]) + 0;
1173 4062 $r->{'cpu.system'} = sprintf('%.3f', $cpu_after[3] - $cpu_before[3]) + 0;
1174 # $interrupted: undef, or the name of a signal ('INT', 'TERM', ...) that
1175 # arrived while a timed command ran; $launch_error: '', or why system()
1176 # could not start the command
1177 4062 my ($status, $timed_out, $launch_error, $interrupted) = @run_result;
1178 4062 ▶ $launch_error //= '';
Condition50%1/2
$launch_error //= ""
l!l
40620
MC/DC0%0/1
$launch_error //= ""
$launch_error
Truth table50%1/2
A
A= $launch_error
Aresult
11
00
1179 4062 ▶ $r->{'timed.out'} = $timed_out ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$timed_out ? : 94 3968 4062
1180 # Decode the raw wait status. On Unix the low 7 bits hold the death
1181 # signal and the high byte holds the exit code. The signal MUST be read
1182 # from the raw status *before* shifting -- the old code shifted first and
1183 # then did ($exit & 127), so the signal was always 0 and could never
1184 # detect a kill by signal 9/15. Windows has no POSIX signals, and a -1
1185 # return from system() means the command never launched.
1186 4062 ▶ if (!defined $status || $status == -1) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $status or $status == -1) { } 16 4046 4062
elsif ($^O eq 'MSWin32') { } 0 4046 4046
Condition66%2/3
not defined $status or $status == -1
l!l&&r!l&&!r
0164046
MC/DC50%1/2
not defined $status or $status == -1
not defined $status $status == -1
Truth table66%2/3
not(A) or B
A= not defined $statusB= $status == -1
ABresult
1X1
011
000
1187 16 $r->{'exit'} = -1;
1188 16 $r->{signal} = 0;
1189 } elsif ($^O eq 'MSWin32') {
1190 0 $r->{signal} = 0;
1191 0 $r->{'exit'} = $status >> 8;
1192 } else {
1193 4046 $r->{signal} = $status & 127; # taken from the raw status, not from the exit code
1194 4046 $r->{'exit'} = $status >> 8;
1195 }
1196 # Remove trailing whitespace. This walks back from the end rather than
1197 # using s/\s+$//, as 0.17 did, which scans forward from the start of the
1198 # capture and, on a perl with copy-on-write, copies the whole of it first.
1199 # Measured on a 100 MB stdout: 0.09 s on perl-5.10.1, and on 5.44.0 0.13 s
1200 # and peak RSS 107 MB -> 205 MB, to remove one newline. The walk costs
1201 # only the whitespace it removes.
1202 4062 foreach my $std ('stderr', 'stdout') {
1203 8124 my $end = length $r->{$std};
1204 8124 ▶ $end-- while ($end > 0) && (substr($r->{$std}, $end - 1, 1) =~ /\s/);
Branch: 1 branch
BranchTrueFalseTotal
$end > 0 and substr($r->{$std}, $end - 1, 1) =~ /\s/ and do { --$end } 74 8124 8198
Condition100%3/3
$end > 0 and substr($r->{$std}, $end - 1, 1) =~ /\s/
!ll&&!rl&&r
773039474
MC/DC100%2/2
$end > 0 and substr($r->{$std}, $end - 1, 1) =~ /\s/
$end > 0 substr($r->{$std}, $end - 1, 1) =~ /\s/
Truth table100%3/3
A and B
A= $end > 0B= substr($r->{$std}, $end - 1, 1) =~ /\s/
ABresult
0X0
100
111
1205 8124 substr($r->{$std}, $end) = '';
1206 }
1207 # Nothing ran, so nothing wrote to stderr; what a shell would have said
1208 # there is the next best thing, and the one place a caller under die => 0
1209 # can read it.
1210 $r->{stderr} = "cannot run \"$cmd_string\": $launch_error"
1211 4062 ▶ if ($launch_error ne '') && ($r->{stderr} eq '') && ($r->{'stderr_file'} eq '');
Branch: 1 branch
BranchTrueFalseTotal
if $launch_error ne "" and $r->{"stderr"} eq "" and $r->{"stderr_file"} eq "" 16 4046 4062
Condition66%4/6
$launch_error ne "" and $r->{"stderr"} eq "" and $r->{"stderr_file"} eq ""
!ll&&!rl&&r
4046016
$launch_error ne "" and $r->{"stderr"} eq ""
!ll&&!rl&&r
4046016
MC/DC33%1/3
$launch_error ne "" and $r->{"stderr"} eq "" and $r->{"stderr_file"} eq ""
$launch_error ne "" $r->{"stderr"} eq "" $r->{"stderr_file"} eq ""
Truth table50%2/4
A and B and C
A= $launch_error ne ""B= $r->{"stderr"} eq ""C= $r->{"stderr_file"} eq ""
ABCresult
0XX0
10X0
1100
1111
1212 4062 return ($interrupted, $launch_error);
1213 }
1214  
1215 # True when a directory holds nothing but "." and "..". One that cannot be
1216 # read is not called empty: that is a different problem, and not this one's.
1217 188 ▶sub _is_empty_dir {
Subroutine _is_empty_dir: called CC=3 SCAR=11.0
1218 188 my $path = shift;
1219 188 ▶ opendir(my $dh, $path) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $path or return 0 188 0 188
1220 188 my @entries = grep { !/\A\.\.?\z/ } readdir $dh;
1221 188 closedir $dh;
1222 188 ▶ return (scalar @entries == 0) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
scalar @entries == 0 ? : 44 144 188
1223 }
1224  
1225 # The command as it is actually run, as an array ref of words, when it is to
1226 # run inside something -- an executor, a container, a conda environment, a
1227 # wrapper -- or undef when it runs as it is. The layers nest in that order,
1228 # outermost first: the executor starts the container, the container runs
1229 # conda, and conda runs the wrapper, which runs the command. A string command
1230 # keeps its shell features by being handed to the shell inside all of them.
1231 5198 ▶sub _wrapped_cmd {
Subroutine _wrapped_cmd: called CC=17 SCAR=28.3
1232 5198 my ($r, $cmd) = @_;
1233 5198 my @layers;
1234 5198 ▶ if ($r->{executor} eq 'slurm') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{"executor"} eq "slurm") 28 5170 5198
1235 # srun blocks until the job step ends, and passes its exit status on,
1236 # so task() waits for it and reads it as for any other command
1237 push @layers, 'srun',
1238 (($r->{threads} > 0) ? "--cpus-per-task=$r->{threads}" : ()),
1239 (($r->{mem} ne '') ? "--mem=$r->{mem}" : ()),
1240 (($r->{walltime} ne '') ? "--time=$r->{walltime}" : ()),
1241 28 ▶ @{ $r->{'executor_args'} };
Branch: 3 branches
BranchTrueFalseTotal
$r->{'threads'} > 0 ? : 6 22 28
$r->{'mem'} ne '' ? : 6 22 28
$r->{'walltime'} ne '' ? : 6 22 28
1242 }
1243 5198 ▶ if ($r->{container} ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{"container"} ne "") 34 5164 5198
1244 34 my $cwd = $r->{dir}; # the step's working directory, mounted at the same path
1245 34 ▶ if (($r->{'container_engine'} eq 'docker') || ($r->{'container_engine'} eq 'podman')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{'container_engine'} eq 'docker' or $r->{'container_engine'} eq 'podman') { } 28 6 34
Condition100%3/3
$r->{"container_engine"} eq "docker" or $r->{"container_engine"} eq "podman"
l!l&&r!l&&!r
6226
MC/DC100%2/2
$r->{"container_engine"} eq "docker" or $r->{"container_engine"} eq "podman"
$r->{"container_engine"} eq "docker" $r->{"container_engine"} eq "podman"
Truth table100%3/3
A or B
A= $r->{"container_engine"} eq "docker"B= $r->{"container_engine"} eq "podman"
ABresult
1X1
011
000
1246 push @layers, $r->{'container_engine'}, 'run', '--rm',
1247 (($r->{stdin} eq 'inherit') ? '-i' : ()),
1248 # docker runs as root unless told otherwise, and a file root
1249 # makes in the mounted directory is root's; podman, rootless,
1250 # maps the caller's own user already
1251 (($r->{'container_engine'} eq 'docker') && ($^O ne 'MSWin32')
1252 ? ('--user', $> . ':' . (split ' ', $))[0]) : ()),
1253 '-v', "$cwd:$cwd", '-w', $cwd,
1254 # the variables "env" and "threads" set, by name: the engine
1255 # copies each value from its own environment, which is the
1256 # command's
1257 22 ▶ (map { ('-e', $_) } grep { defined $r->{env}{$_} } sort keys %{ $r->{env} }),
Branch: 1 branch
BranchTrueFalseTotal
$r->{'threads'} > 0 ? : 22 6 28
1258 (($r->{threads} > 0) ? ('-e', 'SIMPLEFLOW_THREADS') : ()),
1259 28 ▶ @{ $r->{'container_args'} }, $r->{container};
Branch: 2 branches
BranchTrueFalseTotal
$r->{'stdin'} eq 'inherit' ? : 22 6 28
$r->{'container_engine'} eq 'docker' && $^O ne 'MSWin32' ? : 6 22 28
Condition66%2/3
$r->{"container_engine"} eq "docker" and $^O ne "MSWin32"
!ll&&!rl&&r
2206
MC/DC50%1/2
$r->{"container_engine"} eq "docker" and $^O ne "MSWin32"
$r->{"container_engine"} eq "docker" $^O ne "MSWin32"
Truth table66%2/3
A and B
A= $r->{"container_engine"} eq "docker"B= $^O ne "MSWin32"
ABresult
0X0
100
111
1260 } else { # singularity and apptainer, which pass the environment through themselves
1261 push @layers, $r->{'container_engine'}, 'exec', '--bind', $cwd, '--pwd', $cwd,
1262 6 @{ $r->{'container_args'} }, $r->{container};
1263 }
1264 }
1265 5198 ▶ if ($r->{'conda_env'} ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{"conda_env"} ne "") 28 5170 5198
1266 # --no-capture-output, or conda holds the command's output back until
1267 # it ends; a path names a prefix, anything else an environment's name
1268 push @layers, 'conda', 'run', '--no-capture-output',
1269 28 ▶ (($r->{'conda_env'} =~ m{[/\\]}) ? '-p' : '-n'), $r->{'conda_env'};
Branch: 1 branch
BranchTrueFalseTotal
$r->{'conda_env'} =~ m([/\\]) ? : 22 6 28
1270 }
1271 5198 push @layers, @{ $r->{wrapper} };
1272 5198 ▶ return undef if scalar @layers == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @layers == 0 4960 238 5198
1273 238 ▶ return [@layers, @$cmd] if ref $cmd eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $cmd eq "ARRAY" 208 30 238
1274 30 ▶ return [@layers, ($^O eq 'MSWin32') ? ('cmd.exe', '/c', $cmd) : ('/bin/sh', '-c', $cmd)];
Branch: 1 branch
BranchTrueFalseTotal
$^O eq 'MSWin32' ? : 0 30 30
1275 }
1276  
1277 # What "stale_cmd" compares: a digest of everything that decides what the
1278 # command does, other than its inputs -- the command, whether it went to a
1279 # shell, the environment it was given, and what it runs inside. Separated by
1280 # NUL, which cannot occur in a command's words or the environment, so that
1281 # ['a b'] and ['a', 'b'] differ.
1282 #
1283 # What it runs inside went in as "wrapped.cmd", which is space-joined, so
1284 # until 0.192 a wrapper of ['w', 'a b'] and one of ['w', 'a', 'b'] had the
1285 # same digest. The words of those layers -- $run_cmd, less the command's own
1286 # part -- are now added with their boundaries, but only when one of them holds
1287 # a space: without one, the space-joined form is already unambiguous, and
1288 # leaving the digest as it was keeps every digest 0.191 recorded valid, so an
1289 # upgrade does not re-run every "stale_cmd" step. Likewise "threads", which
1290 # reaches a local command only as SIMPLEFLOW_THREADS, is added only when it
1291 # is set; under SLURM it is in srun's --cpus-per-task already.
1292 512 ▶sub _command_signature {
Subroutine _command_signature: called CC=9 SCAR=22.5
1293 512 my ($r, $cmd, $run_cmd) = @_;
1294 512 ▶ my @parts = (ref $cmd eq 'ARRAY') ? ('list', @$cmd) : ('string', $cmd);
Branch: 1 branch
BranchTrueFalseTotal
ref $cmd eq 'ARRAY' ? : 512 0 512
1295 512 ▶ push @parts, 'env', map { (defined $r->{env}{$_}) ? "$_=$r->{env}{$_}" : $_ } sort keys %{ $r->{env} };
Branch: 1 branch
BranchTrueFalseTotal
defined $r->{'env'}{$_} ? : 24 0 24
1296 512 push @parts, 'wrapped', $r->{'wrapped.cmd'};
1297 512 ▶ if ($r->{'wrapped.cmd'} ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{"wrapped.cmd"} ne "") 86 426 512
1298 # a string command is the last word, after the shell and its -c
1299 86 ▶ my $own_words = (ref $cmd eq 'ARRAY') ? scalar @$cmd : 1;
Branch: 1 branch
BranchTrueFalseTotal
ref $cmd eq 'ARRAY' ? : 86 0 86
1300 86 my @layers = @{ $run_cmd }[0 .. $#$run_cmd - $own_words];
1301 86 ▶ push @parts, 'layers', @layers if grep { / / } @layers;
Branch: 1 branch
BranchTrueFalseTotal
if grep {/ /;} @layers 86 0 86
1302 }
1303 512 ▶ push @parts, 'threads', $r->{threads} if ($r->{threads} > 0) && ($r->{executor} ne 'slurm');
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"threads"} > 0 and $r->{"executor"} ne "slurm" 78 434 512
Condition66%2/3
$r->{"threads"} > 0 and $r->{"executor"} ne "slurm"
!ll&&!rl&&r
434078
MC/DC50%1/2
$r->{"threads"} > 0 and $r->{"executor"} ne "slurm"
$r->{"threads"} > 0 $r->{"executor"} ne "slurm"
Truth table66%2/3
A and B
A= $r->{"threads"} > 0B= $r->{"executor"} ne "slurm"
ABresult
0X0
100
111
1304 512 my $joined = join "\0", @parts;
1305 512 ▶ utf8::encode($joined) if utf8::is_utf8($joined); # md5_hex takes bytes
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($joined) 0 512 512
1306 512 return md5_hex($joined);
1307 }
1308 # Where the command that made a set of outputs is kept: .simpleflow/cmd/ in
1309 # the working directory, as the lock files are, one file per set of outputs,
1310 # named for their absolute paths.
1311 2894 ▶sub _signature_file {
Subroutine _signature_file: called CC=2 SCAR=6.9
1312 2894 my @absolute = sort map { File::Spec->rel2abs($_) } @_;
1313 2894 my $joined = join "\0", @absolute;
1314 2894 ▶ utf8::encode($joined) if utf8::is_utf8($joined);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($joined) 36 2858 2894
1315 2894 return File::Spec->catfile('.simpleflow', 'cmd', md5_hex($joined));
1316 }
1317 448 ▶sub _read_signature {
Subroutine _read_signature: called CC=5 SCAR=16.1
1318 448 my $file = shift;
1319 # not through a symbolic link; see _metadata_dir
1320 448 foreach my $dir ('.simpleflow', File::Spec->catdir('.simpleflow', 'cmd')) {
1321 896 ▶ die "\"$dir\" in " . getcwd() . ' is a symbolic link, which is not followed for the command records of "stale_cmd"; make it a directory'
Branch: 1 branch
BranchTrueFalseTotal
if -l $dir 16 880 896
1322 if -l $dir;
1323 }
1324 432 ▶ sysopen(my $fh, $file, Fcntl::O_RDONLY() | $O_NOFOLLOW) or return undef; # none on record
Branch: 1 branch
BranchTrueFalseTotal
sysopen my $fh, $file, 0 | $O_NOFOLLOW or return undef 220 212 432
1325 220 my $signature = <$fh>;
1326 220 close $fh;
1327 220 ▶ return undef if not defined $signature;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $signature 0 220 220
1328 220 chomp $signature;
1329 220 return $signature;
1330 }
1331 428 ▶sub _write_signature {
Subroutine _write_signature: called CC=4 SCAR=15.6
1332 428 my ($file, $signature) = @_;
1333 428 my ($volume, $dirs) = File::Spec->splitpath($file);
1334 # canonpath, to drop the trailing slash, through which -l would follow a link
1335 428 my $dir = File::Spec->canonpath(File::Spec->catpath($volume, $dirs, ''));
1336 428 _metadata_dir('.simpleflow', 'the command records of "stale_cmd"');
1337 428 _metadata_dir($dir, 'the command records of "stale_cmd"');
1338 # Written under another name and renamed into place, so that a run killed
1339 # part-way through never leaves half a signature, which would read as a
1340 # changed command. The other name is File::Temp's, made with O_EXCL: until
1341 # 0.192 it was "<file>.<pid>", opened with truncation, which followed a
1342 # link planted under that predictable name. rename() replaces a link at
1343 # $file itself, rather than following it.
1344 428 my $partial = File::Temp->new(DIR => $dir, TEMPLATE => 'partial-XXXXXXXX', UNLINK => 0);
1345 428 my $partial_name = $partial->filename;
1346 428 ▶ my $ok = (print {$partial} "$signature\n") && (close $partial) && (rename $partial_name, $file);
Condition33%2/6
print({$partial;} "$signature\n") && close $partial && rename($partial_name, $file)
!ll&&!rl&&r
00428
print {$partial;} "$signature\n" and close $partial
!ll&&!rl&&r
00428
MC/DC0%0/3
print({$partial;} "$signature\n") && close $partial && rename($partial_name, $file)
print {$partial;} "$signature\n" close $partial rename($partial_name, $file)
Truth table25%1/4
A and B && C
A= print {$partial;} "$signature\n"B= close $partialC= rename($partial_name, $file)
ABCresult
0XX0
10X0
1100
1111
1347 428 ▶ if (not $ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 428 428
1348 0 my $error = $!;
1349 0 unlink $partial_name;
1350 0 die "cannot record the command for \"stale_cmd\" in \"$file\": $error";
1351 }
1352 428 return;
1353 }
1354  
1355 # The last lines of a failed command's stderr, for the end of the message
1356 # that reports it: the lines that usually say what went wrong. Six, because
1357 # that is what the failures measured needed, run here: a make over a failing
1358 # compile puts the compiler's "error:" line 5th from the end, after the source
1359 # line, the caret and a note, with make's own "Error 1" last; a Python
1360 # traceback needs its last 4 for the failing frame and the exception; perl's
1361 # die, sort and R's stop() need 1 or 2. Each is clipped at 300 characters: the
1362 # longest line in those, a traceback's "File ..." line, was 130. Blank lines
1363 # are skipped. Read back from stderr_file when that is where stderr went, from
1364 # its last 64 KiB, far more than 6 lines of 300 need.
1365 447 my $STDERR_TAIL_LINES = 6;
1366 447 my $STDERR_TAIL_WIDTH = 300;
1367 2116 ▶sub _stderr_tail {
Subroutine _stderr_tail: called CC=7 SCAR=19.7
1368 2116 my $r = shift;
1369 2116 my $text = $r->{stderr};
1370 2116 ▶ if ($r->{'stderr_file'} ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{"stderr_file"} ne "") 176 1940 2116
1371 176 $text = '';
1372 176 ▶ if (open my $fh, '<', $r->{'stderr_file'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<", $r->{"stderr_file"}) 176 0 176
1373 176 my $size = -s $fh;
1374 176 ▶ seek $fh, (($size > 65536) ? $size - 65536 : 0), 0;
Branch: 1 branch
BranchTrueFalseTotal
$size > 65536 ? : 0 176 176
1375 176 local $/;
1376 176 ▶ $text = <$fh> // '';
Condition50%1/2
readline $fh // ""
l!l
1760
MC/DC0%0/1
readline $fh // ""
readline $fh
Truth table50%1/2
A
A= readline $fh
Aresult
11
00
1377 176 close $fh;
1378 }
1379 }
1380 2116 my @lines = grep { /\S/ } split /\r?\n/, $text;
1381 2116 ▶ @lines = @lines[-$STDERR_TAIL_LINES .. -1] if scalar @lines > $STDERR_TAIL_LINES;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @lines > $STDERR_TAIL_LINES 58 2058 2116
1382 return map {
1383 2116 ▶ (length $_ > $STDERR_TAIL_WIDTH) ? substr($_, 0, $STDERR_TAIL_WIDTH) . '...' : $_
Branch: 1 branch
BranchTrueFalseTotal
length $_ > $STDERR_TAIL_WIDTH ? : 0 556 556
1384 } @lines;
1385 }
1386  
1387 # Every reason a run failed, for the one message that reports it. Until 0.19
1388 # the reasons were tried in turn and the missing-output one came first, so a
1389 # step that exited non-zero, or timed out, and left an output missing died
1390 # saying only that the output was missing.
1391 2116 ▶sub _why_failed {
Subroutine _why_failed: called CC=8 SCAR=20.8
1392 2116 my ($r, $interrupted, $launch_error, @missing) = @_;
1393 2116 my @why;
1394 2116 ▶ if ($r->{'timed.out'}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($r->{'timed.out'}) { } 94 2022 2116
elsif (defined $interrupted) { } 44 1978 2022
elsif ($r->{'signal'}) { } 138 1840 1978
1395 94 push @why, "was killed after exceeding its $r->{timeout}s timeout";
1396 } elsif (defined $interrupted) {
1397 44 push @why, "was killed when task() received SIG$interrupted";
1398 } elsif ($r->{signal}) {
1399 138 push @why, "was killed by signal $r->{signal}";
1400 }
1401 2116 ▶ if ($r->{'exit'} == -1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($r->{'exit'} == -1) { } 16 2100 2116
elsif ($r->{'exit'} != 0) { } 1660 440 2100
1402 16 ▶ push @why, 'exited -1: it could not be launched' . (($launch_error ne '') ? " ($launch_error)" : '');
Branch: 1 branch
BranchTrueFalseTotal
$launch_error ne '' ? : 16 0 16
1403 } elsif ($r->{'exit'} != 0) {
1404 1660 push @why, "exited $r->{'exit'}";
1405 }
1406 2116 ▶ if (scalar @missing > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @missing > 0) 312 1804 2116
1407 312 push @why, 'these output files should have been made but are missing: ' . join(', ', @missing);
1408 }
1409 2116 return @why;
1410 }
1411  
1412 6508 ▶sub task {
Subroutine task: called CC=192 SCAR=52.7
Pod documented
1413 # Devel::Confess for this call and nothing after it: see _confess_here.
1414 # First, so that even the argument errors below carry a trace.
1415 6508 local $SIG{__DIE__} = $SIG{__DIE__};
1416 6508 local $SIG{__WARN__} = $SIG{__WARN__};
1417 6508 local $Devel::Confess::OLD_SIG{__DIE__} = $Devel::Confess::OLD_SIG{__DIE__};
1418 6508 local $Devel::Confess::OLD_SIG{__WARN__} = $Devel::Confess::OLD_SIG{__WARN__};
1419 6508 local $Devel::Confess::OPTIONS{color} = $Devel::Confess::OPTIONS{color};
1420 6508 _confess_here();
1421 6508 my $current_sub = (split(/::/,(caller(0))[3]))[-1];
1422 # Accept either a single hash ref -- task({ cmd => ... }) -- or a flat
1423 # key/value list -- task(cmd => ...). A lone non-hashref scalar, or an
1424 # odd-length list, can't be read either way and is fatal.
1425 6508 my $given;
1426 6508 ▶ if (@_ == 1 && ref $_[0] eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (@_ == 1 and ref $_[0] eq 'HASH') { } 632 5876 6508
elsif (@_ % 2 == 0) { } 5870 6 5876
Condition66%2/3
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
58760632
MC/DC50%1/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table66%2/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
1427 632 $given = $_[0];
1428 } elsif (@_ % 2 == 0) {
1429 5870 $given = { @_ };
1430 } else {
1431 6 die "args to $current_sub must be a hash ref (e.g. $current_sub({ cmd => ... })) or a flat key/value list (e.g. $current_sub(cmd => ...)); got an odd-length list";
1432 }
1433 # parallel() runs each task in a child of its own, where the caller would
1434 # be parallel() itself; it sets $CALLER to its own caller instead
1435 6502 ▶ my @c = (defined $CALLER) ? ('main', @$CALLER) : caller;
Branch: 1 branch
BranchTrueFalseTotal
defined $SimpleFlow::CALLER ? : 100 6402 6502
1436 6502 my @reqd_args = (
1437 'cmd', # the shell command
1438 );
1439 6502 my @undef_args = grep { !defined $given->{$_}} @reqd_args;
1440 6502 ▶ if (scalar @undef_args > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 2 6500 6502
1441 2 p @undef_args, output => 'STDERR';
1442 2 die 'the above args are necessary, but were not defined.';
1443 }
1444 6500 my @defined_args = ( @reqd_args,
1445 'conda_env', # name or path of a conda environment to run the command in
1446 'container', # container image to run the command in
1447 'container_args', # array ref: more arguments for the container engine, before the image
1448 'container_engine', # 'docker' (the default), 'podman', 'singularity' or 'apptainer'
1449 'die', # die if not successful; 0 or 1
1450 'dir', # directory to run the step in; its file names are relative to it
1451 'dry_run', # dry run or not
1452 'env', # hash ref: environment variables for the command; undef removes one
1453 'env_secret', # array ref: names in "env" whose values are never printed, logged or traced
1454 'executor', # 'local' (the default) or 'slurm': where the command runs
1455 'executor_args', # array ref: more arguments for the executor (srun)
1456 'input_dir', # a single input directory; the convenience form of "input_dirs"
1457 'input_dirs', # directories that must exist before running; SCALAR or ARRAY
1458 'input_file', # a single input file; the convenience form of "input_files"
1459 'input_files', # check for input files; SCALAR or ARRAY
1460 'lock', # bool; hold a lock on the outputs, so a second run waits for this one
1461 'log_fh',
1462 'mem', # memory to ask the executor for: a number, and K, M, G or T
1463 'note', # a note for the log
1464 'on_failure', # code ref, called with the record when the command ran and failed
1465 'on_success', # code ref, called with the record when the command ran and succeeded
1466 'output_dir', # a single output directory; the convenience form of "output_dirs"
1467 'output_dirs', # directories the step makes; SCALAR or ARRAY
1468 'output_file', # for a single file, gets pushed into output_files anyway
1469 'output_files',# product files that need to be checked; can be scalar or array
1470 'overwrite', # bool
1471 'protect', # bool; make the outputs read-only once the step succeeds
1472 'quiet', # bool; suppress the terminal record, but never the log or STDERR
1473 'retries', # whole number; run a FAILED step again up to this many times
1474 'retry_delay', # seconds, may be fractional; the wait before each retry
1475 'stale', # bool; also re-run when an input is newer than an output
1476 'stale_cmd', # bool; also re-run when the command differs from the one that made the outputs
1477 'stderr_file', # file to write the command's stderr to, instead of the record
1478 'stdin', # 'devnull' (the default) or 'inherit'; what the command sees on fd 0
1479 'stdout_file', # file to write the command's stdout to, instead of the record
1480 'threads', # whole number: CPUs the command uses; told to it, and asked of the executor
1481 'timeout', # whole seconds of wall clock; 0 means no limit
1482 'trace_fh', # filehandle; one line of JSON per task is appended to it
1483 'walltime', # time to ask the executor for, as SLURM writes it: [days-]hours:minutes:seconds
1484 'wrapper', # array ref: a command the command is run inside, as its arguments
1485 );
1486 # Keys that name one particular step, and so make no sense in %DEFAULTS:
1487 # every task would then run the same command, or claim the same files.
1488 6500 my @PER_STEP_KEYS = qw(cmd input_dir input_dirs input_file input_files output_dir
1489 output_dirs output_file output_files stderr_file stdout_file);
1490 6500 my @bad_args = grep { my $key = $_; not grep {$_ eq $key} @defined_args} keys %{ $given };
1491 6500 ▶ if (scalar @bad_args > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_args > 0) 26 6474 6500
1492 26 p @bad_args, array_max => scalar @bad_args, output => 'STDERR';
1493 26 say STDERR "the above arguments are not recognized by $current_sub";
1494 26 p @defined_args, array_max => scalar @defined_args, output => 'STDERR';
1495 26 die "The above args are accepted by $current_sub";
1496 }
1497 my @bad_defaults = grep {
1498 6474 my $key = $_;
1499 308 ▶ (not grep { $_ eq $key } @defined_args) || (grep { $_ eq $key } @PER_STEP_KEYS)
Condition100%3/3
!grep({$_ eq $key;} @defined_args) || grep({$_ eq $key;} @PER_STEP_KEYS)
l!l&&r!l&&!r
3264212
MC/DC100%2/2
!grep({$_ eq $key;} @defined_args) || grep({$_ eq $key;} @PER_STEP_KEYS)
!grep({$_ eq $key;} @defined_args) grep({$_ eq $key;} @PER_STEP_KEYS)
Truth table100%3/3
not(A) || B
A= !grep({$_ eq $key;} @defined_args)B= grep({$_ eq $key;} @PER_STEP_KEYS)
ABresult
1X1
011
000
1500 } sort keys %DEFAULTS;
1501 6474 ▶ if (scalar @bad_defaults > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_defaults > 0) 96 6378 6474
1502 96 _dump_args(\%DEFAULTS);
1503 96 die '%SimpleFlow::DEFAULTS holds ' . join(', ', map { "\"$_\"" } @bad_defaults)
1504 . ', which it cannot: a default must be a key task() accepts, and not one that names a particular step ('
1505 . join(', ', @PER_STEP_KEYS) . ')';
1506 }
1507 # The arguments this call runs with: its own, then %DEFAULTS for any it
1508 # left undefined. A copy, so that the caller's hash is never written to.
1509 6378 my $args = { %$given };
1510 6378 foreach my $key (keys %DEFAULTS) {
1511 212 ▶ $args->{$key} = $DEFAULTS{$key} if not defined $args->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{$key} 136 76 212
1512 }
1513 6378 ▶ if ((ref $DEFAULTS{env} eq 'HASH') && (ref $given->{env} eq 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $SimpleFlow::DEFAULTS{"env"} eq "HASH" and ref $given->{"env"} eq "HASH") 34 6344 6378
Condition100%3/3
ref $SimpleFlow::DEFAULTS{"env"} eq "HASH" and ref $given->{"env"} eq "HASH"
!ll&&!rl&&r
63103434
MC/DC100%2/2
ref $SimpleFlow::DEFAULTS{"env"} eq "HASH" and ref $given->{"env"} eq "HASH"
ref $SimpleFlow::DEFAULTS{"env"} eq "HASH" ref $given->{"env"} eq "HASH"
Truth table100%3/3
A and B
A= ref $SimpleFlow::DEFAULTS{"env"} eq "HASH"B= ref $given->{"env"} eq "HASH"
ABresult
0X0
100
111
1514 34 $args->{env} = { %{ $DEFAULTS{env} }, %{ $given->{env} } }; # the task's own win
1515 }
1516 # and a secret of the pipeline's stays one in a task that names its own
1517 6378 ▶ if ((ref $DEFAULTS{'env_secret'} eq 'ARRAY') && (ref $given->{'env_secret'} eq 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $SimpleFlow::DEFAULTS{"env_secret"} eq "ARRAY" and ref $given->{"env_secret"} eq "ARRAY") 8 6370 6378
Condition66%2/3
ref $SimpleFlow::DEFAULTS{"env_secret"} eq "ARRAY" and ref $given->{"env_secret"} eq "ARRAY"
!ll&&!rl&&r
637008
MC/DC50%1/2
ref $SimpleFlow::DEFAULTS{"env_secret"} eq "ARRAY" and ref $given->{"env_secret"} eq "ARRAY"
ref $SimpleFlow::DEFAULTS{"env_secret"} eq "ARRAY" ref $given->{"env_secret"} eq "ARRAY"
Truth table66%2/3
A and B
A= ref $SimpleFlow::DEFAULTS{"env_secret"} eq "ARRAY"B= ref $given->{"env_secret"} eq "ARRAY"
ABresult
0X0
100
111
1518 8 $args->{'env_secret'} = [@{ $DEFAULTS{'env_secret'} }, @{ $given->{'env_secret'} }];
1519 }
1520 6378 foreach my $key ('log_fh', 'trace_fh') {
1521 12754 ▶ if ((defined $args->{$key}) && (not openhandle($args->{$key}))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{$key} and not &openhandle($args->{$key})) 2 12752 12754
Condition100%3/3
defined $args->{$key} and not &openhandle($args->{$key})
!ll&&!rl&&r
123384142
MC/DC100%2/2
defined $args->{$key} and not &openhandle($args->{$key})
defined $args->{$key} not &openhandle($args->{$key})
Truth table100%3/3
A and not(B)
A= defined $args->{$key}B= not &openhandle($args->{$key})
ABresult
0X0
100
111
1522 2 _dump_args($args);
1523 2 die "the \"$key\" given to $current_sub isn't actually a filehandle";
1524 }
1525 12752 ▶ _autoflush($args->{$key}) if defined $args->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{$key} 414 12338 12752
1526 }
1527  
1528 # "cmd" is either a string handed to the shell, or an array ref that is
1529 # run without a shell (so no quoting or metacharacter surprises). Until
1530 # 0.16 only definedness was checked, and any other reference was
1531 # stringified straight into the shell: task(cmd => ['echo','hi']) ran the
1532 # literal command "ARRAY(0x5ed9d076e618)".
1533 6376 my $cmd_ref = ref $args->{cmd};
1534 6376 ▶ if (($cmd_ref ne '') && ($cmd_ref ne 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd_ref ne "" and $cmd_ref ne "ARRAY") 30 6346 6376
Condition100%3/3
$cmd_ref ne "" and $cmd_ref ne "ARRAY"
!ll&&!rl&&r
1504484230
MC/DC100%2/2
$cmd_ref ne "" and $cmd_ref ne "ARRAY"
$cmd_ref ne "" $cmd_ref ne "ARRAY"
Truth table100%3/3
A and B
A= $cmd_ref ne ""B= $cmd_ref ne "ARRAY"
ABresult
0X0
100
111
1535 30 _dump_args($args);
1536 30 die "\"cmd\" must be a string or an array ref, not a $cmd_ref";
1537 }
1538 6346 ▶ if ($cmd_ref eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if ($cmd_ref eq 'ARRAY') { } 4842 1504 6346
elsif (length $args->{'cmd'} == 0) { } 30 1474 1504
1539 4842 ▶ if (scalar @{ $args->{cmd} } == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$args->{"cmd"};} == 0) 30 4812 4842
1540 30 _dump_args($args);
1541 30 die '"cmd" is an empty array ref; there is no command to run';
1542 }
1543 4812 my @undefined_words = grep { not defined $args->{cmd}[$_] } 0 .. $#{ $args->{cmd} };
1544 4812 ▶ if (scalar @undefined_words > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undefined_words > 0) 30 4782 4812
1545 30 _dump_args($args);
1546 30 die '"cmd" array ref holds undefined elements at index/indices ' . join(', ', @undefined_words);
1547 }
1548 } elsif (length $args->{cmd} == 0) {
1549 30 _dump_args($args);
1550 30 die '"cmd" is the empty string; there is no command to run';
1551 }
1552 # The printable form of the command, used in every message and stored as
1553 # the record's "cmd". An array-ref command is shown space-joined, which is
1554 # readable but is NOT a shell-quoted round trip: it was never passed to a
1555 # shell in the first place.
1556 6256 ▶ my $cmd_string = ($cmd_ref eq 'ARRAY') ? join(' ', @{ $args->{cmd} }) : $args->{cmd};
Branch: 1 branch
BranchTrueFalseTotal
$cmd_ref eq 'ARRAY' ? : 4782 1474 6256
1557  
1558 6256 ▶ if (defined $args->{timeout}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"timeout"}) 338 5918 6256
1559 # ASCII digits to the very end: /^\d+$/, until 0.19, let through a
1560 # trailing newline, which $ matches before, and any Unicode digit,
1561 # which then died "isn't numeric" instead of with this message
1562 338 ▶ if ($args->{timeout} !~ /\A[0-9]+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args->{"timeout"} =~ /\A[0-9]+\z/) 50 288 338
1563 50 _dump_args($args);
1564 50 die '"timeout" must be a whole number of seconds (0 means no limit)';
1565 }
1566 288 ▶ if (($args->{timeout} > 0) && ($^O eq 'MSWin32')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"timeout"} > 0 and $^O eq "MSWin32") 0 288 288
Condition66%2/3
$args->{"timeout"} > 0 and $^O eq "MSWin32"
!ll&&!rl&&r
642240
MC/DC0%0/2
$args->{"timeout"} > 0 and $^O eq "MSWin32"
$args->{"timeout"} > 0 $^O eq "MSWin32"
Truth table66%2/3
A and B
A= $args->{"timeout"} > 0B= $^O eq "MSWin32"
ABresult
0X0
100
111
1567 0 _dump_args($args);
1568 0 die '"timeout" is not supported on MSWin32: it needs fork() and POSIX process groups to kill the command';
1569 }
1570 }
1571 6206 ▶ if ((defined $args->{retries}) && ($args->{retries} !~ /\A[0-9]+\z/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"retries"} and not $args->{"retries"} =~ /\A[0-9]+\z/) 70 6136 6206
Condition100%3/3
defined $args->{"retries"} and not $args->{"retries"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
579434270
MC/DC100%2/2
defined $args->{"retries"} and not $args->{"retries"} =~ /\A[0-9]+\z/
defined $args->{"retries"} not $args->{"retries"} =~ /\A[0-9]+\z/
Truth table100%3/3
A and not(B)
A= defined $args->{"retries"}B= not $args->{"retries"} =~ /\A[0-9]+\z/
ABresult
0X0
100
111
1572 70 _dump_args($args);
1573 70 die '"retries" must be a whole number (0 means no retries)';
1574 }
1575 6136 ▶ if ((defined $args->{'retry_delay'}) && ($args->{'retry_delay'} !~ /\A[0-9]+(?:\.[0-9]+)?\z/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"retry_delay"} and not $args->{"retry_delay"} =~ /\A[0-9]+(?:\.[0-9]+)?\z/) 70 6066 6136
Condition100%3/3
defined $args->{"retry_delay"} and not $args->{"retry_delay"} =~ /\A[0-9]+(?:\.[0-9]+)?\z/
!ll&&!rl&&r
59907670
MC/DC100%2/2
defined $args->{"retry_delay"} and not $args->{"retry_delay"} =~ /\A[0-9]+(?:\.[0-9]+)?\z/
defined $args->{"retry_delay"} not $args->{"retry_delay"} =~ /\A[0-9]+(?:\.[0-9]+)?\z/
Truth table100%3/3
A and not(B)
A= defined $args->{"retry_delay"}B= not $args->{"retry_delay"} =~ /\A[0-9]+(?:\.[0-9]+)?\z/
ABresult
0X0
100
111
1576 70 _dump_args($args);
1577 70 die '"retry_delay" must be a number of seconds, 0 or more';
1578 }
1579 6066 ▶ if (defined $args->{stdin}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"stdin"}) 34 6032 6066
1580 34 ▶ if (($args->{stdin} ne 'devnull') && ($args->{stdin} ne 'inherit')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"stdin"} ne "devnull" and $args->{"stdin"} ne "inherit") 4 30 34
Condition66%2/3
$args->{"stdin"} ne "devnull" and $args->{"stdin"} ne "inherit"
!ll&&!rl&&r
0304
MC/DC50%1/2
$args->{"stdin"} ne "devnull" and $args->{"stdin"} ne "inherit"
$args->{"stdin"} ne "devnull" $args->{"stdin"} ne "inherit"
Truth table66%2/3
A and B
A= $args->{"stdin"} ne "devnull"B= $args->{"stdin"} ne "inherit"
ABresult
0X0
100
111
1581 4 _dump_args($args);
1582 4 die "\"stdin\" must be \"devnull\" (the default) or \"inherit\", not \"$args->{stdin}\"";
1583 }
1584 }
1585 6062 ▶ if (defined $args->{env}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"env"}) 406 5656 6062
1586 406 ▶ if (ref $args->{env} ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args->{"env"} ne "HASH") 68 338 406
1587 68 _dump_args($args);
1588 68 die '"env" must be a hash ref of variable names and values';
1589 }
1590 # no '=' or NUL in a name, since the environment is "NAME=value\0"
1591 # strings; a value is a string, or undef to remove the variable
1592 338 ▶ my @bad_names = grep { ($_ eq '') || /[=\0]/ } sort keys %{ $args->{env} };
Condition66%2/3
$_ eq '' || /[=\0]/
l!l&&r!l&&!r
068422
MC/DC50%1/2
$_ eq '' || /[=\0]/
$_ eq '' /[=\0]/
Truth table66%2/3
A || B
A= $_ eq ''B= /[=\0]/
ABresult
1X1
011
000
1593 338 my @bad_values = grep { ref $args->{env}{$_} ne '' } sort keys %{ $args->{env} };
1594 338 ▶ if ((scalar @bad_names > 0) || (scalar @bad_values > 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_names > 0 or scalar @bad_values > 0) 136 202 338
Condition100%3/3
scalar @bad_names > 0 or scalar @bad_values > 0
l!l&&r!l&&!r
6868202
MC/DC100%2/2
scalar @bad_names > 0 or scalar @bad_values > 0
scalar @bad_names > 0 scalar @bad_values > 0
Truth table100%3/3
A or B
A= scalar @bad_names > 0B= scalar @bad_values > 0
ABresult
1X1
011
000
1595 136 _dump_args($args);
1596 die '"env" can hold only names without "=" and string (or undef) values; these cannot be set: '
1597 136 . join(', ', map { "\"$_\"" } @bad_names, @bad_values);
1598 }
1599 }
1600 5858 ▶ if (defined $args->{'env_secret'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"env_secret"}) 44 5814 5858
1601 44 my $names = $args->{'env_secret'};
1602 44 ▶ if ((ref $names ne 'ARRAY') || (grep { (not defined $_) || (ref $_ ne '') || ($_ eq '') || /[=\0]/ } @$names)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $names ne "ARRAY" or grep {not defined $_ or ref $_ ne "" or $_ eq "" or /[=\0]/;} @$names) 20 24 44
Condition100%12/12
ref $names ne "ARRAY" or grep {not defined $_ or ref $_ ne "" or $_ eq "" or /[=\0]/;} @$names
l!l&&r!l&&!r
41624
!defined($_) || ref $_ ne '' || $_ eq '' || /[=\0]/
l!l&&r!l&&!r
12432
not defined $_ or ref $_ ne "" or $_ eq ""
l!l&&r!l&&!r
8436
not defined $_ or ref $_ ne ""
l!l&&r!l&&!r
4440
MC/DC100%2/2
ref $names ne "ARRAY" or grep {not defined $_ or ref $_ ne "" or $_ eq "" or /[=\0]/;} @$names
ref $names ne "ARRAY" grep {not defined $_ or ref $_ ne "" or $_ eq "" or /[=\0]/;} @$names
MC/DC100%4/4
!defined($_) || ref $_ ne '' || $_ eq '' || /[=\0]/
not defined $_ ref $_ ne "" $_ eq "" /[=\0]/
Truth table100%3/3
A or B
A= ref $names ne "ARRAY"B= grep {not defined $_ or ref $_ ne "" or $_ eq "" or /[=\0]/;} @$names
ABresult
1X1
011
000
Truth table100%5/5
not(A) or B or C || D
A= not defined $_B= ref $_ ne ""C= $_ eq ""D= /[=\0]/
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1603 20 _dump_args($args);
1604 20 die '"env_secret" must be an array ref of the names of environment variables';
1605 }
1606 }
1607 5838 foreach my $key ('on_success', 'on_failure') {
1608 11666 ▶ if ((defined $args->{$key}) && (ref $args->{$key} ne 'CODE')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{$key} and ref $args->{$key} ne "CODE") 10 11656 11666
Condition100%3/3
defined $args->{$key} and ref $args->{$key} ne "CODE"
!ll&&!rl&&r
115807610
MC/DC100%2/2
defined $args->{$key} and ref $args->{$key} ne "CODE"
defined $args->{$key} ref $args->{$key} ne "CODE"
Truth table100%3/3
A and B
A= defined $args->{$key}B= ref $args->{$key} ne "CODE"
ABresult
0X0
100
111
1609 10 _dump_args($args);
1610 10 die "\"$key\" must be a code ref, which is called with the record";
1611 }
1612 }
1613 5828 foreach my $key ('wrapper', 'container_args', 'executor_args') {
1614 17366 ▶ next if not defined $args->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{$key} 17054 312 17366
1615 312 my $list = $args->{$key};
1616 312 ▶ if ((ref $list ne 'ARRAY')
Branch: 1 branch
BranchTrueFalseTotal
if (ref $list ne "ARRAY" or $key eq "wrapper" and scalar @$list == 0 or grep {not defined $_ or ref $_ ne "";} @$list) 70 242 312
Condition77%7/9
ref $list ne "ARRAY" or $key eq "wrapper" and scalar @$list == 0 or grep {not defined $_ or ref $_ ne "";} @$list
l!l&&r!l&&!r
2644242
ref $list ne "ARRAY" or $key eq "wrapper" and scalar @$list == 0
l!l&&r!l&&!r
260286
$key eq "wrapper" and scalar @$list == 0
!ll&&!rl&&r
941920
MC/DC50%2/4
ref $list ne "ARRAY" or $key eq "wrapper" and scalar @$list == 0 or grep {not defined $_ or ref $_ ne "";} @$list
ref $list ne "ARRAY" $key eq "wrapper" scalar @$list == 0 grep {not defined $_ or ref $_ ne "";} @$list
Truth table66%4/6
A or B and C or D
A= ref $list ne "ARRAY"B= $key eq "wrapper"C= scalar @$list == 0D= grep {not defined $_ or ref $_ ne "";} @$list
ABCDresult
1XXX1
011X1
00X11
01011
00X00
01000
1617 || (($key eq 'wrapper') && (scalar @$list == 0))
1618 666 ▶ || (grep { (not defined $_) || (ref $_ ne '') } @$list)) {
Condition100%3/3
!defined($_) || ref $_ ne ''
l!l&&r!l&&!r
2222622
MC/DC100%2/2
!defined($_) || ref $_ ne ''
!defined($_) ref $_ ne ''
Truth table100%3/3
not(A) || B
A= !defined($_)B= ref $_ ne ''
ABresult
1X1
011
000
1619 70 _dump_args($args);
1620 70 ▶ die "\"$key\" must be an array ref of words"
Branch: 1 branch
BranchTrueFalseTotal
$key eq 'wrapper' ? : 48 22 70
1621 . (($key eq 'wrapper') ? ', at least one, the program that runs the command' : '');
1622 }
1623 }
1624 # the values SLURM itself accepts: sbatch(1), "--mem" and "--time"
1625 5758 my %pattern = (
1626 threads => [qr/\A[1-9][0-9]*\z/, 'a whole number of CPUs, 1 or more'],
1627 mem => [qr/\A[0-9]+[KMGT]?\z/, 'an amount of memory: a number, then K, M, G or T'],
1628 walltime => [qr/\A(?:[0-9]+-)?[0-9]+(?::[0-9]{1,2}){0,2}\z/, 'a time limit, [days-]hours:minutes:seconds or minutes'],
1629 executor => [qr/\A(?:local|slurm)\z/, '"local" or "slurm"'],
1630 'container_engine' => [qr/\A(?:docker|podman|singularity|apptainer)\z/, '"docker", "podman", "singularity" or "apptainer"'],
1631 container => [qr/\A\S+\z/, 'the name of an image'],
1632 'conda_env' => [qr/\A\S+\z/, 'the name or path of a conda environment'],
1633 );
1634 5758 foreach my $key (sort keys %pattern) {
1635 40266 ▶ next if not defined $args->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{$key} 39978 288 40266
1636 288 ▶ if ((ref $args->{$key} ne '') || ($args->{$key} !~ $pattern{$key}[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args->{$key} ne "" or not $args->{$key} =~ /$pattern{$key}[0]/) 20 268 288
Condition66%2/3
ref $args->{$key} ne "" or not $args->{$key} =~ /$pattern{$key}[0]/
l!l&&r!l&&!r
020268
MC/DC50%1/2
ref $args->{$key} ne "" or not $args->{$key} =~ /$pattern{$key}[0]/
ref $args->{$key} ne "" not $args->{$key} =~ /$pattern{$key}[0]/
Truth table66%2/3
A or not(B)
A= ref $args->{$key} ne ""B= not $args->{$key} =~ /$pattern{$key}[0]/
ABresult
1X1
011
000
1637 20 _dump_args($args);
1638 20 die "\"$key\" must be $pattern{$key}[1]";
1639 }
1640 }
1641 5738 ▶ if ((defined $args->{'executor_args'}) && (($args->{executor} // 'local') eq 'local')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"executor_args"} and ($args->{"executor"} // "local") eq "local") 44 5694 5738
Condition100%5/5
defined $args->{"executor_args"} and ($args->{"executor"} // "local") eq "local"
!ll&&!rl&&r
5688644
$args->{"executor"} // "local"
l!l
2822
MC/DC100%2/2
defined $args->{"executor_args"} and ($args->{"executor"} // "local") eq "local"
defined $args->{"executor_args"} $args->{"executor"}
Truth table100%3/3
A and B
A= defined $args->{"executor_args"}B= $args->{"executor"}
ABresult
0X0
100
111
1642 44 _dump_args($args);
1643 44 die '"executor_args" needs an executor other than "local" to be given to';
1644 }
1645 5694 ▶ if ((defined $args->{'container_args'}) && (not defined $args->{container})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"container_args"} and not defined $args->{"container"}) 22 5672 5694
Condition100%3/3
defined $args->{"container_args"} and not defined $args->{"container"}
!ll&&!rl&&r
56502222
MC/DC100%2/2
defined $args->{"container_args"} and not defined $args->{"container"}
defined $args->{"container_args"} not defined $args->{"container"}
Truth table100%3/3
A and not(B)
A= defined $args->{"container_args"}B= not defined $args->{"container"}
ABresult
0X0
100
111
1646 22 _dump_args($args);
1647 22 die '"container_args" needs a "container" to be given to';
1648 }
1649 5672 foreach my $key ('dir', 'stdout_file', 'stderr_file') {
1650 16950 ▶ next if not defined $args->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{$key} 15208 1742 16950
1651 1742 ▶ if ((ref $args->{$key} ne '') || (length $args->{$key} == 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args->{$key} ne "" or length $args->{$key} == 0) 66 1676 1742
Condition100%3/3
ref $args->{$key} ne "" or length $args->{$key} == 0
l!l&&r!l&&!r
22441676
MC/DC100%2/2
ref $args->{$key} ne "" or length $args->{$key} == 0
ref $args->{$key} ne "" length $args->{$key} == 0
Truth table100%3/3
A or B
A= ref $args->{$key} ne ""B= length $args->{$key} == 0
ABresult
1X1
011
000
1652 66 _dump_args($args);
1653 66 ▶ die "\"$key\" must be a path, not " . ((ref $args->{$key} ne '') ? 'a reference' : 'the empty string');
Branch: 1 branch
BranchTrueFalseTotal
ref $args->{$key} ne '' ? : 22 44 66
1654 }
1655 }
1656 # "dir": the step runs there, and every name it declares is relative to
1657 # it, as a command run there would see it. The caller is put back where it
1658 # was when this call returns, however it returns.
1659 5606 my $back_to_caller_dir;
1660 5606 ▶ if (defined $args->{dir}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"dir"}) 1246 4360 5606
1661 1246 my $caller_dir = getcwd();
1662 1246 ▶ if (not chdir $args->{dir}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (chdir $args->{"dir"}) 64 1182 1246
1663 64 my $error = $!;
1664 64 _dump_args($args);
1665 64 die "cannot run in \"dir\" \"$args->{dir}\": $error";
1666 }
1667 1092 ▶ $back_to_caller_dir = SimpleFlow::Guard->new(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1668 1092 ▶ chdir $caller_dir or warn "cannot go back to \"$caller_dir\" after running in \"dir\": $!";
Branch: 1 branch
BranchTrueFalseTotal
chdir $caller_dir or warn qq[cannot go back to "$caller_dir" after running in "dir": $!] 1086 6 1092
1669 1182 });
1670 }
1671  
1672 # The file and directory lists are normalised, and their names validated,
1673 # before any filetest touches them.
1674 5542 my @input_files = _normalise_files($args, 'input');
1675 5376 my @input_dirs = _normalise_files($args, 'input', 'dir');
1676 5376 my @output_files = _normalise_files($args, 'output');
1677 5244 my @output_dirs = _normalise_files($args, 'output', 'dir');
1678 5198 my @outputs = (@output_files, @output_dirs);
1679  
1680 5198 my %r = (
1681 cmd => $cmd_string,
1682 dir => getcwd(),
1683 'source.file' => $c[1],
1684 'source.line' => $c[2],
1685 'output_files' => [@output_files],
1686 'output_dirs' => [@output_dirs],
1687 'input_dirs' => [@input_dirs],
1688 );
1689 5198 ▶ $r{'die'} = $args->{'die'} // 1; # by default, true
Condition100%2/2
$args->{"die"} // 1
l!l
17143484
MC/DC100%1/1
$args->{"die"} // 1
$args->{"die"}
Truth table100%2/2
A
A= $args->{"die"}
Aresult
11
00
1690 5198 ▶ $r{'dry_run'} = $args->{'dry_run'} // 0; # by default, false
Condition100%2/2
$args->{"dry_run"} // 0
l!l
4464752
MC/DC100%1/1
$args->{"dry_run"} // 0
$args->{"dry_run"}
Truth table100%2/2
A
A= $args->{"dry_run"}
Aresult
11
00
1691 # The environment the command is given; the record's "env" is this with
1692 # the values "env_secret" names hidden, since the record is printed,
1693 # logged and traced. Until 0.192 every value was written out in full.
1694 5198 ▶ my %command_env = %{ $args->{env} // {} }; # by default, no changes; a copy, not the caller's hash
Condition100%2/2
$args->{"env"} // {}
l!l
2024996
MC/DC100%1/1
$args->{"env"} // {}
$args->{"env"}
Truth table100%2/2
A
A= $args->{"env"}
Aresult
11
00
1695 5198 $r{'env_secret'} = [_secret_names($args)]; # by default, none
1696 5198 $r{env} = _shown_args({ env => \%command_env, 'env_secret' => $r{'env_secret'} })->{env};
1697 5198 ▶ $r{lock} = ($args->{lock} // 0) ? 1 : 0; # by default, false
Branch: 1 branch
BranchTrueFalseTotal
$args->{'lock'} // 0 ? : 184 5014 5198
Condition100%2/2
$args->{"lock"} // 0
l!l
1845014
MC/DC100%1/1
$args->{"lock"} // 0
$args->{"lock"}
Truth table100%2/2
A
A= $args->{"lock"}
Aresult
11
00
1698 5198 ▶ $r{note} = $args->{note} // '';# by default, no note
Condition100%2/2
$args->{"note"} // ""
l!l
1045094
MC/DC100%1/1
$args->{"note"} // ""
$args->{"note"}
Truth table100%2/2
A
A= $args->{"note"}
Aresult
11
00
1699 5198 ▶ $r{overwrite} = $args->{overwrite} // 0; # by default, false
Condition100%2/2
$args->{"overwrite"} // 0
l!l
4304768
MC/DC100%1/1
$args->{"overwrite"} // 0
$args->{"overwrite"}
Truth table100%2/2
A
A= $args->{"overwrite"}
Aresult
11
00
1700 5198 ▶ $r{protect} = ($args->{protect} // 0) ? 1 : 0; # by default, false
Branch: 1 branch
BranchTrueFalseTotal
$args->{'protect'} // 0 ? : 224 4974 5198
Condition100%2/2
$args->{"protect"} // 0
l!l
2244974
MC/DC100%1/1
$args->{"protect"} // 0
$args->{"protect"}
Truth table100%2/2
A
A= $args->{"protect"}
Aresult
11
00
1701 5198 ▶ $r{quiet} = $args->{quiet} // 0; # by default, false
Condition100%2/2
$args->{"quiet"} // 0
l!l
41121086
MC/DC100%1/1
$args->{"quiet"} // 0
$args->{"quiet"}
Truth table100%2/2
A
A= $args->{"quiet"}
Aresult
11
00
1702 5198 ▶ $r{retries} = $args->{retries} // 0; # by default, one attempt only
Condition100%2/2
$args->{"retries"} // 0
l!l
3424856
MC/DC100%1/1
$args->{"retries"} // 0
$args->{"retries"}
Truth table100%2/2
A
A= $args->{"retries"}
Aresult
11
00
1703 5198 ▶ $r{'retry_delay'} = $args->{'retry_delay'} // 0; # by default, retry at once
Condition100%2/2
$args->{"retry_delay"} // 0
l!l
765122
MC/DC100%1/1
$args->{"retry_delay"} // 0
$args->{"retry_delay"}
Truth table100%2/2
A
A= $args->{"retry_delay"}
Aresult
11
00
1704 5198 ▶ $r{stale} = $args->{stale} // 0; # by default, false
Condition100%2/2
$args->{"stale"} // 0
l!l
2104988
MC/DC100%1/1
$args->{"stale"} // 0
$args->{"stale"}
Truth table100%2/2
A
A= $args->{"stale"}
Aresult
11
00
1705 5198 ▶ $r{'stderr_file'} = $args->{'stderr_file'} // ''; # '' = captured into the record's "stderr"
Condition100%2/2
$args->{"stderr_file"} // ""
l!l
1885010
MC/DC100%1/1
$args->{"stderr_file"} // ""
$args->{"stderr_file"}
Truth table100%2/2
A
A= $args->{"stderr_file"}
Aresult
11
00
1706 5198 ▶ $r{stdin} = $args->{stdin} // 'devnull'; # by default, the null device
Condition100%2/2
$args->{"stdin"} // "devnull"
l!l
305168
MC/DC100%1/1
$args->{"stdin"} // "devnull"
$args->{"stdin"}
Truth table100%2/2
A
A= $args->{"stdin"}
Aresult
11
00
1707 5198 ▶ $r{'stdout_file'} = $args->{'stdout_file'} // ''; # '' = captured into the record's "stdout"
Condition100%2/2
$args->{"stdout_file"} // ""
l!l
2424956
MC/DC100%1/1
$args->{"stdout_file"} // ""
$args->{"stdout_file"}
Truth table100%2/2
A
A= $args->{"stdout_file"}
Aresult
11
00
1708 5198 ▶ $r{timeout} = $args->{timeout} // 0; # by default, no limit
Condition100%2/2
$args->{"timeout"} // 0
l!l
2884910
MC/DC100%1/1
$args->{"timeout"} // 0
$args->{"timeout"}
Truth table100%2/2
A
A= $args->{"timeout"}
Aresult
11
00
1709 5198 ▶ $r{'stale_cmd'} = ($args->{'stale_cmd'} // 0) ? 1 : 0; # by default, false
Branch: 1 branch
BranchTrueFalseTotal
$args->{'stale_cmd'} // 0 ? : 448 4750 5198
Condition100%2/2
$args->{"stale_cmd"} // 0
l!l
4484750
MC/DC100%1/1
$args->{"stale_cmd"} // 0
$args->{"stale_cmd"}
Truth table100%2/2
A
A= $args->{"stale_cmd"}
Aresult
11
00
1710 5198 ▶ $r{wrapper} = [@{ $args->{wrapper} // [] }]; # by default, none
Condition100%2/2
$args->{"wrapper"} // []
l!l
1485050
MC/DC100%1/1
$args->{"wrapper"} // []
$args->{"wrapper"}
Truth table100%2/2
A
A= $args->{"wrapper"}
Aresult
11
00
1711 5198 ▶ $r{container} = $args->{container} // ''; # '' = no container
Condition100%2/2
$args->{"container"} // ""
l!l
345164
MC/DC100%1/1
$args->{"container"} // ""
$args->{"container"}
Truth table100%2/2
A
A= $args->{"container"}
Aresult
11
00
1712 5198 ▶ $r{'container_engine'} = $args->{'container_engine'} // (($r{container} ne '') ? 'docker' : ''); # '' = no container
Branch: 1 branch
BranchTrueFalseTotal
$r{'container'} ne '' ? : 6 5164 5170
Condition100%2/2
$args->{"container_engine"} // ($r{"container"} ne "" ? "docker" : "")
l!l
285170
MC/DC100%1/1
$args->{"container_engine"} // ($r{"container"} ne "" ? "docker" : "")
$args->{"container_engine"}
Truth table100%2/2
A
A= $args->{"container_engine"}
Aresult
11
00
1713 5198 ▶ $r{'container_args'} = [@{ $args->{'container_args'} // [] }];
Condition100%2/2
$args->{"container_args"} // []
l!l
225176
MC/DC100%1/1
$args->{"container_args"} // []
$args->{"container_args"}
Truth table100%2/2
A
A= $args->{"container_args"}
Aresult
11
00
1714 5198 ▶ $r{'conda_env'} = $args->{'conda_env'} // ''; # '' = no conda environment
Condition100%2/2
$args->{"conda_env"} // ""
l!l
285170
MC/DC100%1/1
$args->{"conda_env"} // ""
$args->{"conda_env"}
Truth table100%2/2
A
A= $args->{"conda_env"}
Aresult
11
00
1715 5198 ▶ $r{executor} = $args->{executor} // 'local'; # by default, run here
Condition100%2/2
$args->{"executor"} // "local"
l!l
285170
MC/DC100%1/1
$args->{"executor"} // "local"
$args->{"executor"}
Truth table100%2/2
A
A= $args->{"executor"}
Aresult
11
00
1716 5198 ▶ $r{'executor_args'} = [@{ $args->{'executor_args'} // [] }];
Condition100%2/2
$args->{"executor_args"} // []
l!l
65192
MC/DC100%1/1
$args->{"executor_args"} // []
$args->{"executor_args"}
Truth table100%2/2
A
A= $args->{"executor_args"}
Aresult
11
00
1717 5198 ▶ $r{threads} = $args->{threads} // 0; # 0 = not said
Condition100%2/2
$args->{"threads"} // 0
l!l
1125086
MC/DC100%1/1
$args->{"threads"} // 0
$args->{"threads"}
Truth table100%2/2
A
A= $args->{"threads"}
Aresult
11
00
1718 5198 ▶ $r{mem} = $args->{mem} // ''; # '' = not said
Condition100%2/2
$args->{"mem"} // ""
l!l
65192
MC/DC100%1/1
$args->{"mem"} // ""
$args->{"mem"}
Truth table100%2/2
A
A= $args->{"mem"}
Aresult
11
00
1719 5198 ▶ $r{walltime} = $args->{walltime} // ''; # '' = not said
Condition100%2/2
$args->{"walltime"} // ""
l!l
65192
MC/DC100%1/1
$args->{"walltime"} // ""
$args->{"walltime"}
Truth table100%2/2
A
A= $args->{"walltime"}
Aresult
11
00
1720 # The hooks are the one kind of option not on the record: they are code,
1721 # which neither the printed record, the log nor the trace can hold.
1722 5198 my %hook = ('on_success' => $args->{'on_success'}, 'on_failure' => $args->{'on_failure'});
1723 # the command that is actually run: "cmd" itself, or "cmd" inside the
1724 # executor, container, conda environment and wrapper asked for
1725 5198 my $run_cmd = _wrapped_cmd(\%r, $args->{cmd});
1726 5198 ▶ $r{'wrapped.cmd'} = (defined $run_cmd) ? join(' ', @$run_cmd) : ''; # '' = run as it is
Branch: 1 branch
BranchTrueFalseTotal
defined $run_cmd ? : 238 4960 5198
1727 5198 ▶ $run_cmd //= $args->{cmd};
Condition66%2/3
$run_cmd //= $args->{"cmd"}
l!l&&r!l&&!r
23849600
MC/DC0%0/2
$run_cmd //= $args->{"cmd"}
$run_cmd $args->{"cmd"}
Truth table66%2/3
A //= B
A= $run_cmdB= $args->{"cmd"}
ABresult
1X1
011
000
1728 5198 my $run_cmd_ref = ref $run_cmd;
1729 5198 my $log_fh = $args->{'log_fh'};
1730 5198 my $trace_fh = $args->{'trace_fh'};
1731  
1732 # Checked after "dry_run" is resolved, not before, as it was until 0.19:
1733 # a dry run makes nothing, so the input of a pipeline's second step --
1734 # the first step's output -- is legitimately absent, and dying over it
1735 # meant no dry run could get past step 2. A dry run reports the missing
1736 # inputs instead, further down.
1737 5198 my %input_file_size;
1738 5198 ▶ my @missing_inputs = ((grep {not -f -r $_ } @input_files), (grep { not ((-d $_) && (-r $_)) } @input_dirs));
Condition66%2/3
-d $_ && -r $_
!ll&&!rl&&r
52050
MC/DC50%1/2
-d $_ && -r $_
-d $_ -r $_
Truth table66%2/3
A && B
A= -d $_B= -r $_
ABresult
0X0
100
111
1739 5198 ▶ if (scalar @missing_inputs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @missing_inputs > 0) 208 4990 5198
1740 208 ▶ if (!$r{'dry_run'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($r{"dry_run"}) 118 90 208
1741 118 say STDERR 'this list of arguments:';
1742 118 _dump_args($args);
1743 118 say STDERR 'Cannot run because these files are either missing or unreadable in: ' . getcwd();
1744 118 p @missing_inputs, output => 'STDERR';
1745 118 die 'the above files are missing or are not readable';
1746 }
1747 }
1748 5080 %input_file_size = map { $_ => -s $_ } @input_files; # undef for an input a dry run is missing
1749 # These belong to a command that actually ran, but they are seeded on
1750 # every path so that the record has the same shape after a skip or a dry
1751 # run. They used to be absent there, which meant a caller reading
1752 # $t->{'exit'} after a skip took an uninitialized-value warning -- fatal
1753 # under the "warnings FATAL => 'all'" this module itself recommends.
1754 5080 $r{'exit'} = 0;
1755 5080 $r{signal} = 0;
1756 5080 $r{stdout} = '';
1757 5080 $r{stderr} = '';
1758 5080 $r{'timed.out'} = 0;
1759 5080 $r{duration} = 0;
1760 5080 $r{attempts} = 0; # how many times the command was run; 0 = not at all
1761 5080 $r{'cpu.user'} = 0;
1762 5080 $r{'cpu.system'} = 0;
1763 5080 $r{'start.time'} = 0; # epoch seconds when the last attempt started; 0 = none did
1764 5080 $r{'failed.outputs'} = []; # where a failed step's outputs were moved; see _move_aside
1765 5080 $r{'cmd.changed'} = 0; # 1 = stale_cmd found a different command on record for the outputs
1766 5080 $r{'will.do'} = 'yes';
1767 5080 ▶ $r{'will.do'} = 'no: dry run' if $r{'dry_run'};
Branch: 1 branch
BranchTrueFalseTotal
if $r{"dry_run"} 412 4668 5080
1768 5080 ▶ if (scalar @input_files > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @input_files > 0) 314 4766 5080
1769 314 $r{'input_files'} = [@input_files];
1770 314 $r{'input_file.size'} = \%input_file_size;
1771 }
1772  
1773 5080 my $msg = "\@ $c[1] line $c[2] The command is:\n" . colored(['blue on_bright_red'], $cmd_string);
1774 5080 ▶ say $msg unless $r{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $r{"quiet"} 1078 4002 5080
1775 5080 ▶ say {$log_fh} "\@ $c[1] line $c[2] The command is:\n$cmd_string" if defined $log_fh;
Branch: 1 branch
BranchTrueFalseTotal
if defined $log_fh 206 4874 5080
1776  
1777 # Taken before the outputs are looked at, so that a run which waited for
1778 # another to finish the step sees what that one made. A dry run touches
1779 # nothing, and so takes no lock. Held until this call returns.
1780 5080 ▶ my @locks = ($r{lock} && !$r{'dry_run'}) ? _lock_outputs($cmd_string, @outputs) : ();
Branch: 1 branch
BranchTrueFalseTotal
$r{'lock'} && !$r{'dry_run'} ? : 150 4930 5080
Condition100%3/3
$r{"lock"} and not $r{"dry_run"}
!ll&&!rl&&r
489634150
MC/DC100%2/2
$r{"lock"} and not $r{"dry_run"}
$r{"lock"} not $r{"dry_run"}
Truth table100%3/3
A and not(B)
A= $r{"lock"}B= not $r{"dry_run"}
ABresult
0X0
100
111
1781  
1782 # The same test as the post-run check further down (-f -r, not a bare -f).
1783 # A file that exists but cannot be read is not a usable result, and
1784 # counting it as "already done" would skip the very step that could
1785 # replace it.
1786 5064 my @existing = ((grep {-f -r $_} @output_files), (grep { -d $_ } @output_dirs));
1787  
1788 # Staleness, as make and snakemake understand it: outputs that already
1789 # exist are still out of date if any input is newer than any of them.
1790 # Off by default, because switching it on unconditionally would silently
1791 # start re-running steps in pipelines written against 0.15 and earlier.
1792 5064 my $is_stale = 0;
1793 5064 ▶ if (($r{stale}) && (scalar(@input_files) + scalar(@input_dirs) > 0) && (scalar @outputs > 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"stale"} and scalar(@input_files) + scalar(@input_dirs) > 0 and scalar @outputs > 0) 190 4874 5064
Condition83%5/6
$r{"stale"} and scalar(@input_files) + scalar(@input_dirs) > 0 and scalar @outputs > 0
!ll&&!rl&&r
48740190
$r{"stale"} and scalar(@input_files) + scalar(@input_dirs) > 0
!ll&&!rl&&r
485420190
MC/DC66%2/3
$r{"stale"} and scalar(@input_files) + scalar(@input_dirs) > 0 and scalar @outputs > 0
$r{"stale"} scalar(@input_files) + scalar(@input_dirs) > 0 scalar @outputs > 0
Truth table75%3/4
A and B and C
A= $r{"stale"}B= scalar(@input_files) + scalar(@input_dirs) > 0C= scalar @outputs > 0
ABCresult
0XX0
10X0
1100
1111
1794 190 my $newest_input = _newest_mtime(@input_files, @input_dirs);
1795 190 my $oldest_output = _oldest_mtime(@outputs);
1796 190 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (defined $newest_input and defined $oldest_output and $newest_input > $oldest_output) 128 62 190
Condition50%3/6
defined $newest_input and defined $oldest_output and $newest_input > $oldest_output
!ll&&!rl&&r
062128
defined $newest_input and defined $oldest_output
!ll&&!rl&&r
00190
MC/DC33%1/3
defined $newest_input and defined $oldest_output and $newest_input > $oldest_output
defined $newest_input defined $oldest_output $newest_input > $oldest_output
Truth table50%2/4
A and B and C
A= defined $newest_inputB= defined $oldest_outputC= $newest_input > $oldest_output
ABCresult
0XX0
10X0
1100
1111
1797 (defined $newest_input) &&
1798 (defined $oldest_output) &&
1799 ($newest_input > $oldest_output)
1800 ) {
1801 128 $is_stale = 1;
1802 }
1803 }
1804 5064 $r{'out.of.date'} = $is_stale;
1805  
1806 # "stale_cmd": the outputs are out of date if the command on record for
1807 # them is not this one; see _command_signature. Outputs with no command on
1808 # record -- made before stale_cmd was used, or by hand -- are taken as
1809 # made by this one, which is recorded, so that the next change is seen.
1810 #
1811 # A step run without stale_cmd still replaces the outputs, so when there
1812 # is a command on record for them, this one's is written over it after a
1813 # successful run, further down. Until 0.192 it was left, and a later
1814 # stale_cmd run of the command on record took the other one's outputs as
1815 # its own. With nothing on record, nothing is written: a pipeline that
1816 # never asks for stale_cmd gets no .simpleflow/ from it.
1817 5064 my ($signature, $signature_file, $recorded_signature);
1818 5064 ▶ if (($r{'stale_cmd'}) && (scalar @outputs > 0)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($r{'stale_cmd'} and scalar @outputs > 0) { } 448 4616 5064
elsif (scalar @outputs > 0 and -e _signature_file(@outputs)) { } 64 6786 6850
Condition66%2/3
$r{"stale_cmd"} and scalar @outputs > 0
!ll&&!rl&&r
46160448
MC/DC50%1/2
$r{"stale_cmd"} and scalar @outputs > 0
$r{"stale_cmd"} scalar @outputs > 0
Truth table66%2/3
A and B
A= $r{"stale_cmd"}B= scalar @outputs > 0
ABresult
0X0
100
111
1819 448 $signature = _command_signature(\%r, $args->{cmd}, $run_cmd);
1820 448 $signature_file = _signature_file(@outputs);
1821 448 $recorded_signature = _read_signature($signature_file);
1822 432 ▶ $r{'cmd.changed'} = ((defined $recorded_signature) && ($recorded_signature ne $signature)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $recorded_signature && $recorded_signature ne $signature ? : 198 234 432
Condition100%3/3
defined $recorded_signature and $recorded_signature ne $signature
!ll&&!rl&&r
21222198
MC/DC100%2/2
defined $recorded_signature and $recorded_signature ne $signature
defined $recorded_signature $recorded_signature ne $signature
Truth table100%3/3
A and B
A= defined $recorded_signatureB= $recorded_signature ne $signature
ABresult
0X0
100
111
1823 ▶ } elsif ((scalar @outputs > 0) && (-e _signature_file(@outputs))) {
Condition100%3/3
scalar @outputs > 0 and -e _signature_file(@outputs)
!ll&&!rl&&r
2234231864
MC/DC100%2/2
scalar @outputs > 0 and -e _signature_file(@outputs)
scalar @outputs > 0 -e _signature_file(@outputs)
Truth table100%3/3
A and B
A= scalar @outputs > 0B= -e _signature_file(@outputs)
ABresult
0X0
100
111
1824 64 $signature = _command_signature(\%r, $args->{cmd}, $run_cmd);
1825 64 $signature_file = _signature_file(@outputs);
1826 }
1827  
1828 5048 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (not $r{'overwrite'} || $is_stale || $r{'cmd.changed'} and scalar @outputs > 0 and scalar @existing == scalar @outputs) { } 490 4558 5048
Condition100%12/12
not $r{"overwrite"} || $is_stale || $r{"cmd.changed"} and scalar @outputs > 0 and scalar @existing == scalar @outputs
!ll&&!rl&&r
29421616490
not $r{"overwrite"} || $is_stale || $r{"cmd.changed"} and scalar @outputs > 0
!ll&&!rl&&r
70822342106
$r{'overwrite'} || $is_stale || $r{'cmd.changed'}
l!l&&r!l&&!r
5101984340
$r{"overwrite"} or $is_stale
l!l&&r!l&&!r
3821284538
MC/DC100%5/5
not $r{"overwrite"} || $is_stale || $r{"cmd.changed"} and scalar @outputs > 0 and scalar @existing == scalar @outputs
$r{"overwrite"} $is_stale $r{'cmd.changed'} scalar @outputs > 0 scalar @existing == scalar @outputs
Truth table100%6/6
not(A or B || C) and D and E
A= $r{"overwrite"}B= $is_staleC= $r{'cmd.changed'}D= scalar @outputs > 0E= scalar @existing == scalar @outputs
ABCDEresult
1XXXX0
01XXX0
001XX0
0000X0
000100
000111
1829 (!$r{overwrite}) &&
1830 (!$is_stale) &&
1831 (!$r{'cmd.changed'}) &&
1832 (scalar @outputs > 0) &&
1833 (scalar @existing == scalar @outputs)
1834 ) { # this has been done before
1835 490 $r{done} = 'before';
1836 490 $r{'will.do'} = 'no';
1837 490 ▶ say colored(['black on_green'], "\"$cmd_string\"\n") . ' has been done before' unless $r{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $r{"quiet"} 72 418 490
1838 490 $r{'output_file.size'} = { map {$_ => -s $_} @output_files };
1839 _write_signature($signature_file, $signature)
1840 490 ▶ if $r{'stale_cmd'} && (defined $signature) && (not defined $recorded_signature) && (!$r{'dry_run'});
Branch: 1 branch
BranchTrueFalseTotal
if $r{"stale_cmd"} and defined $signature and not defined $recorded_signature and not $r{"dry_run"} 16 474 490
Condition77%7/9
$r{"stale_cmd"} and defined $signature and not defined $recorded_signature and not $r{"dry_run"}
!ll&&!rl&&r
474016
$r{"stale_cmd"} and defined $signature and not defined $recorded_signature
!ll&&!rl&&r
4522216
$r{"stale_cmd"} and defined $signature
!ll&&!rl&&r
452038
MC/DC50%2/4
$r{"stale_cmd"} and defined $signature and not defined $recorded_signature and not $r{"dry_run"}
$r{"stale_cmd"} defined $signature not defined $recorded_signature not $r{"dry_run"}
Truth table60%3/5
A and B and not(C) and not(D)
A= $r{"stale_cmd"}B= defined $signatureC= not defined $recorded_signatureD= not $r{"dry_run"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1841 490 _report(\%r, $log_fh, $r{quiet}, $trace_fh);
1842 490 return \%r;
1843 } else {
1844 4558 $r{done} = 'not yet';
1845 }
1846 4558 ▶ if ($is_stale) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_stale) 128 4430 4558
1847 say colored(['red on_black'], "\"$cmd_string\"")
1848 128 ▶ . ' is being re-run: an input file is newer than an output file' unless $r{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $r{"quiet"} 22 106 128
1849 }
1850 4558 ▶ if ($r{'cmd.changed'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"cmd.changed"}) 198 4360 4558
1851 say colored(['red on_black'], "\"$cmd_string\"")
1852 198 ▶ . ' is being re-run: its command has changed since its outputs were made' unless $r{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $r{"quiet"} 18 180 198
1853 }
1854 4558 ▶ if ($r{'dry_run'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"dry_run"}) 412 4146 4558
1855 412 ▶ unless ($r{quiet}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($r{"quiet"}) 198 214 412
1856 198 say "\@ $c[1] line $c[2] in $r{dir} the command was going to be:";
1857 198 say colored(['red on_black'], "\"$cmd_string\"");
1858 198 ▶ say "run as: $r{'wrapped.cmd'}" if $r{'wrapped.cmd'} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $r{"wrapped.cmd"} ne "" 22 176 198
1859 198 say 'But this is a dry run';
1860 }
1861 412 ▶ if (scalar @missing_inputs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @missing_inputs > 0) 90 322 412
1862 my $missing = "these inputs do not exist yet, which a dry run allows:\n"
1863 90 . join("\n", map { "\t$_" } @missing_inputs);
1864 90 ▶ say $missing unless $r{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $r{"quiet"} 90 0 90
1865 90 ▶ say {$log_fh} $missing if defined $log_fh;
Branch: 1 branch
BranchTrueFalseTotal
if defined $log_fh 22 68 90
1866 }
1867 # Until 0.19 a dry run returned with neither: its record lacked
1868 # output_file.size, and the log held only the command line.
1869 412 $r{'output_file.size'} = { map {$_ => -s $_} @output_files };
1870 412 _report(\%r, $log_fh, $r{quiet}, $trace_fh);
1871 412 ▶ say '-------------' unless $r{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $r{"quiet"} 198 214 412
1872 412 return \%r;
1873 }
1874 # A protected output is one a step made and finished with: re-running
1875 # over it is refused, as Snakemake refuses, rather than left to fail in
1876 # the command with an error that does not say why the file is read-only.
1877 4146 ▶ if ($r{protect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"protect"}) 224 3922 4146
1878 224 ▶ my @protected = grep { (-e $_) && (not -w $_) } @outputs;
Condition66%2/3
-e $_ && !(-w $_)
!ll&&!rl&&r
168056
MC/DC50%1/2
-e $_ && !(-w $_)
-e $_ !(-w $_)
Truth table66%2/3
A && not(B)
A= -e $_B= !(-w $_)
ABresult
0X0
100
111
1879 224 ▶ if (scalar @protected > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @protected > 0) 56 168 224
1880 56 p @protected, output => 'STDERR';
1881 56 die "cannot re-run \"$cmd_string\": the above outputs are write-protected, as \"protect\" left them; "
1882 . 'remove them, or make them writable, to run it again';
1883 }
1884 }
1885 # "stdout_file" and "stderr_file" hold this call's output, from every
1886 # attempt: emptied once, here, and appended to by each attempt.
1887 4090 foreach my $path (grep { $_ ne '' } $r{'stdout_file'}, $r{'stderr_file'}) {
1888 372 ▶ open my $fh, '>', $path or die "cannot empty \"$path\" before running \"$cmd_string\": $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $path or die qq[cannot empty "$path" before running "$cmd_string": $!] 350 22 372
1889 350 close $fh;
1890 }
1891  
1892 4068 my ($interrupted, $launch_error, @missing_outputs, %output_file_size, @stderr_tail);
1893 4068 my %moved; # every .failed name, over all the attempts
1894 4068 my $attempts = $r{retries} + 1;
1895 4068 foreach my $attempt (1 .. $attempts) {
1896 4478 $r{attempts} = $attempt;
1897 4478 ($interrupted, $launch_error) = _run_once(\%r, $run_cmd, $run_cmd_ref, $cmd_string, \%command_env);
1898 # A command that timed out, exited non-zero, was killed by a signal, or
1899 # failed to produce its declared outputs has failed, whether or not
1900 # "die" is set. Until 0.16 the FAILED assignment for a non-zero exit
1901 # lived inside the "die" branch, so under die => 0 -- the very mode in
1902 # which the caller is expected to read will.do -- a failing command was
1903 # reported as "done". Until 0.19 the signal was not tested at all: a
1904 # death by signal leaves exit at 0, so an OOM kill or a Ctrl-C was
1905 # "done" too.
1906 4062 @missing_outputs = ((grep {not -f -r $_} @output_files), (grep { not -d $_ } @output_dirs));
1907 $r{'will.do'} = (
1908 (scalar @missing_outputs > 0) ||
1909 ($r{'exit'} != 0) ||
1910 ($r{signal}) ||
1911 4062 ▶ ($r{'timed.out'})
Branch: 1 branch
BranchTrueFalseTotal
scalar @missing_outputs > 0 || $r{'exit'} != 0 || $r{'signal'} || $r{'timed.out'} ? : 2116 1946 4062
Condition88%8/9
scalar @missing_outputs > 0 or $r{"exit"} != 0 or $r{"signal"} or $r{"timed.out"}
l!l&&r!l&&!r
211601946
scalar @missing_outputs > 0 or $r{"exit"} != 0 or $r{"signal"}
l!l&&r!l&&!r
18702461946
scalar @missing_outputs > 0 or $r{"exit"} != 0
l!l&&r!l&&!r
31215582192
MC/DC75%3/4
scalar @missing_outputs > 0 or $r{"exit"} != 0 or $r{"signal"} or $r{"timed.out"}
scalar @missing_outputs > 0 $r{"exit"} != 0 $r{"signal"} $r{"timed.out"}
Truth table80%4/5
A or B or C or D
A= scalar @missing_outputs > 0B= $r{"exit"} != 0C= $r{"signal"}D= $r{"timed.out"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1912 ) ? 'FAILED' : 'done';
1913 # Measured before the move below, so the record says what the command
1914 # wrote rather than that the declared names are now empty.
1915 4062 %output_file_size = map {$_ => -s $_} @output_files;
1916 4062 $r{'output_file.size'} = { %output_file_size };
1917 # Not retried: success, the last attempt, or an interrupt, which is
1918 # the caller asking for the whole program to stop.
1919 4062 ▶ my $retrying = (($attempt < $attempts) && (not defined $interrupted)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$attempt < $attempts && !defined($interrupted) ? : 492 3570 4062
Condition66%2/3
$attempt < $attempts and not defined $interrupted
!ll&&!rl&&r
35700492
MC/DC50%1/2
$attempt < $attempts and not defined $interrupted
$attempt < $attempts not defined $interrupted
Truth table66%2/3
A and not(B)
A= $attempt < $attemptsB= not defined $interrupted
ABresult
0X0
100
111
1920 4062 ▶ if ($r{'will.do'} eq 'FAILED') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"will.do"} eq "FAILED") 2116 1946 4062
1921 # Read now, while the file is where stderr_file says: when it is
1922 # also an output it is about to be moved, and until 0.192 the
1923 # message then went without it.
1924 2116 @stderr_tail = _stderr_tail(\%r);
1925 # An output that is, or holds, stdout_file or stderr_file stays
1926 # where it is until the last attempt, since those files are to
1927 # hold every attempt, in order. Until 0.192 it was moved aside
1928 # with the rest, and the retry began a new file -- or, inside a
1929 # moved directory, could not open one.
1930 2116 my @to_move = @outputs;
1931 2116 ▶ if ($retrying) {
Branch: 1 branch
BranchTrueFalseTotal
if ($retrying) 410 1706 2116
1932 410 my @streams = map { _canonical($_) } grep { $_ ne '' } $r{'stdout_file'}, $r{'stderr_file'};
1933 @to_move = grep {
1934 410 my $output = _canonical($_);
1935 118 ▶ not grep { ($_ eq $output) || _is_within($_, $output) } @streams;
Condition33%1/3
$_ eq $output || _is_within($_, $output)
l!l&&r!l&&!r
3400
MC/DC0%0/2
$_ eq $output || _is_within($_, $output)
$_ eq $output _is_within($_, $output)
Truth table33%1/3
A || B
A= $_ eq $outputB= _is_within($_, $output)
ABresult
1X1
011
000
1936 } @outputs;
1937 }
1938 2116 my @moved_now = _move_aside(@to_move);
1939 2116 $moved{$_} = 1 foreach @moved_now;
1940 2116 $r{'failed.outputs'} = [sort keys %moved];
1941 2116 ▶ if (scalar @moved_now > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @moved_now > 0) 606 1510 2116
1942 my $moved = "the outputs of the failed \"$cmd_string\" were moved aside, so that the next run does not take them as done:\n"
1943 606 . join("\n", map { "\t$_" } @moved_now);
1944 606 say STDERR $moved;
1945 0 ▶ say {$log_fh} $moved if defined $log_fh;
Branch: 1 branch
BranchTrueFalseTotal
if defined $log_fh 0 606 606
1946 }
1947 }
1948 4062 ▶ last if ($r{'will.do'} ne 'FAILED') || (not $retrying);
Branch: 1 branch
BranchTrueFalseTotal
if $r{"will.do"} ne "FAILED" or not $retrying 3652 410 4062
Condition100%3/3
$r{"will.do"} ne "FAILED" or not $retrying
l!l&&r!l&&!r
19461706410
MC/DC100%2/2
$r{"will.do"} ne "FAILED" or not $retrying
$r{"will.do"} ne "FAILED" not $retrying
Truth table100%3/3
A or not(B)
A= $r{"will.do"} ne "FAILED"B= not $retrying
ABresult
1X1
011
000
1949 my $retry = "\"$cmd_string\" " . join('; ', _why_failed(\%r, $interrupted, $launch_error, @missing_outputs))
1950 . "; attempt $attempt of $attempts, retrying"
1951 410 ▶ . (($r{'retry_delay'} > 0) ? " in $r{'retry_delay'}s" : '');
Branch: 1 branch
BranchTrueFalseTotal
$r{'retry_delay'} > 0 ? : 74 336 410
1952 410 say STDERR $retry;
1953 0 ▶ say {$log_fh} $retry if defined $log_fh;
Branch: 1 branch
BranchTrueFalseTotal
if defined $log_fh 0 410 410
1954 410 ▶ Time::HiRes::sleep($r{'retry_delay'}) if $r{'retry_delay'} > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $r{"retry_delay"} > 0 74 336 410
1955 }
1956 3652 $r{done} = 'now';
1957 3652 ▶ if (scalar @missing_outputs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @missing_outputs > 0) 228 3424 3652
1958 228 my $clipped_args = _clipped(_shown_args($args));
1959 228 say STDERR "this input to $current_sub:";
1960 228 p $clipped_args, output => 'STDERR';
1961 228 ▶ say {$log_fh} "this input to $current_sub:" if defined $log_fh;
Branch: 1 branch
BranchTrueFalseTotal
if defined $log_fh 28 200 228
1962 228 ▶ p($clipped_args, output => $log_fh, string_max => 0) if defined $log_fh;
Branch: 1 branch
BranchTrueFalseTotal
if defined $log_fh 28 200 228
1963 228 say STDERR 'has these output files missing:';
1964 228 ▶ say {$log_fh} 'has these output files missing:' if defined $log_fh;
Branch: 1 branch
BranchTrueFalseTotal
if defined $log_fh 28 200 228
1965 228 p @missing_outputs, output => 'STDERR';
1966 228 ▶ p(@missing_outputs, output => $log_fh) if defined $log_fh;
Branch: 1 branch
BranchTrueFalseTotal
if defined $log_fh 28 200 228
1967 }
1968 # Only outputs that exist: a missing one has an undef size, which until
1969 # 0.19 was defaulted to 0 here, so a file never made was reported twice.
1970 my @files_with_zero_size = grep {
1971 3652 ▶ (defined $output_file_size{$_}) && ($output_file_size{$_} == 0)
Condition100%3/3
defined $output_file_size{$_} && $output_file_size{$_} == 0
!ll&&!rl&&r
158165258
MC/DC100%2/2
defined $output_file_size{$_} && $output_file_size{$_} == 0
defined $output_file_size{$_} $output_file_size{$_} == 0
Truth table100%3/3
A && B
A= defined $output_file_size{$_}B= $output_file_size{$_} == 0
ABresult
0X0
100
111
1972 } @output_files;
1973 3652 ▶ if (scalar @files_with_zero_size > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @files_with_zero_size > 0) 58 3594 3652
1974 58 p @files_with_zero_size, output => 'STDERR';
1975 58 warn 'the above output files have 0 size.';
1976 }
1977 3652 ▶ my @empty_dirs = grep { (-d $_) && _is_empty_dir($_) } @output_dirs;
Condition100%3/3
-d $_ && _is_empty_dir($_)
!ll&&!rl&&r
20214444
MC/DC100%2/2
-d $_ && _is_empty_dir($_)
-d $_ _is_empty_dir($_)
Truth table100%3/3
A && B
A= -d $_B= _is_empty_dir($_)
ABresult
0X0
100
111
1978 3652 ▶ if (scalar @empty_dirs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @empty_dirs > 0) 44 3608 3652
1979 44 p @empty_dirs, output => 'STDERR';
1980 44 warn 'the above output directories are empty.';
1981 }
1982 3652 ▶ _protect(@outputs) if $r{protect} && ($r{'will.do'} eq 'done');
Branch: 1 branch
BranchTrueFalseTotal
if $r{"protect"} and $r{"will.do"} eq "done" 108 3544 3652
Condition100%3/3
$r{"protect"} and $r{"will.do"} eq "done"
!ll&&!rl&&r
349054108
MC/DC100%2/2
$r{"protect"} and $r{"will.do"} eq "done"
$r{"protect"} $r{"will.do"} eq "done"
Truth table100%3/3
A and B
A= $r{"protect"}B= $r{"will.do"} eq "done"
ABresult
0X0
100
111
1983 # with or without stale_cmd; see where $signature is set
1984 3652 ▶ _write_signature($signature_file, $signature) if (defined $signature) && ($r{'will.do'} eq 'done');
Branch: 1 branch
BranchTrueFalseTotal
if defined $signature and $r{"will.do"} eq "done" 412 3240 3652
Condition66%2/3
defined $signature and $r{"will.do"} eq "done"
!ll&&!rl&&r
32400412
MC/DC50%1/2
defined $signature and $r{"will.do"} eq "done"
defined $signature $r{"will.do"} eq "done"
Truth table66%2/3
A and B
A= defined $signatureB= $r{"will.do"} eq "done"
ABresult
0X0
100
111
1985 # The record is printed once, whatever happened. Until 0.19 each kind of
1986 # failure had its own branch with its own _report, and the missing-output
1987 # one fell through into the next under die => 0, logging the record twice.
1988 3652 _report(\%r, $log_fh, $r{quiet}, $trace_fh);
1989 # An interrupt that arrived while a timed command ran has been held back
1990 # until now, so that the capture files are gone, STDIN is restored and the
1991 # record is in the log; see _run_forked. It goes to the caller's own
1992 # handler, or, with none, ends the program as it would have without
1993 # task() in the way.
1994 3652 ▶ kill $interrupted, $$ if defined $interrupted;
Branch: 1 branch
BranchTrueFalseTotal
if defined $interrupted 44 3608 3652
1995 # After the record is written, and before task() dies: a hook sees the
1996 # step as the log does, and a pipeline's on_failure runs even under the
1997 # default die => 1. An exception from a hook propagates as it is.
1998 3652 ▶ if ($r{'will.do'} ne 'FAILED') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"will.do"} ne "FAILED") 1946 1706 3652
1999 1946 ▶ $hook{'on_success'}->(\%r) if defined $hook{'on_success'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $hook{"on_success"} 12 1934 1946
2000 1946 return \%r;
2001 }
2002 1706 ▶ $hook{'on_failure'}->(\%r) if defined $hook{'on_failure'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $hook{"on_failure"} 10 1696 1706
2003 my $failure = "\"$cmd_string\" " . join('; ', _why_failed(\%r, $interrupted, $launch_error, @missing_outputs))
2004 1706 ▶ . (($r{attempts} > 1) ? " (after $r{attempts} attempts)" : '')
Branch: 1 branch
BranchTrueFalseTotal
$r{'attempts'} > 1 ? : 206 1500 1706
2005 . ", from $c[1] line $c[2]";
2006 1706 ▶ $failure .= "; stderr ended with:\n" . join('', map { "\t$_\n" } @stderr_tail) if scalar @stderr_tail > 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @stderr_tail > 0 206 1500 1706
2007 1706 ▶ die $failure if $r{'die'}; # the resolved value (defaults to 1), not the raw arg
Branch: 1 branch
BranchTrueFalseTotal
if $r{"die"} 280 1426 1706
2008 # die => 0 asks task not to stop the pipeline, not to keep quiet: a warning
2009 # is the only signal a caller gets that did not look at will.do.
2010 1426 warn $failure;
2011 1426 return \%r;
2012 }
2013 # Run several tasks at the same time, at most "jobs" at once, and return
2014 # their records in the order given. Each runs in a child of its own, forked
2015 # from here, which runs task() in full -- its checks, its log and its record --
2016 # and hands the record back through a file, with Storable, so that a record of
2017 # any size never has to fit in a pipe. The first task to die stops any more
2018 # from starting; those already running are let finish, and then parallel()
2019 # dies with every failure. With "keep_going", every task runs regardless, and
2020 # parallel() dies at the end if any did. POSIX-only for jobs > 1, like
2021 # "timeout": perl's fork() on MSWin32 is an emulation with threads, and the
2022 # children would share one working directory and one %ENV.
2023 262 ▶sub parallel {
Subroutine parallel: called CC=39 SCAR=37.2
Pod undocumented
2024 # Devel::Confess for this call only, as in task(): see _confess_here
2025 262 local $SIG{__DIE__} = $SIG{__DIE__};
2026 262 local $SIG{__WARN__} = $SIG{__WARN__};
2027 262 local $Devel::Confess::OLD_SIG{__DIE__} = $Devel::Confess::OLD_SIG{__DIE__};
2028 262 local $Devel::Confess::OLD_SIG{__WARN__} = $Devel::Confess::OLD_SIG{__WARN__};
2029 262 local $Devel::Confess::OPTIONS{color} = $Devel::Confess::OPTIONS{color};
2030 262 _confess_here();
2031 262 my @c = caller;
2032 262 ▶ die 'parallel() takes a flat key/value list: parallel(jobs => 4, tasks => [...])' if scalar(@_) % 2 != 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar(@_) % 2 != 0 2 260 262
2033 260 my %opt = @_;
2034 260 my @accepted = (
2035 'jobs', # whole number, 1 or more: how many tasks may run at once
2036 'keep_going', # bool; run every task even after one has failed
2037 'tasks', # array ref of hash refs, each the arguments of one task()
2038 );
2039 260 my @unknown = grep { my $key = $_; not grep { $_ eq $key } @accepted } sort keys %opt;
2040 6 die 'parallel() does not accept ' . join(', ', map { "\"$_\"" } @unknown)
2041 260 ▶ . '; it accepts ' . join(', ', map { "\"$_\"" } @accepted) if scalar @unknown > 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @unknown > 0 6 254 260
2042 254 ▶ if ((not defined $opt{jobs}) || ($opt{jobs} !~ /\A[1-9][0-9]*\z/)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opt{"jobs"} and $opt{"jobs"} =~ /\A[1-9][0-9]*\z/) 6 248 254
Condition66%2/3
defined $opt{"jobs"} and $opt{"jobs"} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
06248
MC/DC50%1/2
defined $opt{"jobs"} and $opt{"jobs"} =~ /\A[1-9][0-9]*\z/
defined $opt{"jobs"} $opt{"jobs"} =~ /\A[1-9][0-9]*\z/
Truth table66%2/3
A and B
A= defined $opt{"jobs"}B= $opt{"jobs"} =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
2043 6 die '"jobs" must be a whole number, 1 or more: how many tasks parallel() may run at once';
2044 }
2045 248 ▶ if (ref $opt{tasks} ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opt{"tasks"} ne "ARRAY") 6 242 248
2046 6 die '"tasks" must be an array ref of hash refs, each the arguments of one task()';
2047 }
2048 242 my @tasks = @{ $opt{tasks} };
2049 242 my @not_hashes = grep { ref $tasks[$_] ne 'HASH' } 0 .. $#tasks;
2050 242 ▶ if (scalar @not_hashes > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @not_hashes > 0) 6 236 242
2051 6 die '"tasks" must hold only hash refs of task() arguments; it does not at index '
2052 . join(', ', @not_hashes);
2053 }
2054 236 ▶ if (($opt{jobs} > 1) && ($^O eq 'MSWin32')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"jobs"} > 1 and $^O eq "MSWin32") 0 236 236
Condition66%2/3
$opt{"jobs"} > 1 and $^O eq "MSWin32"
!ll&&!rl&&r
182180
MC/DC0%0/2
$opt{"jobs"} > 1 and $^O eq "MSWin32"
$opt{"jobs"} > 1 $^O eq "MSWin32"
Truth table66%2/3
A and B
A= $opt{"jobs"} > 1B= $^O eq "MSWin32"
ABresult
0X0
100
111
2055 0 die '"jobs" above 1 is not supported on MSWin32: it needs a real fork(), and perl emulates one there with threads';
2056 }
2057 236 ▶ my $keep_going = $opt{'keep_going'} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'keep_going'} ? : 14 222 236
2058 # each task's source.file and source.line are the parallel() call's
2059 236 local $CALLER = [$c[1], $c[2]];
2060 236 my (@records, @failures); # @failures: [index, error]
2061 236 ▶ if ($opt{jobs} == 1) { # one at a time, here, with nothing to fork
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"jobs"} == 1) 18 218 236
2062 18 foreach my $i (0 .. $#tasks) {
2063 30 my $record = eval { task(%{ $tasks[$i] }) };
2064 24 ▶ if (defined $record) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $record) { } 10 14 24
2065 10 $records[$i] = $record;
2066 } else {
2067 14 push @failures, [$i, $@];
2068 14 ▶ last if not $keep_going;
Branch: 1 branch
BranchTrueFalseTotal
unless $keep_going 2 12 14
2069 }
2070 }
2071 12 ▶ return @records if scalar @failures == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @failures == 0 0 12 12
2072 12 die _parallel_failure(\@tasks, \@failures, \@c);
2073 }
2074 # Anything already written but still in a buffer is written now, before
2075 # the fork, or each child would inherit a copy and write it again.
2076 1748 my %handles = map { ($_ => $_) } grep { defined openhandle($_) } \*STDOUT, \*STDERR,
2077 218 map { ($_->{'log_fh'}, $_->{'trace_fh'}) } @tasks, \%DEFAULTS;
2078 218 _flush($_) foreach values %handles;
2079 # An interrupt to parallel() goes to every running task, which passes it
2080 # to its command before it ends; see _run_forked. It is then re-raised here
2081 # once every child is gone. One the caller ignores stays ignored.
2082 #
2083 # Each task is sent the signal parallel() received, which its child cannot
2084 # be ignoring: the child sets every signal in @interrupts back to the
2085 # caller's own disposition. Until 0.194 it was sent TERM, which a caller
2086 # that ignored TERM had left ignored in the child and the command alike, so
2087 # an INT or a HUP sent to parallel()'s process alone reached no task, and
2088 # each ran on to its end before the interrupt was re-raised.
2089 218 my %running; # pid => [index, the File::Temp its record comes back in]
2090 218 my $report_lock = File::Temp->new; # see $REPORT_LOCK
2091 218 my $interrupted;
2092 218 ▶ my @interrupts = grep { not ((defined $SIG{$_}) && ($SIG{$_} eq 'IGNORE')) } qw(HUP INT QUIT TERM);
Condition100%3/3
defined $SIG{$_} && $SIG{$_} eq 'IGNORE'
!ll&&!rl&&r
4808384
MC/DC100%2/2
defined $SIG{$_} && $SIG{$_} eq 'IGNORE'
defined $SIG{$_} $SIG{$_} eq 'IGNORE'
Truth table100%3/3
A && B
A= defined $SIG{$_}B= $SIG{$_} eq 'IGNORE'
ABresult
0X0
100
111
2093 218 my %caller_sig = map { $_ => $SIG{$_} } @interrupts;
2094 {
2095 218 ▶ local @SIG{@interrupts} = (sub {
Subroutine __ANON__: called CC=2 SCAR=7.4
2096 6 my $signal = shift;
2097 6 ▶ $interrupted //= $signal;
Condition33%1/3
$interrupted //= $signal
l!l&&r!l&&!r
060
MC/DC0%0/2
$interrupted //= $signal
$interrupted $signal
Truth table33%1/3
A //= B
A= $interruptedB= $signal
ABresult
1X1
011
000
2098 6 kill $signal, keys %running;
2099 218 }) x @interrupts;
2100 218 my $next = 0;
2101 218 while (1) {
2102 34878 ▶ while ((not defined $interrupted) && ($next <= $#tasks) && (scalar keys %running < $opt{jobs})
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $interrupted and $next <= $#tasks and scalar keys %running < $opt{"jobs"} and $keep_going || scalar @failures == 0) 1334 34808 36142
Condition91%11/12
not defined $interrupted and $next <= $#tasks and scalar keys %running < $opt{"jobs"} and $keep_going || scalar @failures == 0
!ll&&!rl&&r
340457631334
not defined $interrupted and $next <= $#tasks and scalar keys %running < $opt{"jobs"}
!ll&&!rl&&r
21377126682097
not defined $interrupted and $next <= $#tasks
!ll&&!rl&&r
182135914765
$keep_going or scalar @failures == 0
l!l&&r!l&&!r
01334763
MC/DC80%4/5
not defined $interrupted and $next <= $#tasks and scalar keys %running < $opt{"jobs"} and $keep_going || scalar @failures == 0
not defined $interrupted $next <= $#tasks scalar keys %running < $opt{"jobs"} $keep_going scalar @failures == 0
Truth table83%5/6
not(A) and B and C and D or E
A= not defined $interruptedB= $next <= $#tasksC= scalar keys %running < $opt{"jobs"}D= $keep_goingE= scalar @failures == 0
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
2103 && ($keep_going || (scalar @failures == 0))) {
2104 1334 my $i = $next++;
2105 1334 my $result = File::Temp->new;
2106 1334 my $pid = fork();
2107 1334 ▶ die "fork() failed, so parallel() cannot start task $i: $!" if not defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 1334 1334
2108 1334 ▶ if ($pid == 0) { # the child: one task, its record to the file, and out
Branch: 1 branch
BranchTrueFalseTotal
if ($pid == 0) 70 1264 1334
2109 # Everything up to the _exit is in the eval. Until 0.192
2110 # only task() was, and a failure to store the record or
2111 # flush a handle unwound into the caller's own evals as a
2112 # second copy of the caller's program. The parent then
2113 # reports that it got no record.
2114 eval {
2115 70 ▶ $SIG{$_} = $caller_sig{$_} // 'DEFAULT' foreach @interrupts;
Condition100%2/2
$caller_sig{$_} // "DEFAULT"
l!l
2159
MC/DC100%1/1
$caller_sig{$_} // "DEFAULT"
$caller_sig{$_}
Truth table100%2/2
A
A= $caller_sig{$_}
Aresult
11
00
2116 70 local $REPORT_LOCK = $report_lock->filename;
2117 70 my $record = eval { task(%{ $tasks[$i] }) };
2118 0 my $error = $@;
2119 0 ▶ Storable::nstore({ record => $record, error => (defined $record) ? '' : $error }, $result->filename);
Branch: 1 branch
BranchTrueFalseTotal
defined $record ? : 0 0 0
2120 0 _flush($_) foreach values %handles;
2121 0 1;
2122 0 ▶ } or eval { print STDERR "parallel() could not return the record of task $i: $@" };
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $SIG{$_} = $caller_sig{$_} // "DEFAULT" foreach (@interrupts); local $SimpleFlow::REPORT_LOCK = $report_lock->filename; my $record = eval { do { task(%{$tasks[$i];}) } }; my $error = $@; Storable::nstore({"record", $record, "error", defined $record ? "" : $error}, $result->filename); _flush($_) foreach (values %handles); 1 } } or eval { do { print STDERR "parallel() could not return the record of task ${i}: $@" } } 0 0 0
2123 # _exit, not exit: exit would run END blocks and the
2124 # destructors of the parent's objects, File::Temp's among them
2125 0 POSIX::_exit(0);
2126 }
2127 1264 $running{$pid} = [$i, $result];
2128 }
2129 34808 ▶ last if scalar keys %running == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %running == 0 148 34660 34808
2130 # Each child is waited for by its own pid, never with waitpid(-1),
2131 # which would reap -- and so steal the status of -- any other child
2132 # the caller has. Polled every 20 ms: half the time perl took to
2133 # start here (29-44 ms), so a slot is refilled before its next task
2134 # could have started anyway.
2135 #
2136 # -1 is a child that is no longer ours to wait for: a caller whose
2137 # SIGCHLD is ignored has its children reaped by the kernel, and a
2138 # caller's own SIGCHLD handler may reap them first. Either way it
2139 # has ended, and its record, if it wrote one, is in its file.
2140 # Until 0.192 only its pid counted, and parallel() waited for ever.
2141 my @finished = grep {
2142 34660 my $waited = waitpid($_, POSIX::WNOHANG());
2143 224344 ▶ ($waited == $_) || ($waited == -1);
Condition100%3/3
$waited == $_ || $waited == -1
l!l&&r!l&&!r
103544223265
MC/DC100%2/2
$waited == $_ || $waited == -1
$waited == $_ $waited == -1
Truth table100%3/3
A || B
A= $waited == $_B= $waited == -1
ABresult
1X1
011
000
2144 } keys %running;
2145 34660 ▶ if (scalar @finished == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @finished == 0) 33727 933 34660
2146 33727 Time::HiRes::sleep(0.02);
2147 33727 next;
2148 }
2149 933 foreach my $pid (@finished) {
2150 1079 my ($i, $result) = @{ delete $running{$pid} };
2151 1079 my $got = eval { Storable::retrieve($result->filename) };
2152 1079 ▶ if ((defined $got) && (defined $got->{record})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $got and defined $got->{'record'}) { } 1055 24 1079
elsif (defined $got and $got->{'error'} ne '') { } 20 4 24
Condition100%3/3
defined $got and defined $got->{"record"}
!ll&&!rl&&r
4201055
MC/DC100%2/2
defined $got and defined $got->{"record"}
defined $got defined $got->{"record"}
Truth table100%3/3
A and B
A= defined $gotB= defined $got->{"record"}
ABresult
0X0
100
111
2153 1055 $records[$i] = $got->{record};
2154 ▶ } elsif ((defined $got) && ($got->{error} ne '')) {
Condition66%2/3
defined $got and $got->{"error"} ne ""
!ll&&!rl&&r
4020
MC/DC50%1/2
defined $got and $got->{"error"} ne ""
defined $got $got->{"error"} ne ""
Truth table66%2/3
A and B
A= defined $gotB= $got->{"error"} ne ""
ABresult
0X0
100
111
2155 20 push @failures, [$i, $got->{error}];
2156 } else {
2157 4 push @failures, [$i, 'the process running it ended before it could return a record'];
2158 }
2159 }
2160 }
2161 }
2162 148 ▶ kill $interrupted, $$ if defined $interrupted; # the caller's handler is back in place
Branch: 1 branch
BranchTrueFalseTotal
if defined $interrupted 6 142 148
2163 148 ▶ return @records if scalar @failures == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @failures == 0 124 24 148
2164 24 die _parallel_failure(\@tasks, \@failures, \@c);
2165 }
2166 36 ▶sub _parallel_failure {
Subroutine _parallel_failure: called CC=4 SCAR=14.2
2167 36 my ($tasks, $failures, $c) = @_;
2168 0 my @sorted = sort { $a->[0] <=> $b->[0] } @$failures;
2169 return scalar(@sorted) . ' of ' . scalar(@$tasks) . " tasks failed in parallel() from $c->[1] line $c->[2]:\n"
2170 . join('', map {
2171 36 my ($i, $error) = @$_;
2172 36 my $cmd = $tasks->[$i]{cmd};
2173 36 ▶ $cmd = join(' ', @$cmd) if ref $cmd eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $cmd eq "ARRAY" 36 0 36
2174 36 ▶ "task $i (" . ($cmd // 'no cmd') . "): $error" . (($error =~ /\n\z/) ? '' : "\n")
Branch: 1 branch
BranchTrueFalseTotal
$error =~ /\n\z/ ? : 32 4 36
Condition50%1/2
$cmd // "no cmd"
l!l
360
MC/DC0%0/1
$cmd // "no cmd"
$cmd
Truth table50%1/2
A
A= $cmd
Aresult
11
00
2175 } @sorted);
2176 }
2177  
2178 # An HTML page of a pipeline's trace: every task in the order it was
2179 # traced, with its status, command, timing and exit, a timeline of when each
2180 # ran, and a count of each status at the top. The trace is what "trace_fh"
2181 # wrote, one JSON object a line; the page is a single file, with no scripts
2182 # and nothing fetched, so that it can be mailed or archived as it is.
2183 # Returns how many tasks it read.
2184 306 ▶sub report {
Subroutine report: called CC=56 SCAR=40.3
Pod undocumented
2185 # Devel::Confess for this call only, as in task(): see _confess_here
2186 306 local $SIG{__DIE__} = $SIG{__DIE__};
2187 306 local $SIG{__WARN__} = $SIG{__WARN__};
2188 306 local $Devel::Confess::OLD_SIG{__DIE__} = $Devel::Confess::OLD_SIG{__DIE__};
2189 306 local $Devel::Confess::OLD_SIG{__WARN__} = $Devel::Confess::OLD_SIG{__WARN__};
2190 306 local $Devel::Confess::OPTIONS{color} = $Devel::Confess::OPTIONS{color};
2191 306 _confess_here();
2192 306 ▶ die 'report() takes a flat key/value list: report(trace => ..., html => ...)' if scalar(@_) % 2 != 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar(@_) % 2 != 0 2 304 306
2193 304 my %opt = @_;
2194 304 my @accepted = (
2195 'html', # the file to write the page to
2196 'svg', # the file to write the flow diagram to, as an SVG image
2197 'title', # the page's title; by default, "SimpleFlow report"
2198 'trace', # the trace file to read, as "trace_fh" wrote it
2199 );
2200 304 my @unknown = grep { my $key = $_; not grep { $_ eq $key } @accepted } sort keys %opt;
2201 304 ▶ die 'report() does not accept ' . join(', ', map { "\"$_\"" } @unknown) if scalar @unknown > 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @unknown > 0 2 302 304
2202 # "html" was required until 0.196; now either output will do, or both
2203 302 ▶ die 'report() needs "html" or "svg", a file name to write' if (not defined $opt{html}) && (not defined $opt{svg});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $opt{"html"} or defined $opt{"svg"} 10 292 302
Condition100%3/3
defined $opt{"html"} or defined $opt{"svg"}
l!l&&r!l&&!r
14814410
MC/DC100%2/2
defined $opt{"html"} or defined $opt{"svg"}
defined $opt{"html"} defined $opt{"svg"}
Truth table100%3/3
A or B
A= defined $opt{"html"}B= defined $opt{"svg"}
ABresult
1X1
011
000
2204 292 foreach my $key ('trace', grep { defined $opt{$_} } 'html', 'svg') {
2205 594 ▶ die "report() needs \"$key\", a file name" if (not defined $opt{$key}) || (ref $opt{$key} ne '') || ($opt{$key} eq '');
Branch: 1 branch
BranchTrueFalseTotal
if not defined $opt{$key} or ref $opt{$key} ne "" or $opt{$key} eq "" 28 566 594
Condition83%5/6
not defined $opt{$key} or ref $opt{$key} ne "" or $opt{$key} eq ""
l!l&&r!l&&!r
1810566
not defined $opt{$key} or ref $opt{$key} ne ""
l!l&&r!l&&!r
018576
MC/DC66%2/3
not defined $opt{$key} or ref $opt{$key} ne "" or $opt{$key} eq ""
not defined $opt{$key} ref $opt{$key} ne "" $opt{$key} eq ""
Truth table75%3/4
not(A) or B or C
A= not defined $opt{$key}B= ref $opt{$key} ne ""C= $opt{$key} eq ""
ABCresult
1XX1
01X1
0011
0000
2206 }
2207 264 ▶ my $title = $opt{title} // 'SimpleFlow report';
Condition100%2/2
$opt{"title"} // "SimpleFlow report"
l!l
12252
MC/DC100%1/1
$opt{"title"} // "SimpleFlow report"
$opt{"title"}
Truth table100%2/2
A
A= $opt{"title"}
Aresult
11
00
2208 # A title of UTF-8 bytes -- read from a file or the command line, say --
2209 # is taken as the characters it encodes, as _json_string takes a byte
2210 # string. Until 0.192 it was encoded again with the page, and the two bytes
2211 # of the e in "caf\xc3\xa9" came out as two characters. Bytes that are not
2212 # UTF-8 are Latin-1 characters, as perl itself treats them.
2213 264 ▶ if (not utf8::is_utf8($title)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (utf8::is_utf8($title)) 264 0 264
2214 264 my $decoded = $title;
2215 264 ▶ $title = $decoded if utf8::decode($decoded);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::decode($decoded) 264 0 264
2216 }
2217 264 ▶ open my $in, '<', $opt{trace} or die "cannot read the trace \"$opt{trace}\": $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $in, "<", $opt{"trace"} or die qq[cannot read the trace "$opt{"trace"}": $!] 262 2 264
2218 262 my @tasks;
2219 262 ▶ while (my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 478 150 628
2220 478 ▶ next if $line !~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/ 4 474 478
2221 474 my $task = eval { _json_decode($line) };
2222 474 ▶ if ((not defined $task) || (ref $task ne 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $task or ref $task ne "HASH") 42 432 474
Condition66%2/3
not defined $task or ref $task ne "HASH"
l!l&&r!l&&!r
420432
MC/DC50%1/2
not defined $task or ref $task ne "HASH"
not defined $task ref $task ne "HASH"
Truth table66%2/3
not(A) or B
A= not defined $taskB= ref $task ne "HASH"
ABresult
1X1
011
000
2223 42 ▶ my $why = $@ || 'it is not a JSON object';
Condition50%1/2
$@ || 'it is not a JSON object'
l!l
420
MC/DC0%0/1
$@ || 'it is not a JSON object'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
2224 42 $why =~ s/ at \S+ line \d+.*//s;
2225 42 die "line $. of the trace \"$opt{trace}\" is not a task's record: $why";
2226 }
2227 432 my $bad = _bad_trace_field($task);
2228 432 ▶ die "line $. of the trace \"$opt{trace}\" is not a task's record: $bad" if defined $bad;
Branch: 1 branch
BranchTrueFalseTotal
if defined $bad 70 362 432
2229 362 push @tasks, $task;
2230 }
2231 150 close $in;
2232 150 my %label = ('done' => 'done', 'no' => 'skipped', 'no: dry run' => 'dry run', 'FAILED' => 'FAILED');
2233 150 my %class = ('done' => 'done', 'skipped' => 'skipped', 'dry run' => 'dry', 'FAILED' => 'failed');
2234 150 my %count;
2235 150 foreach my $task (@tasks) {
2236 360 ▶ $task->{_status} = $label{ $task->{'will.do'} // '' } // ($task->{'will.do'} // 'unknown');
Condition100%6/6
$label{$task->{"will.do"} // ""} // ($task->{"will.do"} // "unknown")
l!l
33426
$task->{"will.do"} // ""
l!l
34812
$task->{"will.do"} // "unknown"
l!l
1412
MC/DC100%1/1
$label{$task->{"will.do"} // ""} // ($task->{"will.do"} // "unknown")
$label{$task->{"will.do"} // ""}
MC/DC100%1/1
$task->{"will.do"} // ""
$task->{"will.do"}
Truth table100%2/2
A
A= $label{$task->{"will.do"} // ""}
Aresult
11
00
Truth table100%2/2
A
A= $task->{"will.do"}
Aresult
11
00
2237 360 $count{ $task->{_status} }++;
2238 }
2239 # The four statuses task() writes, then any other, from a trace it did not
2240 # write, under its own name. Until 0.196 the others were counted but not
2241 # shown, and "3 tasks: 1 done, 0 skipped, 0 failed" did not add up. The
2242 # tasks and dry runs are counted in the singular for one: until 0.196,
2243 # "1 tasks" and "1 dry runs".
2244 150 my %noun = ('FAILED' => 'failed');
2245 150 my @other = sort grep { not exists $class{$_} } keys %count;
2246 490 ▶ my @summary = map { my $k = $count{$_} // 0; "$k " . ($noun{$_} // $_) . ((($_ eq 'dry run') && ($k != 1)) ? 's' : '') }
Branch: 1 branch
BranchTrueFalseTotal
$_ eq 'dry run' && $k != 1 ? : 2 488 490
Condition87%7/8
$count{$_} // 0
l!l
202288
$noun{$_} // $_
l!l&&r!l&&!r
1503400
$_ eq "dry run" and $k != 1
!ll&&!rl&&r
476122
MC/DC100%1/1
$count{$_} // 0
$count{$_}
MC/DC0%0/2
$noun{$_} // $_
$noun{$_} $_
MC/DC100%2/2
$_ eq "dry run" and $k != 1
$_ eq "dry run" $k != 1
Truth table100%2/2
A
A= $count{$_}
Aresult
11
00
Truth table66%2/3
A // B
A= $noun{$_}B= $_
ABresult
1X1
011
000
Truth table100%3/3
A and B
A= $_ eq "dry run"B= $k != 1
ABresult
0X0
100
111
2247 150 ▶ (grep { ($_ ne 'dry run') || $count{$_} } 'done', 'skipped', 'FAILED', 'dry run'), @other;
Condition100%3/3
$_ ne 'dry run' || $count{$_}
l!l&&r!l&&!r
45014136
MC/DC100%2/2
$_ ne 'dry run' || $count{$_}
$_ ne 'dry run' $count{$_}
Truth table100%3/3
A || B
A= $_ ne 'dry run'B= $count{$_}
ABresult
1X1
011
000
2248 150 ▶ my $summary = scalar(@tasks) . ((scalar @tasks == 1) ? ' task: ' : ' tasks: ') . join(', ', @summary);
Branch: 1 branch
BranchTrueFalseTotal
scalar @tasks == 1 ? : 46 104 150
2249 150 my ($flow, $links) = _flow_svg(\@tasks, \%class);
2250 # the timeline spans the first start to the last end among tasks that ran
2251 150 ▶ my @ran = grep { ($_->{'start.time'} // 0) > 0 } @tasks;
Condition100%2/2
$_->{"start.time"} // 0
l!l
26334
MC/DC100%1/1
$_->{"start.time"} // 0
$_->{"start.time"}
Truth table100%2/2
A
A= $_->{"start.time"}
Aresult
11
00
2252 150 ▶ my $first = min(map { $_->{'start.time'} } @ran) // 0;
Condition100%2/2
&min(map({$_->{"start.time"};} @ran)) // 0
l!l
10140
MC/DC100%1/1
&min(map({$_->{"start.time"};} @ran)) // 0
&min(map({$_->{"start.time"};} @ran))
Truth table100%2/2
A
A= &min(map({$_->{"start.time"};} @ran))
Aresult
11
00
2253 150 ▶ my $last = max(map { $_->{'start.time'} + ($_->{duration} // 0) } @ran) // 0;
Condition75%3/4
&max(map({$_->{"start.time"} + ($_->{"duration"} // 0);} @ran)) // 0
l!l
10140
$_->{"duration"} // 0
l!l
220
MC/DC100%1/1
&max(map({$_->{"start.time"} + ($_->{"duration"} // 0);} @ran)) // 0
&max(map({$_->{"start.time"} + ($_->{"duration"} // 0);} @ran))
MC/DC0%0/1
$_->{"duration"} // 0
$_->{"duration"}
Truth table100%2/2
A
A= &max(map({$_->{"start.time"} + ($_->{"duration"} // 0);} @ran))
Aresult
11
00
Truth table50%1/2
A
A= $_->{"duration"}
Aresult
11
00
2254 150 ▶ my $span = ($last > $first) ? ($last - $first) : 1;
Branch: 1 branch
BranchTrueFalseTotal
$last > $first ? : 10 140 150
2255 150 my @rows;
2256 150 foreach my $i (0 .. $#tasks) {
2257 360 my $t = $tasks[$i];
2258 360 ▶ my $cmd = $t->{cmd} // '';
Condition50%1/2
$t->{"cmd"} // ""
l!l
3600
MC/DC0%0/1
$t->{"cmd"} // ""
$t->{"cmd"}
Truth table50%1/2
A
A= $t->{"cmd"}
Aresult
11
00
2259 my $started = (($t->{'start.time'} // 0) > 0)
2260 360 ▶ ? POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime int $t->{'start.time'}) : '';
Branch: 1 branch
BranchTrueFalseTotal
($t->{'start.time'} // 0) > 0 ? : 22 338 360
Condition100%2/2
$t->{"start.time"} // 0
l!l
26334
MC/DC100%1/1
$t->{"start.time"} // 0
$t->{"start.time"}
Truth table100%2/2
A
A= $t->{"start.time"}
Aresult
11
00
2261 360 my $bar = '';
2262 360 ▶ if (($t->{'start.time'} // 0) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (($t->{"start.time"} // 0) > 0) 22 338 360
Condition100%2/2
$t->{"start.time"} // 0
l!l
26334
MC/DC100%1/1
$t->{"start.time"} // 0
$t->{"start.time"}
Truth table100%2/2
A
A= $t->{"start.time"}
Aresult
11
00
2263 # A bar of at least half a percent, so that a quick task is seen,
2264 # moved left if it must be to end inside the lane. Until 0.196 a
2265 # quick task in the run's last half percent stuck out past the end.
2266 # The width is rounded first, so that the two rounded add to 100.
2267 22 ▶ my $width = sprintf '%.2f', max(0.5, 100 * ($t->{duration} // 0) / $span);
Condition50%1/2
$t->{"duration"} // 0
l!l
220
MC/DC0%0/1
$t->{"duration"} // 0
$t->{"duration"}
Truth table50%1/2
A
A= $t->{"duration"}
Aresult
11
00
2268 22 my $left = sprintf '%.2f', min(100 - $width, 100 * ($t->{'start.time'} - $first) / $span);
2269 22 ▶ my $bar_class = $class{ $t->{_status} } // 'other';
Condition100%2/2
$class{$t->{"_status"}} // "other"
l!l
202
MC/DC100%1/1
$class{$t->{"_status"}} // "other"
$class{$t->{"_status"}}
Truth table100%2/2
A
A= $class{$t->{"_status"}}
Aresult
11
00
2270 22 $bar = qq{<div class="bar $bar_class" style="margin-left:$left%;width:$width%"></div>};
2271 }
2272 360 ▶ my $cpu = sprintf '%.2f', ($t->{'cpu.user'} // 0) + ($t->{'cpu.system'} // 0);
Condition100%4/4
$t->{"cpu.user"} // 0
l!l
18342
$t->{"cpu.system"} // 0
l!l
18342
MC/DC100%1/1
$t->{"cpu.user"} // 0
$t->{"cpu.user"}
MC/DC100%1/1
$t->{"cpu.system"} // 0
$t->{"cpu.system"}
Truth table100%2/2
A
A= $t->{"cpu.user"}
Aresult
11
00
Truth table100%2/2
A
A= $t->{"cpu.system"}
Aresult
11
00
2273 push @rows, '<tr class="' . ($class{ $t->{_status} } // 'other') . '">'
2274 3960 ▶ . join('', map { "<td>$_</td>" }
Branch: 1 branch
BranchTrueFalseTotal
($t->{'note'} // '') ne '' ? : 10 350 360
Condition100%14/14
$t->{"note"} // ""
l!l
26334
$t->{"duration"} // 0
l!l
24336
$t->{"exit"} // ""
l!l
18342
$t->{"signal"} // ""
l!l
18342
$t->{"attempts"} // ""
l!l
18342
$t->{"source.file"} // ""
l!l
18342
$t->{"source.line"} // ""
l!l
18342
MC/DC100%1/1
$t->{"note"} // ""
$t->{"note"}
MC/DC100%1/1
$t->{"duration"} // 0
$t->{"duration"}
MC/DC100%1/1
$t->{"exit"} // ""
$t->{"exit"}
MC/DC100%1/1
$t->{"signal"} // ""
$t->{"signal"}
MC/DC100%1/1
$t->{"attempts"} // ""
$t->{"attempts"}
MC/DC100%1/1
$t->{"source.file"} // ""
$t->{"source.file"}
MC/DC100%1/1
$t->{"source.line"} // ""
$t->{"source.line"}
Truth table100%2/2
A
A= $t->{"note"}
Aresult
11
00
Truth table100%2/2
A
A= $t->{"duration"}
Aresult
11
00
Truth table100%2/2
A
A= $t->{"exit"}
Aresult
11
00
Truth table100%2/2
A
A= $t->{"signal"}
Aresult
11
00
Truth table100%2/2
A
A= $t->{"attempts"}
Aresult
11
00
Truth table100%2/2
A
A= $t->{"source.file"}
Aresult
11
00
Truth table100%2/2
A
A= $t->{"source.line"}
Aresult
11
00
2275 $i + 1,
2276 '<span class="status">' . _html($t->{_status}) . '</span>',
2277 '<code>' . _html($cmd) . '</code>'
2278 . ((($t->{note} // '') ne '') ? '<div class="note">' . _html($t->{note}) . '</div>' : ''),
2279 _html($started),
2280 sprintf('%.3f', $t->{duration} // 0),
2281 $cpu,
2282 _html($t->{'exit'} // ''),
2283 _html($t->{signal} // ''),
2284 _html($t->{attempts} // ''),
2285 360 ▶ _html(($t->{'source.file'} // '') . ':' . ($t->{'source.line'} // '')),
Condition100%2/2
$class{$t->{"_status"}} // "other"
l!l
33426
MC/DC100%1/1
$class{$t->{"_status"}} // "other"
$class{$t->{"_status"}}
Truth table100%2/2
A
A= $class{$t->{"_status"}}
Aresult
11
00
2286 qq{<div class="lane">$bar</div>})
2287 . '</tr>';
2288 }
2289 150 my $html = <<"HTML";
2290 <!doctype html>
2291 <html lang="en">
2292 <head>
2293 <meta charset="utf-8">
2294 <meta name="viewport" content="width=device-width, initial-scale=1">
2295 150 <title>@{[ _html($title) ]}</title>
2296 <style>
2297 :root { --bg: #ffffff; --fg: #1f2328; --muted: #656d76; --line: #d0d7de; --done: #1a7f37; --skipped: #8c959f; --failed: #cf222e; --dry: #9a6700; }
2298 \@media (prefers-color-scheme: dark) { :root { --bg: #0d1117; --fg: #e6edf3; --muted: #8d96a0; --line: #30363d; --done: #3fb950; --skipped: #6e7681; --failed: #f85149; --dry: #d29922; } }
2299 body { background: var(--bg); color: var(--fg); font: 14px/1.4 system-ui, sans-serif; margin: 16px; }
2300 h1 { font-size: 20px; margin: 0 0 4px; }
2301 p.summary { color: var(--muted); margin: 0 0 16px; }
2302 .table { overflow-x: auto; }
2303 table { border-collapse: collapse; width: 100%; }
2304 th, td { border-bottom: 1px solid var(--line); padding: 4px 8px; text-align: left; vertical-align: top; }
2305 th { color: var(--muted); font-weight: 600; white-space: nowrap; }
2306 td code { white-space: pre-wrap; word-break: break-all; }
2307 .note { color: var(--muted); }
2308 .status { font-weight: 600; }
2309 tr.done .status { color: var(--done); } tr.skipped .status { color: var(--skipped); }
2310 tr.failed .status { color: var(--failed); } tr.dry .status { color: var(--dry); }
2311 .lane { position: relative; min-width: 160px; height: 10px; margin-top: 4px; }
2312 .bar { height: 10px; border-radius: 2px; background: var(--skipped); } /* any status without its own color; until 0.196, none */
2313 .bar.done { background: var(--done); } .bar.failed { background: var(--failed); }
2314 h2 { font-size: 16px; margin: 24px 0 8px; }
2315 .flow { overflow: auto; max-height: 80vh; border: 1px solid var(--line); border-radius: 4px; }
2316 </style>
2317 </head>
2318 <body>
2319 150 <h1>@{[ _html($title) ]}</h1>
2320 150 <p class="summary">@{[ _html($summary) ]}</p>
2321 <div class="table">
2322 <table>
2323 <thead><tr><th>#</th><th>status</th><th>command</th><th>started</th><th>seconds</th><th>CPU s</th><th>exit</th><th>signal</th><th>attempts</th><th>source</th><th>timeline</th></tr></thead>
2324 <tbody>
2325 150 @{[ join("\n", @rows) ]}
2326 </tbody>
2327 </table>
2328 </div>
2329 150 ▶@{[ ($links > 0) ? qq{<h2>Flow</h2>\n<div class="flow">\n$flow</div>} : '' ]}
Branch: 1 branch
BranchTrueFalseTotal
$links > 0 ? : 62 88 150
2330 </body>
2331 </html>
2332 HTML
2333 150 my @out;
2334 150 ▶ push @out, [$opt{html}, $html, 'report'] if defined $opt{html};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"html"} 62 88 150
2335 150 ▶ push @out, [$opt{svg}, qq{<?xml version="1.0" encoding="UTF-8"?>\n$flow}, 'diagram'] if defined $opt{svg};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"svg"} 94 56 150
2336 150 _write_utf8(@out);
2337 136 return scalar @tasks;
2338 }
2339 # Write report()'s files, each given as [file, text, noun]: the text is
2340 # characters, written as the UTF-8 the page and the image say they are, and
2341 # the noun names the file in an error, 'report' or 'diagram'.
2342 #
2343 # Each is written under a File::Temp name in its own directory, and all are
2344 # renamed into place only once every one is written in full, so that a write
2345 # that fails leaves the files as they were. Until 0.196 each was opened in
2346 # place and written in turn, which left a page cut short by a full disk where
2347 # the old one had been, or a new page beside a diagram that could not be
2348 # written. File::Temp makes its files 0600, so each is given the mode open()
2349 # would have: the old file's, or 0666 less the umask. A link at a file's name
2350 # is replaced, where open() wrote through it. A rename that fails once the
2351 # writes have succeeded can still leave the earlier files renamed.
2352 150 ▶sub _write_utf8 {
Subroutine _write_utf8: called CC=13 SCAR=26.6
2353 150 my @partial; # [the File::Temp name, the file, the noun]
2354 my $error;
2355 150 foreach my $out (@_) {
2356 156 my ($file, $text, $noun) = @$out;
2357 156 utf8::encode($text);
2358 156 my ($volume, $dirs) = File::Spec->splitpath($file);
2359 156 my $dir = File::Spec->catpath($volume, $dirs, '');
2360 156 ▶ $dir = File::Spec->curdir if $dir eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $dir eq "" 0 156 156
2361 156 my $fh = eval { File::Temp->new(DIR => $dir, TEMPLATE => 'partial-XXXXXXXX', UNLINK => 0) };
2362 156 ▶ if (not defined $fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $fh) 14 142 156
2363 14 (my $why = $@) =~ s/ at \S+ line \d+.*//s;
2364 14 $error = "cannot write the $noun \"$file\": $why";
2365 14 last;
2366 }
2367 142 push @partial, [$fh->filename, $file, $noun];
2368 142 ▶ my $mode = (-e $file) ? ((stat _)[2] & 07777) : (0666 & ~(umask() // 0)); # umask is undef where unimplemented
Branch: 1 branch
BranchTrueFalseTotal
-e $file ? : 16 126 142
Condition50%1/2
umask() // 0
l!l
1260
MC/DC0%0/1
umask() // 0
umask()
Truth table50%1/2
A
A= umask()
Aresult
11
00
2369 142 binmode $fh;
2370 142 ▶ if (not ((print {$fh} $text) && (close $fh) && (chmod $mode, $fh->filename))) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print {$fh;} $text and close $fh and chmod $mode, $fh->filename) 0 142 142
Condition33%2/6
print {$fh;} $text and close $fh and chmod $mode, $fh->filename
!ll&&!rl&&r
00142
print {$fh;} $text and close $fh
!ll&&!rl&&r
00142
MC/DC0%0/3
print {$fh;} $text and close $fh and chmod $mode, $fh->filename
print {$fh;} $text close $fh chmod $mode, $fh->filename
Truth table25%1/4
A and B and C
A= print {$fh;} $textB= close $fhC= chmod $mode, $fh->filename
ABCresult
0XX0
10X0
1100
1111
2371 0 $error = "cannot write the $noun \"$file\": $!";
2372 0 last;
2373 }
2374 }
2375 150 foreach my $k (0 .. $#partial) {
2376 142 ▶ last if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 4 138 142
2377 138 my ($name, $file, $noun) = @{ $partial[$k] };
2378 138 ▶ if (rename $name, $file) {
Branch: 1 branch
BranchTrueFalseTotal
if (rename $name, $file) { } 138 0 138
2379 138 $partial[$k] = undef;
2380 } else {
2381 0 $error = "cannot write the $noun \"$file\": $!";
2382 }
2383 }
2384 150 ▶ if (defined $error) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $error) 14 136 150
2385 14 unlink map { $_->[0] } grep { defined } @partial;
2386 14 die $error;
2387 }
2388 136 return;
2389 }
2390 # The flow diagram of a trace, as an SVG image, and the number of arrows in it.
2391 #
2392 # Each task is a box, and an arrow runs from a task to a later one that reads
2393 # what it wrote, as Snakemake's --dag and Nextflow's -with-dag draw them: an
2394 # input file or directory is linked to the most recent earlier task that
2395 # declared it as an output, or, failing that, declared a directory it is in.
2396 # Names are compared as absolute paths, each made from the record's "dir", the
2397 # directory the step ran in, so that "a.txt" and "./a.txt" are one file, and
2398 # the same name in two directories is two. Only earlier tasks are searched,
2399 # so the graph has no cycles, and a pipeline re-run onto the same trace links
2400 # the second run's tasks to each other, not to the first's.
2401 #
2402 # A task's column is one more than the furthest of the tasks it reads from
2403 # (longest-path layering), so the flow runs left to right. Within a column the
2404 # boxes are ordered by the mean row of their neighbors (the barycenter
2405 # heuristic of Sugiyama, Tagawa and Toda, 1981), to keep arrows from crossing.
2406 # There is no routing: an arrow that skips a column is drawn behind its boxes.
2407 #
2408 # Sizes are SVG user units (px). The label is set in a monospace face, whose
2409 # advance is 0.6 em in DejaVu Sans Mono, Menlo and Courier (Consolas, 0.55),
2410 # so that the 33 characters of a label take 33 * 0.6 * 11 = 218 of the 224
2411 # the box leaves inside its 8 of padding on each side, without font metrics.
2412 447 my %FLOW = (
2413 box_w => 240, box_h => 44, # a task's box
2414 gap_x => 56, gap_y => 14, # between columns, and between boxes in one
2415 pad => 12, # around the whole diagram
2416 chars => 33, # the longest label, in characters
2417 sweeps => 4, # ordering passes, alternately forwards and back; more rarely helps
2418 );
2419 447 my %FLOW_COLOR = ( # light, then dark: the report's own palette
2420 bg => ['#ffffff', '#0d1117'], fg => ['#1f2328', '#e6edf3'],
2421 muted => ['#656d76', '#8d96a0'], line => ['#8c959f', '#6e7681'],
2422 done => ['#1a7f37', '#3fb950'], failed => ['#cf222e', '#f85149'],
2423 dry => ['#9a6700', '#d29922'], skipped => ['#8c959f', '#6e7681'],
2424 );
2425 150 ▶sub _flow_svg {
Subroutine _flow_svg: called CC=42 SCAR=37.4
2426 150 my ($tasks, $class) = @_; # $class: report()'s CSS class of each status
2427 150 my $n = scalar @$tasks;
2428 150 my (%producer, %files, @preds);
2429 150 my @succs = map { [] } 1 .. $n;
2430 150 foreach my $j (0 .. $n - 1) {
2431 360 my $t = $tasks->[$j];
2432 360 my (%from, %seen);
2433 360 ▶ foreach my $name (map { @{ $t->{$_} // [] } } 'input_files', 'input_dirs') {
Condition100%2/2
$t->{$_} // []
l!l
148572
MC/DC100%1/1
$t->{$_} // []
$t->{$_}
Truth table100%2/2
A
A= $t->{$_}
Aresult
11
00
2434 152 my @keys = _flow_keys($name, $t->{dir});
2435 # each file once in an arrow's tooltip, as first written, however
2436 # many times or ways the task names it: until 0.196, "a\na\n./a"
2437 152 ▶ next if $seen{ $keys[0] }++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$keys[0]}++ 4 148 152
2438 148 my ($i) = grep { defined } map { $producer{$_} } @keys;
2439 148 ▶ next if not defined $i;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $i 24 124 148
2440 124 push @{ $files{"$i $j"} }, $name;
2441 124 $from{$i} = 1;
2442 }
2443 360 $preds[$j] = [sort { $a <=> $b } keys %from];
2444 360 push @{ $succs[$_] }, $j foreach @{ $preds[$j] };
2445 # after the inputs, so that a step that rewrites its input is not its own source
2446 360 ▶ $producer{ (_flow_keys($_, $t->{dir}))[0] } = $j foreach map { @{ $t->{$_} // [] } } 'output_files', 'output_dirs';
Condition100%2/2
$t->{$_} // []
l!l
150570
MC/DC100%1/1
$t->{$_} // []
$t->{$_}
Truth table100%2/2
A
A= $t->{$_}
Aresult
11
00
2447 }
2448 150 my @layer;
2449 150 foreach my $j (0 .. $n - 1) {
2450 360 $layer[$j] = 1 + max(-1, map { $layer[$_] } @{ $preds[$j] });
2451 }
2452 150 my $depth = max(0, @layer); # the last column
2453 # An arrow that skips columns takes a row in each column it crosses, as a
2454 # placeholder node numbered from $n up, so that it runs between the boxes
2455 # there and not behind one. @up and @down are the neighbors of every
2456 # node, placeholders included, along the arrows' routes.
2457 150 my %route; # "$i $j" => [$i, the placeholders, $j]
2458 150 my @up = map { [] } 1 .. $n;
2459 150 my @down = map { [] } 1 .. $n;
2460 150 ▶ foreach my $edge (sort { ($a->[0] <=> $b->[0]) || ($a->[1] <=> $b->[1]) } map { [split / /] } keys %files) {
Condition66%2/3
$SimpleFlow::a->[0] <=> $SimpleFlow::b->[0] || $SimpleFlow::a->[1] <=> $SimpleFlow::b->[1]
l!l&&r!l&&!r
40240
MC/DC0%0/2
$SimpleFlow::a->[0] <=> $SimpleFlow::b->[0] || $SimpleFlow::a->[1] <=> $SimpleFlow::b->[1]
$SimpleFlow::a->[0] <=> $SimpleFlow::b->[0] $SimpleFlow::a->[1] <=> $SimpleFlow::b->[1]
Truth table66%2/3
A || B
A= $SimpleFlow::a->[0] <=> $SimpleFlow::b->[0]B= $SimpleFlow::a->[1] <=> $SimpleFlow::b->[1]
ABresult
1X1
011
000
2461 122 my ($i, $j) = @$edge;
2462 122 my @path = ($i);
2463 122 foreach my $c ($layer[$i] + 1 .. $layer[$j] - 1) {
2464 8 push @layer, $c;
2465 8 push @path, $#layer;
2466 }
2467 122 push @path, $j;
2468 122 foreach my $k (1 .. $#path) {
2469 130 push @{ $up[ $path[$k] ] }, $path[$k - 1];
2470 130 push @{ $down[ $path[$k - 1] ] }, $path[$k];
2471 }
2472 122 $route{"$i $j"} = \@path;
2473 }
2474 150 my @cols = map { [] } 0 .. $depth;
2475 150 push @{ $cols[ $layer[$_] ] }, $_ foreach 0 .. $#layer;
2476 150 my @pos; # each node's row within its column
2477 150 foreach my $col (@cols) {
2478 240 $pos[ $col->[$_] ] = $_ foreach 0 .. $#$col;
2479 }
2480 150 foreach my $sweep (1 .. $FLOW{sweeps}) {
2481 600 my $forward = $sweep % 2;
2482 600 ▶ foreach my $c ($forward ? (1 .. $depth) : reverse(0 .. $depth - 1)) {
Branch: 1 branch
BranchTrueFalseTotal
$forward ? : 300 300 600
2483 360 my %key;
2484 360 foreach my $j (@{ $cols[$c] }) {
2485 504 ▶ my @near = @{ $forward ? ($up[$j] // []) : ($down[$j] // []) };
Branch: 1 branch
BranchTrueFalseTotal
$forward ? : 244 260 504
Condition50%2/4
$up[$j] // []
l!l
2440
$down[$j] // []
l!l
2600
MC/DC0%0/1
$up[$j] // []
$up[$j]
MC/DC0%0/1
$down[$j] // []
$down[$j]
Truth table50%1/2
A
A= $up[$j]
Aresult
11
00
Truth table50%1/2
A
A= $down[$j]
Aresult
11
00
2486 504 ▶ $key{$j} = (scalar @near > 0) ? sum(map { $pos[$_] } @near) / scalar(@near) : $pos[$j];
Branch: 1 branch
BranchTrueFalseTotal
scalar @near > 0 ? : 456 48 504
2487 }
2488 360 ▶ $cols[$c] = [sort { ($key{$a} <=> $key{$b}) || ($pos[$a] <=> $pos[$b]) } @{ $cols[$c] }];
Condition66%2/3
$key{$a} <=> $key{$b} || $pos[$a] <=> $pos[$b]
l!l&&r!l&&!r
80800
MC/DC0%0/2
$key{$a} <=> $key{$b} || $pos[$a] <=> $pos[$b]
$key{$a} <=> $key{$b} $pos[$a] <=> $pos[$b]
Truth table66%2/3
A || B
A= $key{$a} <=> $key{$b}B= $pos[$a] <=> $pos[$b]
ABresult
1X1
011
000
2489 360 $pos[ $cols[$c][$_] ] = $_ foreach 0 .. $#{ $cols[$c] };
2490 }
2491 }
2492 150 my $rows = max(map { scalar @$_ } @cols);
2493 150 ▶ my $columns = ($n > 0) ? $depth + 1 : 0; # an empty trace is a diagram of its margins
Branch: 1 branch
BranchTrueFalseTotal
$n > 0 ? : 142 8 150
2494 150 my $width = 2 * $FLOW{pad} + $columns * $FLOW{box_w} + max(0, $columns - 1) * $FLOW{gap_x};
2495 150 my $height = 2 * $FLOW{pad} + $rows * $FLOW{box_h} + max(0, $rows - 1) * $FLOW{gap_y};
2496 150 my (@x, @y);
2497 150 foreach my $j (0 .. $#layer) {
2498 368 my $center = ($rows - scalar @{ $cols[ $layer[$j] ] }) / 2; # a short column is centered
2499 368 $x[$j] = $FLOW{pad} + $layer[$j] * ($FLOW{box_w} + $FLOW{gap_x});
2500 368 $y[$j] = $FLOW{pad} + ($center + $pos[$j]) * ($FLOW{box_h} + $FLOW{gap_y});
2501 }
2502 my @css = map {
2503 150 my $k = $_; # 0 = light, 1 = dark
2504 300 my %c = map { $_ => $FLOW_COLOR{$_}[$k] } keys %FLOW_COLOR;
2505 join("\n",
2506 ".sf-bg { fill: $c{bg}; }",
2507 ".sf-task rect { fill: $c{bg}; stroke: $c{muted}; stroke-width: 1.5; }",
2508 300 (map { ".sf-$_ rect { stroke: $c{$_}; } .sf-$_ .sf-head { fill: $c{$_}; }" } 'done', 'failed', 'dry', 'skipped'),
2509 ".sf-task text { fill: $c{fg}; }",
2510 ".sf-edge { fill: none; stroke: $c{line}; stroke-width: 1.5; }",
2511 ".sf-arrow { fill: $c{line}; }");
2512 } 0, 1;
2513 150 my $f = $FLOW{box_h} / 2;
2514 150 my @svg = (
2515 qq{<svg xmlns="http://www.w3.org/2000/svg" class="sf-flow" width="$width" height="$height" viewBox="0 0 $width $height" role="img" aria-label="the flow of $n tasks">},
2516 '<style>',
2517 $css[0],
2518 '.sf-task text { font-family: ui-monospace, Menlo, Consolas, "DejaVu Sans Mono", monospace; font-size: 11px; }',
2519 '.sf-head { font-weight: bold; }',
2520 '@media (prefers-color-scheme: dark) {',
2521 $css[1],
2522 '}',
2523 '</style>',
2524 '<defs><marker id="sf-arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="7" markerHeight="7" orient="auto">'
2525 . '<path class="sf-arrow" d="M 0 0 L 10 5 L 0 10 z"/></marker></defs>',
2526 qq{<rect class="sf-bg" width="$width" height="$height"/>},
2527 );
2528 # arrows first, so that the boxes are drawn over them
2529 # a curve across each gap between columns, and a straight line through
2530 # each placeholder's row
2531 150 foreach my $edge (sort keys %route) {
2532 122 my @path = @{ $route{$edge} };
2533 122 my ($x1, $y1) = ($x[ $path[0] ] + $FLOW{box_w}, $y[ $path[0] ] + $f);
2534 122 my $d = "M $x1 $y1";
2535 122 foreach my $k (@path[1 .. $#path]) {
2536 130 my ($x2, $y2) = ($x[$k], $y[$k] + $f);
2537 130 my $mid = ($x1 + $x2) / 2;
2538 130 $d .= " C $mid $y1, $mid $y2, $x2 $y2";
2539 130 ($x1, $y1) = ($x2 + $FLOW{box_w}, $y2);
2540 130 ▶ $d .= " L $x1 $y1" if $k >= $n;
Branch: 1 branch
BranchTrueFalseTotal
if $k >= $n 8 122 130
2541 }
2542 push @svg, qq{<path class="sf-edge" d="$d" marker-end="url(#sf-arrow)">}
2543 122 . '<title>' . _xml(join "\n", @{ $files{$edge} }) . '</title></path>';
2544 }
2545 150 foreach my $j (0 .. $n - 1) {
2546 360 my $t = $tasks->[$j];
2547 360 ▶ my $label = $t->{cmd} // '';
Condition50%1/2
$t->{"cmd"} // ""
l!l
3600
MC/DC0%0/1
$t->{"cmd"} // ""
$t->{"cmd"}
Truth table50%1/2
A
A= $t->{"cmd"}
Aresult
11
00
2548 360 $label =~ s/\A\s+|\s+\z//g; # so that "\n echo hi\n" is "echo hi", not " echo hi "
2549 360 $label =~ s/\s+/ /g;
2550 360 ▶ $label = substr($label, 0, $FLOW{chars} - 1) . "\x{2026}" if length($label) > $FLOW{chars};
Branch: 1 branch
BranchTrueFalseTotal
if length $label > $FLOW{"chars"} 18 342 360
2551 360 ▶ my @tip = ('#' . ($j + 1) . " $t->{_status}", $t->{cmd} // '');
Condition50%1/2
$t->{"cmd"} // ""
l!l
3600
MC/DC0%0/1
$t->{"cmd"} // ""
$t->{"cmd"}
Truth table50%1/2
A
A= $t->{"cmd"}
Aresult
11
00
2552 360 ▶ push @tip, $t->{note} if ($t->{note} // '') ne '';
Branch: 1 branch
BranchTrueFalseTotal
if ($t->{"note"} // "") ne "" 10 350 360
Condition100%2/2
$t->{"note"} // ""
l!l
26334
MC/DC100%1/1
$t->{"note"} // ""
$t->{"note"}
Truth table100%2/2
A
A= $t->{"note"}
Aresult
11
00
2553 360 foreach my $way ('input', 'output') {
2554 720 ▶ my @names = map { @{ $t->{$_} // [] } } "${way}_files", "${way}_dirs";
Condition100%2/2
$t->{$_} // []
l!l
2981142
MC/DC100%1/1
$t->{$_} // []
$t->{$_}
Truth table100%2/2
A
A= $t->{$_}
Aresult
11
00
2555 720 ▶ push @tip, "${way}s: " . join(', ', @names) if scalar @names > 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @names > 0 256 464 720
2556 }
2557 360 my ($tx, $ty) = ($x[$j] + 8, $y[$j]);
2558 push @svg, '<g class="sf-task sf-' . ($class->{ $t->{_status} } // 'other') . '">'
2559 . '<title>' . _xml(join "\n", @tip) . '</title>'
2560 . qq{<rect x="$x[$j]" y="$y[$j]" width="$FLOW{box_w}" height="$FLOW{box_h}" rx="4"/>}
2561 360 ▶ . '<text class="sf-head" x="' . $tx . '" y="' . ($ty + 17) . '">#' . ($j + 1) . ' ' . _xml($t->{_status}) . '</text>'
Condition100%2/2
$$class{$t->{"_status"}} // "other"
l!l
33426
MC/DC100%1/1
$$class{$t->{"_status"}} // "other"
$$class{$t->{"_status"}}
Truth table100%2/2
A
A= $$class{$t->{"_status"}}
Aresult
11
00
2562 . '<text x="' . $tx . '" y="' . ($ty + 34) . '">' . _xml($label) . '</text></g>';
2563 }
2564 150 push @svg, '</svg>';
2565 150 return (join("\n", @svg) . "\n", scalar keys %files);
2566 }
2567 # A name as an absolute path, made from the directory its step ran in, then
2568 # each directory above it, nearest first: the keys an input is looked up by.
2569 # A trace written before 0.19 has no "dir", and its names are compared as
2570 # they are.
2571 #
2572 # The path is resolved through any symbolic links, as far as it still
2573 # exists, because "dir" is recorded with getcwd(), which gives the real path:
2574 # a step run in "dir" => '/tmp/x' records /private/tmp/x on macOS, where /tmp
2575 # is a link, and until 0.196 its output "a" was not the "/tmp/x/a" another
2576 # step read.
2577 280 ▶sub _flow_keys {
Subroutine _flow_keys: called CC=6 SCAR=17.9
2578 280 my ($name, $dir) = @_;
2579 280 ▶ my $key = File::Spec->canonpath((defined $dir) && ($dir ne '') ? File::Spec->rel2abs($name, $dir) : $name);
Branch: 1 branch
BranchTrueFalseTotal
defined $dir && $dir ne '' ? : 256 24 280
Condition66%2/3
defined $dir and $dir ne ""
!ll&&!rl&&r
240256
MC/DC50%1/2
defined $dir and $dir ne ""
defined $dir $dir ne ""
Truth table66%2/3
A and B
A= defined $dirB= $dir ne ""
ABresult
0X0
100
111
2580 280 ▶ $key = _resolved($key) if File::Spec->file_name_is_absolute($key);
Branch: 1 branch
BranchTrueFalseTotal
if "File::Spec"->file_name_is_absolute($key) 256 24 280
2581 280 my @keys = ($key);
2582 280 while (1) {
2583 1308 my ($volume, $dirs) = File::Spec->splitpath($keys[-1]);
2584 1308 my $up = File::Spec->canonpath(File::Spec->catpath($volume, $dirs, ''));
2585 1308 ▶ last if ($up eq '') || ($up eq $keys[-1]);
Branch: 1 branch
BranchTrueFalseTotal
if $up eq "" or $up eq $keys[-1] 280 1028 1308
Condition100%3/3
$up eq "" or $up eq $keys[-1]
l!l&&r!l&&!r
242561028
MC/DC100%2/2
$up eq "" or $up eq $keys[-1]
$up eq "" $up eq $keys[-1]
Truth table100%3/3
A or B
A= $up eq ""B= $up eq $keys[-1]
ABresult
1X1
011
000
2586 1028 push @keys, $up;
2587 }
2588 280 return @keys;
2589 }
2590 # An absolute path with its longest existing head replaced by that head's
2591 # real path, and the names after it, which do not exist (yet, or any more),
2592 # kept as they are. Unchanged when nothing of it exists or the head cannot be
2593 # resolved, as for a trace read on another machine.
2594 256 ▶sub _resolved {
Subroutine _resolved: called CC=6 SCAR=18.2
2595 256 my $path = shift;
2596 256 my @tail;
2597 256 my $head = $path;
2598 256 ▶ while (not -e $head) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $head) 480 256 736
2599 480 my ($volume, $dirs, $last) = File::Spec->splitpath($head);
2600 480 my $up = File::Spec->canonpath(File::Spec->catpath($volume, $dirs, ''));
2601 480 ▶ return $path if ($up eq '') || ($up eq $head);
Branch: 1 branch
BranchTrueFalseTotal
if $up eq "" or $up eq $head 0 480 480
Condition33%1/3
$up eq "" or $up eq $head
l!l&&r!l&&!r
00480
MC/DC0%0/2
$up eq "" or $up eq $head
$up eq "" $up eq $head
Truth table33%1/3
A or B
A= $up eq ""B= $up eq $head
ABresult
1X1
011
000
2602 480 unshift @tail, $last;
2603 480 $head = $up;
2604 }
2605 256 my $real = _realpath($head);
2606 256 ▶ return $path if not defined $real;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $real 0 256 256
2607 256 ▶ return (scalar @tail > 0) ? File::Spec->catfile($real, @tail) : File::Spec->canonpath($real);
Branch: 1 branch
BranchTrueFalseTotal
scalar @tail > 0 ? : 236 20 256
2608 }
2609 # Text for XML: _html, after replacing what XML 1.0 cannot hold even escaped,
2610 # the control characters other than tab, newline and return, with U+FFFD. An
2611 # HTML page shows them; an SVG file with one in it is not an image at all.
2612 1202 ▶sub _xml {
Subroutine _xml: called CC=2 SCAR=7.0
2613 1202 my $text = shift;
2614 1202 ▶ $text = '' if not defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 1202 1202
2615 1202 $text =~ s/[\x00-\x08\x0B\x0C\x0E-\x1F\x{FFFE}\x{FFFF}]/\x{FFFD}/g;
2616 1202 return _html($text);
2617 }
2618 # Why a decoded trace line cannot be shown, or undef if it can. The page does
2619 # arithmetic with the times and puts the rest in its cells, and until 0.192 a
2620 # line with a string for a time died "isn't numeric", deep inside report(),
2621 # and one with a list for a command showed "ARRAY(0x...)". A start time is
2622 # epoch seconds below 1e15, the year 31690708: past 1e16 perl's localtime
2623 # dies on 5.44.0 ("too large", at 1e17) and returns nothing on 5.10.1.
2624 447 my @TRACE_TIMES = ('start.time', 'duration', 'cpu.user', 'cpu.system');
2625 447 my @TRACE_TEXTS = ('cmd', 'note', 'will.do', 'exit', 'signal', 'attempts', 'source.file', 'source.line', 'dir');
2626 # the names the flow diagram links tasks by, each a list of strings
2627 447 my @TRACE_NAMES = ('input_files', 'input_dirs', 'output_files', 'output_dirs');
2628 432 ▶sub _bad_trace_field {
Subroutine _bad_trace_field: called CC=16 SCAR=27.7
2629 432 my $task = shift;
2630 432 foreach my $field (@TRACE_NAMES) {
2631 1680 my $names = $task->{$field};
2632 1680 ▶ next if not defined $names;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $names 1350 330 1680
2633 return "its \"$field\" is not a list of names"
2634 330 ▶ if (ref $names ne 'ARRAY') || grep { (not defined $_) || (ref $_ ne '') || ($_ eq '') } @$names;
Branch: 1 branch
BranchTrueFalseTotal
if ref $names ne "ARRAY" or grep {not defined $_ or ref $_ ne "" or $_ eq "";} @$names 32 298 330
Condition100%9/9
ref $names ne "ARRAY" or grep {not defined $_ or ref $_ ne "" or $_ eq "";} @$names
l!l&&r!l&&!r
824298
!defined($_) || ref $_ ne '' || $_ eq ''
l!l&&r!l&&!r
168280
not defined $_ or ref $_ ne ""
l!l&&r!l&&!r
88288
MC/DC100%2/2
ref $names ne "ARRAY" or grep {not defined $_ or ref $_ ne "" or $_ eq "";} @$names
ref $names ne "ARRAY" grep {not defined $_ or ref $_ ne "" or $_ eq "";} @$names
MC/DC100%3/3
!defined($_) || ref $_ ne '' || $_ eq ''
not defined $_ ref $_ ne "" $_ eq ''
Truth table100%3/3
A or B
A= ref $names ne "ARRAY"B= grep {not defined $_ or ref $_ ne "" or $_ eq "";} @$names
ABresult
1X1
011
000
Truth table100%4/4
not(A) or B || C
A= not defined $_B= ref $_ ne ""C= $_ eq ''
ABCresult
1XX1
01X1
0011
0000
2635 }
2636 400 foreach my $field (@TRACE_TIMES) {
2637 1570 my $value = $task->{$field};
2638 1570 ▶ next if not defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1464 106 1570
2639 106 ▶ return "its \"$field\" is not a number of seconds, 0 or more"
Branch: 1 branch
BranchTrueFalseTotal
if ref $value ne "" or not $value =~ /$JSON_NUMBER/ or $value < 0 10 96 106
Condition66%4/6
ref $value ne "" or not $value =~ /$JSON_NUMBER/ or $value < 0
l!l&&r!l&&!r
10096
ref $value ne "" or not $value =~ /$JSON_NUMBER/
l!l&&r!l&&!r
01096
MC/DC33%1/3
ref $value ne "" or not $value =~ /$JSON_NUMBER/ or $value < 0
ref $value ne "" not $value =~ /$JSON_NUMBER/ $value < 0
Truth table50%2/4
A or not(B) or C
A= ref $value ne ""B= not $value =~ /$JSON_NUMBER/C= $value < 0
ABCresult
1XX1
01X1
0011
0000
2640 if (ref $value ne '') || ($value !~ $JSON_NUMBER) || ($value < 0); # "Inf" fails the pattern
2641 }
2642 return "its \"start.time\" is not a time since the epoch, in seconds"
2643 390 ▶ if (defined $task->{'start.time'}) && ($task->{'start.time'} >= 1e15);
Branch: 1 branch
BranchTrueFalseTotal
if defined $task->{"start.time"} and $task->{"start.time"} >= "1e+15" 10 380 390
Condition100%3/3
defined $task->{"start.time"} and $task->{"start.time"} >= "1e+15"
!ll&&!rl&&r
3542610
MC/DC100%2/2
defined $task->{"start.time"} and $task->{"start.time"} >= "1e+15"
defined $task->{"start.time"} $task->{"start.time"} >= "1e+15"
Truth table100%3/3
A and B
A= defined $task->{"start.time"}B= $task->{"start.time"} >= "1e+15"
ABresult
0X0
100
111
2644 380 foreach my $field (@TRACE_TEXTS) {
2645 3340 ▶ return "its \"$field\" is not a single value" if ref $task->{$field} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if ref $task->{$field} ne "" 18 3322 3340
2646 }
2647 362 return undef;
2648 }
2649  
2650 4182 ▶sub _html {
Subroutine _html: called CC=2 SCAR=7.0
2651 4182 my $text = shift;
2652 4182 ▶ $text = '' if not defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 4182 4182
2653 4182 $text =~ s/&/&amp;/g;
2654 4182 $text =~ s/</&lt;/g;
2655 4182 $text =~ s/>/&gt;/g;
2656 4182 $text =~ s/"/&quot;/g;
2657 4182 $text =~ s/'/&#39;/g;
2658 4182 return $text;
2659 }
2660  
2661 # Read one JSON value, as report() needs to read a trace. JSON::PP, which could
2662 # do it, is core only from perl 5.14. The text is UTF-8 bytes, as _json writes
2663 # them; true and false are read as 1 and 0, null as undef.
2664 #
2665 # Until 0.192 it took more than JSON: bytes that were not UTF-8, raw control
2666 # characters in a string, an unpaired UTF-16 surrogate, and whitespace beyond
2667 # JSON's four; and it nested without limit, so a line of "[[[[..." recursed as
2668 # deep as it was long. Each is now refused, nesting past $JSON_MAX_DEPTH -- 512,
2669 # JSON::PP's own default max_depth (JSON::PP 4.16, "max_depth") -- among them.
2670 # A trace line is at most 3 deep: the record, a hash or array in it, and the
2671 # values of that. There is no limit on a line's length, as JSON::PP has none by
2672 # default: a trace holds each task's whole "note".
2673 447 my $JSON_MAX_DEPTH = 512;
2674 494 ▶sub _json_decode {
Subroutine _json_decode: called CC=5 SCAR=16.2
2675 494 my $text = shift;
2676 494 ▶ utf8::decode($text) or die "it is not UTF-8\n"; # bytes of UTF-8 in, characters out
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($text) or die "it is not UTF-8\n" 484 10 494
2677 484 my $value = _json_value(\$text, 0);
2678 438 $text =~ /\G[ \t\n\r]*/gc;
2679 438 ▶ die 'unexpected text after the JSON value, at character ' . (pos($text) // 0) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if (pos $text // 0) != length $text 2 436 438
Condition50%2/4
pos $text // 0
l!l
4380
pos $text // 0
l!l
20
MC/DC0%0/1
pos $text // 0
pos $text
MC/DC0%0/1
pos $text // 0
pos $text
Truth table50%1/2
A
A= pos $text
Aresult
11
00
Truth table50%1/2
A
A= pos $text
Aresult
11
00
2680 if (pos($text) // 0) != length $text;
2681 436 return $value;
2682 }
2683 447 my %JSON_ESCAPE = ('"' => '"', '\\' => '\\', '/' => '/', b => "\b", f => "\f", n => "\n", r => "\r", t => "\t");
2684 8260 ▶sub _json_value {
Subroutine _json_value: called CC=23 SCAR=31.5
2685 8260 my ($t, $depth) = @_;
2686 # "Deep recursion" warns at 100 levels, and is fatal here; $JSON_MAX_DEPTH
2687 # is the limit, as JSON::PP turns the warning off for its own
2688 447 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
2689 8260 $$t =~ /\G[ \t\n\r]*/gc;
2690 8260 ▶ if ($$t =~ /\G([\{\[])/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$t =~ /\G([\{\[])/cg) 6094 2166 8260
2691 6094 ▶ die "the JSON nests deeper than $JSON_MAX_DEPTH, at character " . (pos($$t) // 0) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if $depth >= $JSON_MAX_DEPTH 10 6084 6094
Condition50%1/2
pos $$t // 0
l!l
100
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table50%1/2
A
A= pos $$t
Aresult
11
00
2692 if $depth >= $JSON_MAX_DEPTH;
2693 6084 ▶ if ($1 eq '{') {
Branch: 1 branch
BranchTrueFalseTotal
if ($1 eq "{") 524 5560 6084
2694 524 my %hash;
2695 524 $$t =~ /\G[ \t\n\r]*/gc;
2696 524 ▶ return \%hash if $$t =~ /\G\}/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\G\}/cg 26 498 524
2697 498 while (1) {
2698 2308 ▶ $$t =~ /\G[ \t\n\r]*"/gc or die 'expected a string for a key, at character ' . (pos($$t) // 0) . "\n";
Branch: 1 branch
BranchTrueFalseTotal
$$t =~ /\G[ \t\n\r]*"/cg or die 'expected a string for a key, at character ' . (pos $$t // 0) . "\n" 2306 2 2308
Condition50%1/2
pos $$t // 0
l!l
20
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table50%1/2
A
A= pos $$t
Aresult
11
00
2699 2306 my $key = _json_string_body($t);
2700 2306 ▶ $$t =~ /\G[ \t\n\r]*:/gc or die 'expected ":" after a key, at character ' . (pos($$t) // 0) . "\n";
Branch: 1 branch
BranchTrueFalseTotal
$$t =~ /\G[ \t\n\r]*:/cg or die 'expected ":" after a key, at character ' . (pos $$t // 0) . "\n" 2304 2 2306
Condition50%1/2
pos $$t // 0
l!l
20
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table50%1/2
A
A= pos $$t
Aresult
11
00
2701 2304 $hash{$key} = _json_value($t, $depth + 1);
2702 2274 $$t =~ /\G[ \t\n\r]*/gc;
2703 2274 ▶ next if $$t =~ /\G,/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\G,/cg 1810 464 2274
2704 464 ▶ return \%hash if $$t =~ /\G\}/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\G\}/cg 462 2 464
2705 2 ▶ die 'expected "," or "}" in an object, at character ' . (pos($$t) // 0) . "\n";
Condition50%1/2
pos $$t // 0
l!l
20
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table50%1/2
A
A= pos $$t
Aresult
11
00
2706 }
2707 }
2708 5560 my @array;
2709 5560 $$t =~ /\G[ \t\n\r]*/gc;
2710 5560 ▶ return \@array if $$t =~ /\G\]/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\G\]/cg 134 5426 5560
2711 5426 while (1) {
2712 5472 push @array, _json_value($t, $depth + 1);
2713 362 $$t =~ /\G[ \t\n\r]*/gc;
2714 362 ▶ next if $$t =~ /\G,/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\G,/cg 46 316 362
2715 316 ▶ return \@array if $$t =~ /\G\]/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\G\]/cg 314 2 316
2716 2 ▶ die 'expected "," or "]" in an array, at character ' . (pos($$t) // 0) . "\n";
Condition50%1/2
pos $$t // 0
l!l
20
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table50%1/2
A
A= pos $$t
Aresult
11
00
2717 }
2718 }
2719 2166 ▶ return _json_string_body($t) if $$t =~ /\G"/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\G"/cg 1710 456 2166
2720 456 ▶ return $1 + 0 if $$t =~ /\G(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?)/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\G(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?)/cg 438 18 456
2721 18 ▶ return 1 if $$t =~ /\Gtrue/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\Gtrue/cg 2 16 18
2722 16 ▶ return 0 if $$t =~ /\Gfalse/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\Gfalse/cg 2 14 16
2723 14 ▶ return undef if $$t =~ /\Gnull/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $$t =~ /\Gnull/cg 10 4 14
2724 4 ▶ die 'expected a JSON value, at character ' . (pos($$t) // 0) . "\n";
Condition50%1/2
pos $$t // 0
l!l
40
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table50%1/2
A
A= pos $$t
Aresult
11
00
2725 }
2726 # The rest of a string, its opening quote already read.
2727 4016 ▶sub _json_string_body {
Subroutine _json_string_body: called CC=15 SCAR=28.6
2728 4016 my $t = shift;
2729 4016 my $string = '';
2730 4016 while (1) {
2731 7948 ▶ if ($$t =~ /\G([^"\\\x00-\x1f]+)/gc) {
Branch: 5 branches
BranchTrueFalseTotal
if ($$t =~ /\G([^"\\\x00-\x1f]+)/cg) { } 3870 4078 7948
elsif ($$t =~ /\G"/cg) { } 3992 86 4078
elsif ($$t =~ m[\G\\(["\\/bfnrt])]cg) { } 48 38 86
elsif ($$t =~ /\G\\u([0-9a-fA-F]{4})/cg) { } 24 14 38
elsif ($$t =~ /\G(?=[\x00-\x1f])/cg) { } 10 4 14
2732 3870 $string .= $1;
2733 } elsif ($$t =~ /\G"/gc) {
2734 3992 return $string;
2735 } elsif ($$t =~ /\G\\(["\\\/bfnrt])/gc) {
2736 48 $string .= $JSON_ESCAPE{$1};
2737 } elsif ($$t =~ /\G\\u([0-9a-fA-F]{4})/gc) {
2738 24 my $code = hex $1;
2739 # a character beyond U+FFFF is written as a UTF-16 surrogate pair,
2740 # and half of one is not a character
2741 24 ▶ if (($code >= 0xD800) && ($code <= 0xDBFF)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($code >= 55296 and $code <= 56319) { } 12 12 24
elsif ($code >= 56320 and $code <= 57343) { } 0 24 24
Condition66%2/3
$code >= 55296 and $code <= 56319
!ll&&!rl&&r
12012
MC/DC50%1/2
$code >= 55296 and $code <= 56319
$code >= 55296 $code <= 56319
Truth table66%2/3
A and B
A= $code >= 55296B= $code <= 56319
ABresult
0X0
100
111
2742 12 ▶ $$t =~ /\G\\u([dD][c-fC-F][0-9a-fA-F]{2})/gc
Branch: 1 branch
BranchTrueFalseTotal
$$t =~ /\G\\u([dD][c-fC-F][0-9a-fA-F]{2})/cg or die 'an unpaired UTF-16 surrogate, at character ' . (pos $$t // 0) . "\n" 2 10 12
Condition50%1/2
pos $$t // 0
l!l
100
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table50%1/2
A
A= pos $$t
Aresult
11
00
2743 or die 'an unpaired UTF-16 surrogate, at character ' . (pos($$t) // 0) . "\n";
2744 2 $code = 0x10000 + (($code - 0xD800) << 10) + (hex($1) - 0xDC00);
2745 ▶ } elsif (($code >= 0xDC00) && ($code <= 0xDFFF)) {
Condition33%1/3
$code >= 56320 and $code <= 57343
!ll&&!rl&&r
1200
MC/DC0%0/2
$code >= 56320 and $code <= 57343
$code >= 56320 $code <= 57343
Truth table33%1/3
A and B
A= $code >= 56320B= $code <= 57343
ABresult
0X0
100
111
2746 0 ▶ die 'an unpaired UTF-16 surrogate, at character ' . (pos($$t) // 0) . "\n";
Condition0%0/2
pos $$t // 0
l!l
00
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table0%0/2
A
A= pos $$t
Aresult
11
00
2747 }
2748 14 $string .= chr $code;
2749 } elsif ($$t =~ /\G(?=[\x00-\x1f])/gc) {
2750 10 ▶ die 'a raw control character in a string, at character ' . (pos($$t) // 0) . "\n";
Condition50%1/2
pos $$t // 0
l!l
100
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table50%1/2
A
A= pos $$t
Aresult
11
00
2751 } else {
2752 4 ▶ die 'a string is not closed, or has a bad escape, at character ' . (pos($$t) // 0) . "\n";
Condition50%1/2
pos $$t // 0
l!l
40
MC/DC0%0/1
pos $$t // 0
pos $$t
Truth table50%1/2
A
A= pos $$t
Aresult
11
00
2753 }
2754 }
2755 }
2756  
2757 # the end of this file's code: see $CALLER_PERLDB_FLAGS at the top
2758 447 ▶BEGIN { $^P = $CALLER_PERLDB_FLAGS }
Subroutine BEGIN: called CC=1 SCAR=0.0
2759 447 1;
2760  
2761 =encoding utf8
2762  
2763 =head1 NAME
2764  
2765 SimpleFlow - easy, simple workflow manager (and logger); for keeping track of and debugging large and complex shell command workflows
2766  
2767 =head1 VERSION
2768  
2769 version 0.1961
2770  
2771 =head1 DESCRIPTION
2772  
2773 A tiny workflow manager and logger for Perl, like SnakeMake or NextFlow, but in pure Perl and aimed at making long, error-prone shell pipelines easy to B<debug> and B<reproduce>.
2774  
2775 Every step is a single C<task()> call. SimpleFlow checks the inputs before a
2776 command runs and the outputs after, times the command, captures its C<stdout>,
2777 C<stderr>, exit code and signal, optionally logs a full structured record, and
2778 skips work that has already been done. It can also bound a step with a
2779 L<timeout|/"Timeouts">, L<retry|/"Retries"> it, rebuild
2780 L<out-of-date outputs|/"Out-of-date outputs">, run it in its own
2781 L<directory and environment|/"Environment and directory">, make its outputs
2782 L<read-only|/"Protected outputs">, keep a L<trace|/"Tracing"> of the whole run,
2783 L<lock|/"Locking"> a step against a second copy of the pipeline, run it in a
2784 L<container, a conda environment or on a SLURM cluster|/"Containers, conda and clusters">,
2785 and L<run independent steps at once|/"Running steps in parallel">. A trace
2786 becomes an L<HTML report|/"Reports"> and a L<flow diagram|/"Flow diagrams">.
2787  
2788 Two subroutines are exported by default: L</"task"> and L</"say2">.
2789 Two more are exported on request:
2790 L<parallel|/"Running steps in parallel"> and L<report|/"Reports">.
2791  
2792 use SimpleFlow qw(task say2 parallel report);
2793  
2794 =head1 Install
2795  
2796 With a CPAN client:
2797  
2798 cpanm SimpleFlow
2799  
2800 Or from a release tarball, unpacked:
2801  
2802 perl Makefile.PL
2803 make
2804 make test
2805 make install
2806  
2807 A git checkout has no C<Makefile.PL>: it is written by
2808 L<Dist::Zilla>, so run C<dzil build> there
2809 first and install from the tarball it makes, or run the tests in place with
2810 C<prove -Ilib t/>.
2811  
2812 =head1 Synopsis
2813  
2814 The simplest useful case: run a command and confirm it produced its output:
2815  
2816 use SimpleFlow qw(task say2);
2817  
2818 my $t = task(
2819 cmd => 'echo hello > hello.txt',
2820 'output_file' => 'hello.txt',
2821 );
2822  
2823 C<task> returns a hash reference describing exactly what happened, and prints
2824 it (here from a script called C<example.pl>, run in C</home/you/project>):
2825  
2826 {
2827 attempts 1,
2828 cmd "echo hello > hello.txt",
2829 cmd.changed 0,
2830 conda_env "",
2831 container "",
2832 container_args [],
2833 container_engine "",
2834 cpu.system 0,
2835 cpu.user 0,
2836 die 1,
2837 dir "/home/you/project",
2838 done "now",
2839 dry_run 0,
2840 duration 0.00192999839782715,
2841 env {},
2842 env_secret [],
2843 executor "local",
2844 executor_args [],
2845 exit 0,
2846 failed.outputs [],
2847 input_dirs [],
2848 lock 0,
2849 mem "",
2850 note "",
2851 out.of.date 0,
2852 output_dirs [],
2853 output_file.size {
2854 hello.txt 6
2855 },
2856 output_files [
2857 [0] "hello.txt"
2858 ],
2859 overwrite 0,
2860 protect 0,
2861 quiet 0,
2862 retries 0,
2863 retry_delay 0,
2864 signal 0,
2865 source.file "example.pl",
2866 source.line 3,
2867 stale 0,
2868 stale_cmd 0,
2869 start.time 1790446630.13174,
2870 stderr "",
2871 stderr_file "",
2872 stdin "devnull",
2873 stdout "",
2874 stdout_file "",
2875 threads 0,
2876 timed.out 0,
2877 timeout 0,
2878 walltime "",
2879 will.do "done",
2880 wrapped.cmd "",
2881 wrapper []
2882 }
2883  
2884 Run it a second time and C<hello.txt> is already there, so the step is skipped:
2885 C<done> is C<"before"> and C<will.do> is C<"no">.
2886  
2887 > B<Portability note.> SimpleFlow runs whatever shell command you give it via
2888 > C<system()>, so the I<commands themselves> are your responsibility to keep
2889 > cross-platform (e.g. C<which ls> is Unix-only). SimpleFlow's own behaviour —
2890 > exit/signal decoding and coloured output — is cross-platform; see the
2891 > C<Changes> file for what was done to make it so.
2892  
2893 =head1 C<task>
2894  
2895 my $result = task(%args); # or task(\%args)
2896  
2897 Runs one command with checking, timing, capture and logging. Takes either a
2898 flat key/value list or a single hash reference; the only required key is C<cmd>.
2899  
2900 =head2 Arguments
2901  
2902  
2903  
2904 =begin html
2905  
2906 <table>
2907 <thead>
2908 <tr>
2909 <th>Key</th>
2910 <th>Type</th>
2911 <th>Default</th>
2912 <th>Description</th>
2913 </tr>
2914 </thead>
2915 <tbody>
2916 <tr>
2917 <td><code>cmd</code></td>
2918 <td>scalar or array</td>
2919 <td><code>undef</code></td>
2920 <td><b>Required.</b> The command to run. A string is handed to the shell; an array ref is run without a shell.</td>
2921 </tr>
2922 <tr>
2923 <td><code>conda_env</code></td>
2924 <td>name or path</td>
2925 <td><code>undef</code></td>
2926 <td>Run the command in this conda environment. See Containers, conda and clusters.</td>
2927 </tr>
2928 <tr>
2929 <td><code>container</code></td>
2930 <td>image</td>
2931 <td><code>undef</code></td>
2932 <td>Run the command in a container made from this image.</td>
2933 </tr>
2934 <tr>
2935 <td><code>container_args</code></td>
2936 <td>array ref</td>
2937 <td><code>[]</code></td>
2938 <td>More arguments for the container engine, before the image.</td>
2939 </tr>
2940 <tr>
2941 <td><code>container_engine</code></td>
2942 <td>name</td>
2943 <td><code>'docker'</code></td>
2944 <td><code>'docker'</code>, <code>'podman'</code>, <code>'singularity'</code> or <code>'apptainer'</code>.</td>
2945 </tr>
2946 <tr>
2947 <td><code>die</code></td>
2948 <td>bool (<code>0</code>/<code>1</code>)</td>
2949 <td><code>1</code></td>
2950 <td>Die if the command fails (non-zero exit, a kill by signal, a timeout, or a missing output file). Set to <code>0</code> to warn and continue instead.</td>
2951 </tr>
2952 <tr>
2953 <td><code>dir</code></td>
2954 <td>directory</td>
2955 <td><code>undef</code></td>
2956 <td>Run the step in this directory; every file it declares is relative to it. See Environment and directory.</td>
2957 </tr>
2958 <tr>
2959 <td><code>dry_run</code></td>
2960 <td>bool</td>
2961 <td><code>0</code></td>
2962 <td>Print the command (and log it) but do not execute it.</td>
2963 </tr>
2964 <tr>
2965 <td><code>env</code></td>
2966 <td>hash ref</td>
2967 <td><code>{}</code></td>
2968 <td>Environment variables for the command only; a value of <code>undef</code> removes one. See Environment and directory.</td>
2969 </tr>
2970 <tr>
2971 <td><code>env_secret</code></td>
2972 <td>array ref</td>
2973 <td><code>[]</code></td>
2974 <td>Names in <code>env</code> whose values are never printed, logged or traced. See Secrets.</td>
2975 </tr>
2976 <tr>
2977 <td><code>executor</code></td>
2978 <td><code>'local'</code>/<code>'slurm'</code></td>
2979 <td><code>'local'</code></td>
2980 <td>Where the command runs: here, or as a SLURM job step through <code>srun</code>.</td>
2981 </tr>
2982 <tr>
2983 <td><code>executor_args</code></td>
2984 <td>array ref</td>
2985 <td><code>[]</code></td>
2986 <td>More arguments for the executor (<code>srun</code>).</td>
2987 </tr>
2988 <tr>
2989 <td><code>input_dirs</code></td>
2990 <td>scalar or array</td>
2991 <td><code>undef</code></td>
2992 <td>Directories that must exist before running, as <code>input_files</code> must.</td>
2993 </tr>
2994 <tr>
2995 <td><code>input_dir</code></td>
2996 <td>scalar</td>
2997 <td><code>undef</code></td>
2998 <td>Convenience form of <code>input_dirs</code> for a <b>single</b> directory.</td>
2999 </tr>
3000 <tr>
3001 <td><code>input_files</code></td>
3002 <td>scalar or array</td>
3003 <td><code>undef</code></td>
3004 <td>File(s) that must exist and be readable <b>before</b> running; otherwise <code>task</code> dies (except in a dry run, which lists them instead).</td>
3005 </tr>
3006 <tr>
3007 <td><code>input_file</code></td>
3008 <td>scalar</td>
3009 <td><code>undef</code></td>
3010 <td>Convenience form of <code>input_files</code> for a <b>single</b> file. Must be a plain filename (not a reference). Cannot be combined with <code>input_files</code>.</td>
3011 </tr>
3012 <tr>
3013 <td><code>on_failure</code></td>
3014 <td>code ref</td>
3015 <td><code>undef</code></td>
3016 <td>Called with the record when the command ran and failed, before <code>task</code> dies. See Hooks.</td>
3017 </tr>
3018 <tr>
3019 <td><code>on_success</code></td>
3020 <td>code ref</td>
3021 <td><code>undef</code></td>
3022 <td>Called with the record when the command ran and succeeded.</td>
3023 </tr>
3024 <tr>
3025 <td><code>output_dirs</code></td>
3026 <td>scalar or array</td>
3027 <td><code>undef</code></td>
3028 <td>Directories the step makes, checked like <code>output_files</code>. See Directory outputs.</td>
3029 </tr>
3030 <tr>
3031 <td><code>output_dir</code></td>
3032 <td>scalar</td>
3033 <td><code>undef</code></td>
3034 <td>Convenience form of <code>output_dirs</code> for a <b>single</b> directory. Cannot be combined with <code>output_dirs</code>.</td>
3035 </tr>
3036 <tr>
3037 <td><code>output_files</code></td>
3038 <td>scalar or array</td>
3039 <td><code>undef</code></td>
3040 <td>File(s) expected to exist <b>after</b> running; used both for the missing-output check and for skip detection.</td>
3041 </tr>
3042 <tr>
3043 <td><code>output_file</code></td>
3044 <td>scalar</td>
3045 <td><code>undef</code></td>
3046 <td>Convenience form of <code>output_files</code> for a <b>single</b> file. Must be a plain filename (not a reference). Cannot be combined with <code>output_files</code>.</td>
3047 </tr>
3048 <tr>
3049 <td><code>lock</code></td>
3050 <td>bool</td>
3051 <td><code>0</code></td>
3052 <td>Hold a lock on the outputs while the step runs, so that a second copy of the pipeline waits for this one. See Locking.</td>
3053 </tr>
3054 <tr>
3055 <td><code>log_fh</code></td>
3056 <td>open filehandle</td>
3057 <td><code>undef</code></td>
3058 <td>If given, the full result record is also written here. Must be a real, open filehandle; <code>task</code> switches it to autoflush.</td>
3059 </tr>
3060 <tr>
3061 <td><code>mem</code></td>
3062 <td>e.g. <code>'16G'</code></td>
3063 <td><code>undef</code></td>
3064 <td>Memory to ask the executor for.</td>
3065 </tr>
3066 <tr>
3067 <td><code>note</code></td>
3068 <td>scalar</td>
3069 <td><code>''</code></td>
3070 <td>Free-text note copied into the result and the log.</td>
3071 </tr>
3072 <tr>
3073 <td><code>overwrite</code></td>
3074 <td>bool</td>
3075 <td><code>0</code></td>
3076 <td>If false and all <code>output_files</code> already exist, the command is skipped. Set true to always run.</td>
3077 </tr>
3078 <tr>
3079 <td><code>protect</code></td>
3080 <td>bool</td>
3081 <td><code>0</code></td>
3082 <td>Make the outputs read-only once the step succeeds. See Protected outputs.</td>
3083 </tr>
3084 <tr>
3085 <td><code>quiet</code></td>
3086 <td>bool</td>
3087 <td><code>0</code></td>
3088 <td>Suppress the record printed to the terminal. The log and error messages on <code>STDERR</code> are unaffected. See Quiet runs.</td>
3089 </tr>
3090 <tr>
3091 <td><code>retries</code></td>
3092 <td>whole number</td>
3093 <td><code>0</code></td>
3094 <td>Run a failed step again, up to this many more times. See Retries.</td>
3095 </tr>
3096 <tr>
3097 <td><code>retry_delay</code></td>
3098 <td>seconds</td>
3099 <td><code>0</code></td>
3100 <td>How long to wait before each retry; may be fractional.</td>
3101 </tr>
3102 <tr>
3103 <td><code>stale</code></td>
3104 <td>bool</td>
3105 <td><code>0</code></td>
3106 <td>Also re-run when an input file is newer than an output file. See Out-of-date outputs.</td>
3107 </tr>
3108 <tr>
3109 <td><code>stale_cmd</code></td>
3110 <td>bool</td>
3111 <td><code>0</code></td>
3112 <td>Also re-run when the command differs from the one that made the outputs. See Re-running a changed command.</td>
3113 </tr>
3114 <tr>
3115 <td><code>stderr_file</code></td>
3116 <td>path</td>
3117 <td><code>undef</code></td>
3118 <td>Write the command's standard error to this file instead of the record. See Output to files.</td>
3119 </tr>
3120 <tr>
3121 <td><code>stdin</code></td>
3122 <td><code>'devnull'</code>/<code>'inherit'</code></td>
3123 <td><code>'devnull'</code></td>
3124 <td>What the command sees on its standard input. The default is the null device; <code>'inherit'</code> hands it the caller's own. See Standard input.</td>
3125 </tr>
3126 <tr>
3127 <td><code>stdout_file</code></td>
3128 <td>path</td>
3129 <td><code>undef</code></td>
3130 <td>Write the command's standard output to this file instead of the record.</td>
3131 </tr>
3132 <tr>
3133 <td><code>threads</code></td>
3134 <td>whole number</td>
3135 <td><code>undef</code></td>
3136 <td>CPUs the command uses: given to it as <code>SIMPLEFLOW_THREADS</code>, and asked of the executor.</td>
3137 </tr>
3138 <tr>
3139 <td><code>timeout</code></td>
3140 <td>whole seconds</td>
3141 <td><code>0</code></td>
3142 <td>Kill the command if it runs longer than this. <code>0</code> means no limit. See Timeouts.</td>
3143 </tr>
3144 <tr>
3145 <td><code>trace_fh</code></td>
3146 <td>open filehandle</td>
3147 <td><code>undef</code></td>
3148 <td>Append one line of JSON per task to this filehandle. See Tracing.</td>
3149 </tr>
3150 <tr>
3151 <td><code>walltime</code></td>
3152 <td>e.g. <code>'2:00:00'</code></td>
3153 <td><code>undef</code></td>
3154 <td>Time to ask the executor for, as SLURM writes it.</td>
3155 </tr>
3156 <tr>
3157 <td><code>wrapper</code></td>
3158 <td>array ref</td>
3159 <td><code>undef</code></td>
3160 <td>A command to run the command inside, e.g. <code>['nice', '-n', '10']</code>.</td>
3161 </tr>
3162 </tbody>
3163 </table>
3164  
3165 =end html
3166  
3167 =begin :text
3168  
3169 =over
3170  
3171 =item C<cmd>
3172  
3173 Type: scalar or array; Default: C<undef>.
3174  
3175 B<Required.> The command to run. A string is handed to the shell; an array ref is run L<without a shell|/"Running without a shell">.
3176  
3177 =item C<conda_env>
3178  
3179 Type: name or path; Default: C<undef>.
3180  
3181 Run the command in this conda environment. See L</"Containers, conda and clusters">.
3182  
3183 =item C<container>
3184  
3185 Type: image; Default: C<undef>.
3186  
3187 Run the command in a container made from this image.
3188  
3189 =item C<container_args>
3190  
3191 Type: array ref; Default: C<[]>.
3192  
3193 More arguments for the container engine, before the image.
3194  
3195 =item C<container_engine>
3196  
3197 Type: name; Default: C<'docker'>.
3198  
3199 C<'docker'>, C<'podman'>, C<'singularity'> or C<'apptainer'>.
3200  
3201 =item C<die>
3202  
3203 Type: bool (C<0>/C<1>); Default: C<1>.
3204  
3205 Die if the command fails (non-zero exit, a kill by signal, a timeout, or a missing output file). Set to C<0> to warn and continue instead.
3206  
3207 =item C<dir>
3208  
3209 Type: directory; Default: C<undef>.
3210  
3211 Run the step in this directory; every file it declares is relative to it. See L</"Environment and directory">.
3212  
3213 =item C<dry_run>
3214  
3215 Type: bool; Default: C<0>.
3216  
3217 Print the command (and log it) but do not execute it.
3218  
3219 =item C<env>
3220  
3221 Type: hash ref; Default: C<{}>.
3222  
3223 Environment variables for the command only; a value of C<undef> removes one. See L</"Environment and directory">.
3224  
3225 =item C<env_secret>
3226  
3227 Type: array ref; Default: C<[]>.
3228  
3229 Names in C<env> whose values are never printed, logged or traced. See L</"Secrets">.
3230  
3231 =item C<executor>
3232  
3233 Type: C<'local'>/C<'slurm'>; Default: C<'local'>.
3234  
3235 Where the command runs: here, or as a SLURM job step through C<srun>.
3236  
3237 =item C<executor_args>
3238  
3239 Type: array ref; Default: C<[]>.
3240  
3241 More arguments for the executor (C<srun>).
3242  
3243 =item C<input_dirs>
3244  
3245 Type: scalar or array; Default: C<undef>.
3246  
3247 Directories that must exist before running, as C<input_files> must.
3248  
3249 =item C<input_dir>
3250  
3251 Type: scalar; Default: C<undef>.
3252  
3253 Convenience form of C<input_dirs> for a B<single> directory.
3254  
3255 =item C<input_files>
3256  
3257 Type: scalar or array; Default: C<undef>.
3258  
3259 File(s) that must exist and be readable B<before> running; otherwise C<task> dies (except in a L<dry run|/"Dry runs">, which lists them instead).
3260  
3261 =item C<input_file>
3262  
3263 Type: scalar; Default: C<undef>.
3264  
3265 Convenience form of C<input_files> for a B<single> file. Must be a plain filename (not a reference). Cannot be combined with C<input_files>.
3266  
3267 =item C<on_failure>
3268  
3269 Type: code ref; Default: C<undef>.
3270  
3271 Called with the record when the command ran and failed, before C<task> dies. See L</"Hooks">.
3272  
3273 =item C<on_success>
3274  
3275 Type: code ref; Default: C<undef>.
3276  
3277 Called with the record when the command ran and succeeded.
3278  
3279 =item C<output_dirs>
3280  
3281 Type: scalar or array; Default: C<undef>.
3282  
3283 Directories the step makes, checked like C<output_files>. See L</"Directory outputs">.
3284  
3285 =item C<output_dir>
3286  
3287 Type: scalar; Default: C<undef>.
3288  
3289 Convenience form of C<output_dirs> for a B<single> directory. Cannot be combined with C<output_dirs>.
3290  
3291 =item C<output_files>
3292  
3293 Type: scalar or array; Default: C<undef>.
3294  
3295 File(s) expected to exist B<after> running; used both for the missing-output check and for L<skip detection|/"Skipping completed work">.
3296  
3297 =item C<output_file>
3298  
3299 Type: scalar; Default: C<undef>.
3300  
3301 Convenience form of C<output_files> for a B<single> file. Must be a plain filename (not a reference). Cannot be combined with C<output_files>.
3302  
3303 =item C<lock>
3304  
3305 Type: bool; Default: C<0>.
3306  
3307 Hold a lock on the outputs while the step runs, so that a second copy of the pipeline waits for this one. See L</"Locking">.
3308  
3309 =item C<log_fh>
3310  
3311 Type: open filehandle; Default: C<undef>.
3312  
3313 If given, the full result record is also written here. Must be a real, open filehandle; C<task> switches it to autoflush.
3314  
3315 =item C<mem>
3316  
3317 Type: e.g. C<'16G'>; Default: C<undef>.
3318  
3319 Memory to ask the executor for.
3320  
3321 =item C<note>
3322  
3323 Type: scalar; Default: C<''>.
3324  
3325 Free-text note copied into the result and the log.
3326  
3327 =item C<overwrite>
3328  
3329 Type: bool; Default: C<0>.
3330  
3331 If false and all C<output_files> already exist, the command is skipped. Set true to always run.
3332  
3333 =item C<protect>
3334  
3335 Type: bool; Default: C<0>.
3336  
3337 Make the outputs read-only once the step succeeds. See L</"Protected outputs">.
3338  
3339 =item C<quiet>
3340  
3341 Type: bool; Default: C<0>.
3342  
3343 Suppress the record printed to the terminal. The log and error messages on C<STDERR> are unaffected. See L</"Quiet runs">.
3344  
3345 =item C<retries>
3346  
3347 Type: whole number; Default: C<0>.
3348  
3349 Run a failed step again, up to this many more times. See L</"Retries">.
3350  
3351 =item C<retry_delay>
3352  
3353 Type: seconds; Default: C<0>.
3354  
3355 How long to wait before each retry; may be fractional.
3356  
3357 =item C<stale>
3358  
3359 Type: bool; Default: C<0>.
3360  
3361 Also re-run when an input file is newer than an output file. See L</"Out-of-date outputs">.
3362  
3363 =item C<stale_cmd>
3364  
3365 Type: bool; Default: C<0>.
3366  
3367 Also re-run when the command differs from the one that made the outputs. See L</"Re-running a changed command">.
3368  
3369 =item C<stderr_file>
3370  
3371 Type: path; Default: C<undef>.
3372  
3373 Write the command's standard error to this file instead of the record. See L</"Output to files">.
3374  
3375 =item C<stdin>
3376  
3377 Type: C<'devnull'>/C<'inherit'>; Default: C<'devnull'>.
3378  
3379 What the command sees on its standard input. The default is the null device; C<'inherit'> hands it the caller's own. See L</"Standard input">.
3380  
3381 =item C<stdout_file>
3382  
3383 Type: path; Default: C<undef>.
3384  
3385 Write the command's standard output to this file instead of the record.
3386  
3387 =item C<threads>
3388  
3389 Type: whole number; Default: C<undef>.
3390  
3391 CPUs the command uses: given to it as C<SIMPLEFLOW_THREADS>, and asked of the executor.
3392  
3393 =item C<timeout>
3394  
3395 Type: whole seconds; Default: C<0>.
3396  
3397 Kill the command if it runs longer than this. C<0> means no limit. See L</"Timeouts">.
3398  
3399 =item C<trace_fh>
3400  
3401 Type: open filehandle; Default: C<undef>.
3402  
3403 Append one line of JSON per task to this filehandle. See L</"Tracing">.
3404  
3405 =item C<walltime>
3406  
3407 Type: e.g. C<'2:00:00'>; Default: C<undef>.
3408  
3409 Time to ask the executor for, as SLURM writes it.
3410  
3411 =item C<wrapper>
3412  
3413 Type: array ref; Default: C<undef>.
3414  
3415 A command to run the command inside, e.g. C<['nice', '-n', '10']>.
3416  
3417 =back
3418  
3419 =end :text
3420  
3421 =begin :man
3422  
3423 =over
3424  
3425 =item C<cmd>
3426  
3427 Type: scalar or array; Default: C<undef>.
3428  
3429 B<Required.> The command to run. A string is handed to the shell; an array ref is run L<without a shell|/"Running without a shell">.
3430  
3431 =item C<conda_env>
3432  
3433 Type: name or path; Default: C<undef>.
3434  
3435 Run the command in this conda environment. See L</"Containers, conda and clusters">.
3436  
3437 =item C<container>
3438  
3439 Type: image; Default: C<undef>.
3440  
3441 Run the command in a container made from this image.
3442  
3443 =item C<container_args>
3444  
3445 Type: array ref; Default: C<[]>.
3446  
3447 More arguments for the container engine, before the image.
3448  
3449 =item C<container_engine>
3450  
3451 Type: name; Default: C<'docker'>.
3452  
3453 C<'docker'>, C<'podman'>, C<'singularity'> or C<'apptainer'>.
3454  
3455 =item C<die>
3456  
3457 Type: bool (C<0>/C<1>); Default: C<1>.
3458  
3459 Die if the command fails (non-zero exit, a kill by signal, a timeout, or a missing output file). Set to C<0> to warn and continue instead.
3460  
3461 =item C<dir>
3462  
3463 Type: directory; Default: C<undef>.
3464  
3465 Run the step in this directory; every file it declares is relative to it. See L</"Environment and directory">.
3466  
3467 =item C<dry_run>
3468  
3469 Type: bool; Default: C<0>.
3470  
3471 Print the command (and log it) but do not execute it.
3472  
3473 =item C<env>
3474  
3475 Type: hash ref; Default: C<{}>.
3476  
3477 Environment variables for the command only; a value of C<undef> removes one. See L</"Environment and directory">.
3478  
3479 =item C<env_secret>
3480  
3481 Type: array ref; Default: C<[]>.
3482  
3483 Names in C<env> whose values are never printed, logged or traced. See L</"Secrets">.
3484  
3485 =item C<executor>
3486  
3487 Type: C<'local'>/C<'slurm'>; Default: C<'local'>.
3488  
3489 Where the command runs: here, or as a SLURM job step through C<srun>.
3490  
3491 =item C<executor_args>
3492  
3493 Type: array ref; Default: C<[]>.
3494  
3495 More arguments for the executor (C<srun>).
3496  
3497 =item C<input_dirs>
3498  
3499 Type: scalar or array; Default: C<undef>.
3500  
3501 Directories that must exist before running, as C<input_files> must.
3502  
3503 =item C<input_dir>
3504  
3505 Type: scalar; Default: C<undef>.
3506  
3507 Convenience form of C<input_dirs> for a B<single> directory.
3508  
3509 =item C<input_files>
3510  
3511 Type: scalar or array; Default: C<undef>.
3512  
3513 File(s) that must exist and be readable B<before> running; otherwise C<task> dies (except in a L<dry run|/"Dry runs">, which lists them instead).
3514  
3515 =item C<input_file>
3516  
3517 Type: scalar; Default: C<undef>.
3518  
3519 Convenience form of C<input_files> for a B<single> file. Must be a plain filename (not a reference). Cannot be combined with C<input_files>.
3520  
3521 =item C<on_failure>
3522  
3523 Type: code ref; Default: C<undef>.
3524  
3525 Called with the record when the command ran and failed, before C<task> dies. See L</"Hooks">.
3526  
3527 =item C<on_success>
3528  
3529 Type: code ref; Default: C<undef>.
3530  
3531 Called with the record when the command ran and succeeded.
3532  
3533 =item C<output_dirs>
3534  
3535 Type: scalar or array; Default: C<undef>.
3536  
3537 Directories the step makes, checked like C<output_files>. See L</"Directory outputs">.
3538  
3539 =item C<output_dir>
3540  
3541 Type: scalar; Default: C<undef>.
3542  
3543 Convenience form of C<output_dirs> for a B<single> directory. Cannot be combined with C<output_dirs>.
3544  
3545 =item C<output_files>
3546  
3547 Type: scalar or array; Default: C<undef>.
3548  
3549 File(s) expected to exist B<after> running; used both for the missing-output check and for L<skip detection|/"Skipping completed work">.
3550  
3551 =item C<output_file>
3552  
3553 Type: scalar; Default: C<undef>.
3554  
3555 Convenience form of C<output_files> for a B<single> file. Must be a plain filename (not a reference). Cannot be combined with C<output_files>.
3556  
3557 =item C<lock>
3558  
3559 Type: bool; Default: C<0>.
3560  
3561 Hold a lock on the outputs while the step runs, so that a second copy of the pipeline waits for this one. See L</"Locking">.
3562  
3563 =item C<log_fh>
3564  
3565 Type: open filehandle; Default: C<undef>.
3566  
3567 If given, the full result record is also written here. Must be a real, open filehandle; C<task> switches it to autoflush.
3568  
3569 =item C<mem>
3570  
3571 Type: e.g. C<'16G'>; Default: C<undef>.
3572  
3573 Memory to ask the executor for.
3574  
3575 =item C<note>
3576  
3577 Type: scalar; Default: C<''>.
3578  
3579 Free-text note copied into the result and the log.
3580  
3581 =item C<overwrite>
3582  
3583 Type: bool; Default: C<0>.
3584  
3585 If false and all C<output_files> already exist, the command is skipped. Set true to always run.
3586  
3587 =item C<protect>
3588  
3589 Type: bool; Default: C<0>.
3590  
3591 Make the outputs read-only once the step succeeds. See L</"Protected outputs">.
3592  
3593 =item C<quiet>
3594  
3595 Type: bool; Default: C<0>.
3596  
3597 Suppress the record printed to the terminal. The log and error messages on C<STDERR> are unaffected. See L</"Quiet runs">.
3598  
3599 =item C<retries>
3600  
3601 Type: whole number; Default: C<0>.
3602  
3603 Run a failed step again, up to this many more times. See L</"Retries">.
3604  
3605 =item C<retry_delay>
3606  
3607 Type: seconds; Default: C<0>.
3608  
3609 How long to wait before each retry; may be fractional.
3610  
3611 =item C<stale>
3612  
3613 Type: bool; Default: C<0>.
3614  
3615 Also re-run when an input file is newer than an output file. See L</"Out-of-date outputs">.
3616  
3617 =item C<stale_cmd>
3618  
3619 Type: bool; Default: C<0>.
3620  
3621 Also re-run when the command differs from the one that made the outputs. See L</"Re-running a changed command">.
3622  
3623 =item C<stderr_file>
3624  
3625 Type: path; Default: C<undef>.
3626  
3627 Write the command's standard error to this file instead of the record. See L</"Output to files">.
3628  
3629 =item C<stdin>
3630  
3631 Type: C<'devnull'>/C<'inherit'>; Default: C<'devnull'>.
3632  
3633 What the command sees on its standard input. The default is the null device; C<'inherit'> hands it the caller's own. See L</"Standard input">.
3634  
3635 =item C<stdout_file>
3636  
3637 Type: path; Default: C<undef>.
3638  
3639 Write the command's standard output to this file instead of the record.
3640  
3641 =item C<threads>
3642  
3643 Type: whole number; Default: C<undef>.
3644  
3645 CPUs the command uses: given to it as C<SIMPLEFLOW_THREADS>, and asked of the executor.
3646  
3647 =item C<timeout>
3648  
3649 Type: whole seconds; Default: C<0>.
3650  
3651 Kill the command if it runs longer than this. C<0> means no limit. See L</"Timeouts">.
3652  
3653 =item C<trace_fh>
3654  
3655 Type: open filehandle; Default: C<undef>.
3656  
3657 Append one line of JSON per task to this filehandle. See L</"Tracing">.
3658  
3659 =item C<walltime>
3660  
3661 Type: e.g. C<'2:00:00'>; Default: C<undef>.
3662  
3663 Time to ask the executor for, as SLURM writes it.
3664  
3665 =item C<wrapper>
3666  
3667 Type: array ref; Default: C<undef>.
3668  
3669 A command to run the command inside, e.g. C<['nice', '-n', '10']>.
3670  
3671 =back
3672  
3673 =end :man
3674  
3675  
3676  
3677 Any key but those naming a particular step can also be given once for the whole
3678 program; see L</"Defaults for a whole pipeline">.
3679  
3680 Passing an unrecognised key, an undefined or empty filename, a C<cmd> that is
3681 neither a string nor an array ref, or a non-filehandle C<log_fh> causes C<task>
3682 to die: these are usually mistakes worth catching early. Giving both
3683 C<output_file> and C<output_files> (or both C<input_file> and C<input_files>), or a
3684 reference where a single filename is expected, dies for the same reason.
3685  
3686 =head2 Return value
3687  
3688 C<task> always returns a hash reference. Every field below except the two
3689 C<input.*> ones is present on B<every> path, so a caller running under
3690 C<< use warnings FATAL =E<gt> 'all' >> can read the record after a skip or a dry run
3691 without an uninitialized-value warning turning fatal. On those paths the
3692 execution-only fields simply hold their empty values (C<exit> and C<signal> are
3693 C<0>, C<stdout> and C<stderr> are C<''>, C<duration> is C<0>).
3694  
3695  
3696  
3697 =begin html
3698  
3699 <table>
3700 <thead>
3701 <tr>
3702 <th>Field</th>
3703 <th>Meaning</th>
3704 </tr>
3705 </thead>
3706 <tbody>
3707 <tr>
3708 <td><code>cmd</code></td>
3709 <td>The command that was run. An array-ref <code>cmd</code> is recorded space-joined for readability; that is not a shell-quoted round trip, since it never went near a shell.</td>
3710 </tr>
3711 <tr>
3712 <td><code>dir</code></td>
3713 <td>Working directory at execution time: the absolute path of <code>dir</code>, if it was given.</td>
3714 </tr>
3715 <tr>
3716 <td><code>done</code></td>
3717 <td><code>"now"</code> (just ran), <code>"before"</code> (skipped, outputs already existed), or <code>"not yet"</code> (dry run).</td>
3718 </tr>
3719 <tr>
3720 <td><code>will.do</code></td>
3721 <td><code>"done"</code>, <code>"no"</code> (skipped), <code>"no: dry run"</code>, or <code>"FAILED"</code>. <code>"FAILED"</code> is set whenever the command exited non-zero, was killed by a signal, timed out, or left a declared output file missing — <b>whether or not <code>die</code> is set</b>.</td>
3722 </tr>
3723 <tr>
3724 <td><code>duration</code></td>
3725 <td>Wall-clock seconds the command took (<code>0</code> for skips/dry runs). With retries, the last attempt's.</td>
3726 </tr>
3727 <tr>
3728 <td><code>attempts</code></td>
3729 <td>How many times the command was run: <code>0</code> for a skip or a dry run, <code>1</code> without retries.</td>
3730 </tr>
3731 <tr>
3732 <td><code>start.time</code></td>
3733 <td>When the last attempt started, in epoch seconds with a fractional part; <code>0</code> if none did.</td>
3734 </tr>
3735 <tr>
3736 <td><code>cpu.user</code>, <code>cpu.system</code></td>
3737 <td>CPU seconds the command, and everything it waited for, spent in user and system mode. The clock counts in ticks of 1/100 s on Linux. Not known to be filled in on Windows, and <code>0</code> on GNU/Hurd unless its glibc was built to count a finished child's time.</td>
3738 </tr>
3739 <tr>
3740 <td><code>exit</code></td>
3741 <td>Exit code of the command, or <code>-1</code> if it could not be launched at all (<code>stderr</code> then says why).</td>
3742 </tr>
3743 <tr>
3744 <td><code>signal</code></td>
3745 <td>Signal number if the command process was killed by a signal, else <code>0</code>. A non-zero <code>signal</code> makes the step <code>"FAILED"</code>, even though <code>exit</code> is then <code>0</code>. Always <code>0</code> on Windows (no POSIX signals).</td>
3746 </tr>
3747 <tr>
3748 <td><code>timed.out</code></td>
3749 <td><code>1</code> if the command was killed for exceeding its <code>timeout</code>, else <code>0</code>.</td>
3750 </tr>
3751 <tr>
3752 <td><code>out.of.date</code></td>
3753 <td><code>1</code> if <code>stale</code> was set and an input was newer than an output, else <code>0</code>.</td>
3754 </tr>
3755 <tr>
3756 <td><code>stdout</code>, <code>stderr</code></td>
3757 <td>Captured output, with trailing whitespace stripped; <code>''</code> for a stream sent to <code>stdout_file</code> or <code>stderr_file</code>. When the command could not be launched at all (<code>exit</code> is <code>-1</code>), <code>stderr</code> says why, e.g. <code>cannot run "x": No such file or directory</code>.</td>
3758 </tr>
3759 <tr>
3760 <td><code>conda_env</code>, <code>container</code>, <code>container_args</code>, <code>container_engine</code>, <code>die</code>, <code>dry_run</code>, <code>env</code>, <code>env_secret</code>, <code>executor</code>, <code>executor_args</code>, <code>lock</code>, <code>mem</code>, <code>note</code>, <code>overwrite</code>, <code>protect</code>, <code>quiet</code>, <code>retries</code>, <code>retry_delay</code>, <code>stale</code>, <code>stale_cmd</code>, <code>stderr_file</code>, <code>stdin</code>, <code>stdout_file</code>, <code>threads</code>, <code>timeout</code>, <code>walltime</code>, <code>wrapper</code></td>
3761 <td>The (defaulted) argument values used. A string option not given is <code>''</code>, a list <code>[]</code>, <code>env</code> is <code>{}</code>, and <code>threads</code> is <code>0</code>. The values <code>env_secret</code> names are <code>(secret)</code> in <code>env</code>. The hooks are not recorded: they are code.</td>
3762 </tr>
3763 <tr>
3764 <td><code>output_files</code></td>
3765 <td>Array ref of the output files (a scalar argument, or an <code>output_file</code>, is normalised to a one-element array).</td>
3766 </tr>
3767 <tr>
3768 <td><code>output_dirs</code></td>
3769 <td>Array ref of the output directories, normalised as <code>output_files</code> is.</td>
3770 </tr>
3771 <tr>
3772 <td><code>input_dirs</code></td>
3773 <td>Array ref of the input directories, normalised the same way; <code>[]</code> if none.</td>
3774 </tr>
3775 <tr>
3776 <td><code>cmd.changed</code></td>
3777 <td><code>1</code> if <code>stale_cmd</code> was set and the command on record for the outputs was a different one, else <code>0</code>.</td>
3778 </tr>
3779 <tr>
3780 <td><code>wrapped.cmd</code></td>
3781 <td>The command as actually run, inside its executor, container, conda environment and wrapper, space-joined; <code>''</code> if it ran as it is.</td>
3782 </tr>
3783 <tr>
3784 <td><code>output_file.size</code></td>
3785 <td>Hash of <code>filename => size in bytes</code> for the outputs, as the command left them (measured before a failed step's outputs are moved aside).</td>
3786 </tr>
3787 <tr>
3788 <td><code>failed.outputs</code></td>
3789 <td>Array ref of the names a failed step's outputs were moved to, each the output's own name with <code>.failed</code> appended; <code>[]</code> on every other path.</td>
3790 </tr>
3791 <tr>
3792 <td><code>input_files</code></td>
3793 <td>Array ref of the input files, normalised the same way (present only if you passed <code>input_files</code> or <code>input_file</code>).</td>
3794 </tr>
3795 <tr>
3796 <td><code>input_file.size</code></td>
3797 <td>Hash of <code>filename => size in bytes</code> for the inputs (present only if you passed <code>input_files</code> or <code>input_file</code>). In a dry run, an input that does not exist yet has <code>undef</code>.</td>
3798 </tr>
3799 <tr>
3800 <td><code>source.file</code>, <code>source.line</code></td>
3801 <td>Where in <i>your</i> code the <code>task</code> was called: handy when debugging a long pipeline.</td>
3802 </tr>
3803 </tbody>
3804 </table>
3805  
3806 =end html
3807  
3808 =begin :text
3809  
3810 =over
3811  
3812 =item C<cmd>
3813  
3814 The command that was run. An array-ref C<cmd> is recorded space-joined for readability; that is not a shell-quoted round trip, since it never went near a shell.
3815  
3816 =item C<dir>
3817  
3818 Working directory at execution time: the absolute path of C<dir>, if it was given.
3819  
3820 =item C<done>
3821  
3822 C<"now"> (just ran), C<"before"> (skipped, outputs already existed), or C<"not yet"> (dry run).
3823  
3824 =item C<will.do>
3825  
3826 C<"done">, C<"no"> (skipped), C<"no: dry run">, or C<"FAILED">. C<"FAILED"> is set whenever the command exited non-zero, was killed by a signal, timed out, or left a declared output file missing — B<whether or not C<die> is set>.
3827  
3828 =item C<duration>
3829  
3830 Wall-clock seconds the command took (C<0> for skips/dry runs). With L<retries|/"Retries">, the last attempt's.
3831  
3832 =item C<attempts>
3833  
3834 How many times the command was run: C<0> for a skip or a dry run, C<1> without retries.
3835  
3836 =item C<start.time>
3837  
3838 When the last attempt started, in epoch seconds with a fractional part; C<0> if none did.
3839  
3840 =item C<cpu.user>, C<cpu.system>
3841  
3842 CPU seconds the command, and everything it waited for, spent in user and system mode. The clock counts in ticks of 1/100 s on Linux. Not known to be filled in on Windows, and C<0> on GNU/Hurd unless its glibc was built to count a finished child's time.
3843  
3844 =item C<exit>
3845  
3846 Exit code of the command, or C<-1> if it could not be launched at all (C<stderr> then says why).
3847  
3848 =item C<signal>
3849  
3850 Signal number if the command process was killed by a signal, else C<0>. A non-zero C<signal> makes the step C<"FAILED">, even though C<exit> is then C<0>. Always C<0> on Windows (no POSIX signals).
3851  
3852 =item C<timed.out>
3853  
3854 C<1> if the command was killed for exceeding its C<timeout>, else C<0>.
3855  
3856 =item C<out.of.date>
3857  
3858 C<1> if C<stale> was set and an input was newer than an output, else C<0>.
3859  
3860 =item C<stdout>, C<stderr>
3861  
3862 Captured output, with trailing whitespace stripped; C<''> for a stream sent to C<stdout_file> or C<stderr_file>. When the command could not be launched at all (C<exit> is C<-1>), C<stderr> says why, e.g. C<cannot run "x": No such file or directory>.
3863  
3864 =item C<conda_env>, C<container>, C<container_args>, C<container_engine>, C<die>, C<dry_run>, C<env>, C<env_secret>, C<executor>, C<executor_args>, C<lock>, C<mem>, C<note>, C<overwrite>, C<protect>, C<quiet>, C<retries>, C<retry_delay>, C<stale>, C<stale_cmd>, C<stderr_file>, C<stdin>, C<stdout_file>, C<threads>, C<timeout>, C<walltime>, C<wrapper>
3865  
3866 The (defaulted) argument values used. A string option not given is C<''>, a list C<[]>, C<env> is C<{}>, and C<threads> is C<0>. The values C<env_secret> names are C<(secret)> in C<env>. The hooks are not recorded: they are code.
3867  
3868 =item C<output_files>
3869  
3870 Array ref of the output files (a scalar argument, or an C<output_file>, is normalised to a one-element array).
3871  
3872 =item C<output_dirs>
3873  
3874 Array ref of the output directories, normalised as C<output_files> is.
3875  
3876 =item C<input_dirs>
3877  
3878 Array ref of the input directories, normalised the same way; C<[]> if none.
3879  
3880 =item C<cmd.changed>
3881  
3882 C<1> if C<stale_cmd> was set and the command on record for the outputs was a different one, else C<0>.
3883  
3884 =item C<wrapped.cmd>
3885  
3886 The command as actually run, inside its executor, container, conda environment and wrapper, space-joined; C<''> if it ran as it is.
3887  
3888 =item C<output_file.size>
3889  
3890 Hash of C<filename =E<gt> size in bytes> for the outputs, as the command left them (measured before a failed step's outputs are moved aside).
3891  
3892 =item C<failed.outputs>
3893  
3894 Array ref of the names a failed step's outputs were L<moved to|/"Failure behaviour">, each the output's own name with C<.failed> appended; C<[]> on every other path.
3895  
3896 =item C<input_files>
3897  
3898 Array ref of the input files, normalised the same way (present only if you passed C<input_files> or C<input_file>).
3899  
3900 =item C<input_file.size>
3901  
3902 Hash of C<filename =E<gt> size in bytes> for the inputs (present only if you passed C<input_files> or C<input_file>). In a dry run, an input that does not exist yet has C<undef>.
3903  
3904 =item C<source.file>, C<source.line>
3905  
3906 Where in I<your> code the C<task> was called: handy when debugging a long pipeline.
3907  
3908 =back
3909  
3910 =end :text
3911  
3912 =begin :man
3913  
3914 =over
3915  
3916 =item C<cmd>
3917  
3918 The command that was run. An array-ref C<cmd> is recorded space-joined for readability; that is not a shell-quoted round trip, since it never went near a shell.
3919  
3920 =item C<dir>
3921  
3922 Working directory at execution time: the absolute path of C<dir>, if it was given.
3923  
3924 =item C<done>
3925  
3926 C<"now"> (just ran), C<"before"> (skipped, outputs already existed), or C<"not yet"> (dry run).
3927  
3928 =item C<will.do>
3929  
3930 C<"done">, C<"no"> (skipped), C<"no: dry run">, or C<"FAILED">. C<"FAILED"> is set whenever the command exited non-zero, was killed by a signal, timed out, or left a declared output file missing — B<whether or not C<die> is set>.
3931  
3932 =item C<duration>
3933  
3934 Wall-clock seconds the command took (C<0> for skips/dry runs). With L<retries|/"Retries">, the last attempt's.
3935  
3936 =item C<attempts>
3937  
3938 How many times the command was run: C<0> for a skip or a dry run, C<1> without retries.
3939  
3940 =item C<start.time>
3941  
3942 When the last attempt started, in epoch seconds with a fractional part; C<0> if none did.
3943  
3944 =item C<cpu.user>, C<cpu.system>
3945  
3946 CPU seconds the command, and everything it waited for, spent in user and system mode. The clock counts in ticks of 1/100 s on Linux. Not known to be filled in on Windows, and C<0> on GNU/Hurd unless its glibc was built to count a finished child's time.
3947  
3948 =item C<exit>
3949  
3950 Exit code of the command, or C<-1> if it could not be launched at all (C<stderr> then says why).
3951  
3952 =item C<signal>
3953  
3954 Signal number if the command process was killed by a signal, else C<0>. A non-zero C<signal> makes the step C<"FAILED">, even though C<exit> is then C<0>. Always C<0> on Windows (no POSIX signals).
3955  
3956 =item C<timed.out>
3957  
3958 C<1> if the command was killed for exceeding its C<timeout>, else C<0>.
3959  
3960 =item C<out.of.date>
3961  
3962 C<1> if C<stale> was set and an input was newer than an output, else C<0>.
3963  
3964 =item C<stdout>, C<stderr>
3965  
3966 Captured output, with trailing whitespace stripped; C<''> for a stream sent to C<stdout_file> or C<stderr_file>. When the command could not be launched at all (C<exit> is C<-1>), C<stderr> says why, e.g. C<cannot run "x": No such file or directory>.
3967  
3968 =item C<conda_env>, C<container>, C<container_args>, C<container_engine>, C<die>, C<dry_run>, C<env>, C<env_secret>, C<executor>, C<executor_args>, C<lock>, C<mem>, C<note>, C<overwrite>, C<protect>, C<quiet>, C<retries>, C<retry_delay>, C<stale>, C<stale_cmd>, C<stderr_file>, C<stdin>, C<stdout_file>, C<threads>, C<timeout>, C<walltime>, C<wrapper>
3969  
3970 The (defaulted) argument values used. A string option not given is C<''>, a list C<[]>, C<env> is C<{}>, and C<threads> is C<0>. The values C<env_secret> names are C<(secret)> in C<env>. The hooks are not recorded: they are code.
3971  
3972 =item C<output_files>
3973  
3974 Array ref of the output files (a scalar argument, or an C<output_file>, is normalised to a one-element array).
3975  
3976 =item C<output_dirs>
3977  
3978 Array ref of the output directories, normalised as C<output_files> is.
3979  
3980 =item C<input_dirs>
3981  
3982 Array ref of the input directories, normalised the same way; C<[]> if none.
3983  
3984 =item C<cmd.changed>
3985  
3986 C<1> if C<stale_cmd> was set and the command on record for the outputs was a different one, else C<0>.
3987  
3988 =item C<wrapped.cmd>
3989  
3990 The command as actually run, inside its executor, container, conda environment and wrapper, space-joined; C<''> if it ran as it is.
3991  
3992 =item C<output_file.size>
3993  
3994 Hash of C<filename =E<gt> size in bytes> for the outputs, as the command left them (measured before a failed step's outputs are moved aside).
3995  
3996 =item C<failed.outputs>
3997  
3998 Array ref of the names a failed step's outputs were L<moved to|/"Failure behaviour">, each the output's own name with C<.failed> appended; C<[]> on every other path.
3999  
4000 =item C<input_files>
4001  
4002 Array ref of the input files, normalised the same way (present only if you passed C<input_files> or C<input_file>).
4003  
4004 =item C<input_file.size>
4005  
4006 Hash of C<filename =E<gt> size in bytes> for the inputs (present only if you passed C<input_files> or C<input_file>). In a dry run, an input that does not exist yet has C<undef>.
4007  
4008 =item C<source.file>, C<source.line>
4009  
4010 Where in I<your> code the C<task> was called: handy when debugging a long pipeline.
4011  
4012 =back
4013  
4014 =end :man
4015  
4016  
4017  
4018 =head2 Skipping completed work
4019  
4020 If C<overwrite> is false (the default) and every file in C<output_files> already
4021 exists, C<task> does B<not> re-run the command. This makes pipelines
4022 restartable: re-running the script picks up where it left off.
4023  
4024 open my $log, '>', 'logfile.txt';
4025 my $t = task(
4026 cmd => 'gmx grompp -f em.mdp -c box.gro -p topol.top -o em.tpr',
4027 'input_files' => ['em.mdp', 'box.gro', 'topol.top'],
4028 'output_files' => 'em.tpr',
4029 'log_fh' => $log,
4030 );
4031 close $log;
4032  
4033 On the first run C<done> is C<"now">; on a re-run (with C<em.tpr> present) C<done>
4034 is C<"before"> and C<will.do> is C<"no">. Pass C<< overwrite =E<gt> 1 >> to force it.
4035  
4036 An output file that exists but cannot be B<read> does not count as done: it is
4037 not a usable result, and treating it as one would skip the very step that could
4038 replace it. Nor does the output of a step that failed: that is moved aside to
4039 C<< E<lt>fileE<gt>.failed >> (see L</"Failure behaviour">), so a re-run runs
4040 the step again instead of taking a half-written file as its result.
4041  
4042 =head2 Out-of-date outputs
4043  
4044 Existence alone is a weak test. If an input file has been edited since the
4045 output was built, the output is stale even though it is present, and by
4046 default C<task> will still skip the step, exactly as earlier versions did.
4047  
4048 Pass C<< stale =E<gt> 1 >> to get the rule C<make> and C<snakemake> use: re-run whenever
4049 the newest C<input_files> mtime is later than the oldest C<output_files> mtime.
4050 The mtimes are compared to the sub-second, where the filesystem records that,
4051 so an input rewritten in the same second as its output still counts as newer.
4052  
4053 my $t = task(
4054 cmd => 'gmx grompp -f em.mdp -c box.gro -p topol.top -o em.tpr',
4055 'input_files' => ['em.mdp', 'box.gro', 'topol.top'],
4056 'output_files' => 'em.tpr',
4057 stale => 1,
4058 );
4059  
4060 Editing C<em.mdp> now rebuilds C<em.tpr>; leaving it alone still skips. The
4061 result's C<out.of.date> field says which of the two happened. This is off by
4062 default so that upgrading does not silently start re-running steps in pipelines
4063 written against 0.15 and earlier.
4064  
4065 =head2 Timeouts
4066  
4067 C<timeout> gives a step a wall-clock budget in whole seconds:
4068  
4069 my $t = task(
4070 cmd => 'a command that sometimes wedges',
4071 timeout => 600,
4072 die => 0,
4073 );
4074  
4075 The command is run in its own process group and, if the budget is exceeded, the
4076 B<whole group> is killed — a shell command is usually a pipeline, not a single
4077 process, and killing only the shell would leave its children running. The
4078 result then has C<< timed.out =E<gt> 1 >> and C<< will.do =E<gt> "FAILED" >>; with the default
4079 C<< die =E<gt> 1 >> the pipeline stops there instead.
4080  
4081 Because the command has a process group of its own, a Ctrl-C at the terminal
4082 reaches only your script, not the command. C<task> therefore catches C<INT>,
4083 C<TERM>, C<HUP> and C<QUIT> while a timed command runs, kills the command's group,
4084 writes the record, and then passes the signal on: to your own handler if you
4085 have one, and otherwise it ends the script as it would have without C<task> in
4086 the way. A signal your script ignores stays ignored.
4087  
4088 With C<< stdin =E<gt> 'inherit' >> and a terminal on standard input, the command is
4089 given the terminal's foreground for the duration, as a shell gives it to a job,
4090 so that it can read from the terminal; your script takes it back afterwards.
4091 A Ctrl-Z then suspends the command and your script together, as a shell
4092 suspends a job, with the timeout's clock stopped, and C<fg> carries on with
4093 both. The same holds without a C<timeout>.
4094  
4095 Without a C<timeout> the command has a process group of its own as well, so
4096 that a signal reaches the whole of it, not just the shell at its head. A
4097 C<TERM> or C<HUP> sent to your script, by a batch scheduler or C<kill>, is passed
4098 on to the command's group, which is waited for; then the record is written and
4099 the signal passed on to your script, as with a timeout. A Ctrl-C (C<INT>) or
4100 C<QUIT> is passed on to the group in the same way, but, as under C<system>, not
4101 to your script afterwards: the step fails, killed by the signal, and C<die>
4102 decides what happens next. A Ctrl-Z stops the command and your script together,
4103 and C<fg> or C<bg> carries on with both. A command that opens the terminal
4104 itself, as C<ssh> or C<sudo> do to ask for a password, is given its foreground
4105 while your script has it to give.
4106  
4107 If one of your own signal handlers dies while a command runs, the command's
4108 group is killed and waited for before the exception reaches your code.
4109 Before 0.192 the command was left running.
4110  
4111 An C<alarm> your script already had pending is kept: it is put back when the
4112 command finishes, less the time the command took, and if it fell due while the
4113 command ran it is delivered then.
4114  
4115 C<timeout> needs C<fork()> and POSIX process groups, so it is refused on
4116 C<MSWin32>. Leaving it at C<0> (the default) changes nothing anywhere.
4117  
4118 =head2 Retries
4119  
4120 A step that fails for a reason outside its control, such as a flaky network or
4121 a busy licence server, can be run again automatically:
4122  
4123 my $t = task(
4124 cmd => 'fetch-data --to data.csv',
4125 'output_file' => 'data.csv',
4126 retries => 3,
4127 'retry_delay' => 30,
4128 );
4129  
4130 A failed attempt, for any of the reasons in
4131 L</"Failure behaviour">, has its outputs moved aside and is
4132 reported on C<STDERR> and in the log (C<attempt 1 of 4, retrying in 30s>); then
4133 the command runs again. Only when the last attempt fails does the step fail,
4134 and C<die> apply. The record describes the last attempt, and C<attempts> says how
4135 many there were. An interrupt under a C<timeout> is never retried, since it is a
4136 request for the whole program to stop. This is Nextflow's C<errorStrategy
4137 'retry'> and Snakemake's C<--retries>.
4138  
4139 =head2 Environment and directory
4140  
4141 C<env> sets environment variables for the command alone, and C<dir> runs the step
4142 in another directory:
4143  
4144 my $t = task(
4145 cmd => 'make all',
4146 dir => 'build',
4147 env => { CFLAGS => '-O2', MAKEFLAGS => undef },
4148 'output_file' => 'a.out', # that is, build/a.out
4149 );
4150  
4151 A value of C<undef> in C<env> removes the variable for the command. Your script's
4152 own C<%ENV> is untouched: it is put back as soon as the command finishes.
4153  
4154 Under C<dir> the whole step happens in that directory, the input and output
4155 checks as well as the command, so every name it declares is relative to it, as
4156 the command itself sees it. Your script is back in its own directory when
4157 C<task> returns, however it returns, dying included. The record's C<dir> is the
4158 absolute path the step ran in.
4159  
4160 =head2 Secrets
4161  
4162 The record holds the C<env> a step was given, and the record is printed, written
4163 to the log and written to the trace. A credential passed in C<env> would be
4164 written out with it. C<env_secret> names the variables whose values must not be:
4165  
4166 my $t = task(
4167 cmd => 'fetch-data --to data.csv',
4168 env => { API_TOKEN => $token },
4169 'env_secret' => ['API_TOKEN'],
4170 );
4171  
4172 The command is given the real value; everywhere else, the record included, it
4173 is C<(secret)>, and so it is in the arguments printed with an error. A secret's
4174 value is not part of what L<stalecmd|/"Re-running a changed command">
4175 compares, so a new token does not re-run every step. C<env_secret> in
4176 L<%SimpleFlow::DEFAULTS|/"Defaults for a whole pipeline"> is combined with a
4177 step's own, as C<env> is.
4178  
4179 Nothing else is hidden: the command line, C<note> and every other C<env> value
4180 are written out in full. Pass a credential through C<env>, never on the command
4181 line.
4182  
4183 =head2 Output to files
4184  
4185 A command that prints a great deal is better written to a file than held in
4186 memory and printed in the record:
4187  
4188 my $t = task(
4189 cmd => 'aligner --verbose reads.fq',
4190 'stdout_file' => 'align.out',
4191 'stderr_file' => 'align.log',
4192 );
4193  
4194 The files are emptied when the step starts and receive the output of every
4195 attempt, in order; the record's C<stdout> and C<stderr> are then C<''>. That holds
4196 even when the file is also a declared output, or is inside one: a failed
4197 attempt that is to be retried leaves such an output where it is, and only a
4198 step that has failed for good moves it aside. Naming the
4199 same file for both puts the two streams in it interleaved, as a terminal would
4200 show them. A step that is skipped, or dry-run, leaves the files alone, so they
4201 still hold the output of the run that made the step's outputs. This is
4202 Snakemake's C<log:> directive.
4203  
4204 =head2 Directory outputs
4205  
4206 A step whose result is a directory declares it with C<output_dir> (or a list,
4207 C<output_dirs>), as Snakemake's C<directory()> does:
4208  
4209 my $t = task(
4210 cmd => 'split-by-sample input.bam samples',
4211 'input_file' => 'input.bam',
4212 'output_dir' => 'samples',
4213 );
4214  
4215 A declared directory counts as made if it exists, and the step is skipped when
4216 all its outputs, files and directories alike, exist already. A directory that
4217 exists but is empty is warned about, as an empty output file is. When the step
4218 fails, the directory is moved aside to C<samples.failed> like any other output.
4219 Under C<stale>, a directory is as new as the newest thing in it.
4220  
4221 A directory can be an input, too: C<input_dir> and C<input_dirs> must exist, and
4222 be readable, before the step runs, just as C<input_files> must, and under
4223 C<stale> an output is out of date if anything in an input directory is newer
4224 than it.
4225  
4226 =head2 Protected outputs
4227  
4228 C<< protect =E<gt> 1 >> makes a step's outputs read-only once it succeeds, and, for a
4229 directory output, everything in it, as Snakemake's C<protected()> does:
4230  
4231 my $t = task(
4232 cmd => 'expensive-simulation > result.dat',
4233 'output_file' => 'result.dat',
4234 protect => 1,
4235 );
4236  
4237 Re-running such a step over its outputs, with C<overwrite> or C<stale>, is then
4238 refused with a message naming them, instead of failing inside the command with
4239 an error that does not say why the file is read-only. Remove them, or make them
4240 writable, to run it again. Symbolic links are left alone. C<root> can write to a
4241 read-only file, so for C<root> this protects nothing, and nor, under Cygwin, for
4242 a Windows administrator, whose backup and restore privileges do the same.
4243  
4244 =head2 Tracing
4245  
4246 C<trace_fh> takes a filehandle and appends one line of JSON to it for every
4247 task, on every path (run, skipped, dry-run or failed), in the spirit of
4248 Nextflow's C<trace.txt>:
4249  
4250 open my $trace, '>>', 'trace.jsonl' or die $!;
4251 local %SimpleFlow::DEFAULTS = ('trace_fh' => $trace);
4252  
4253 Each line holds every field of the record except C<stdout> and C<stderr>, which
4254 can be any size, plus C<time>, when the line was written: the command line and
4255 C<env> included, so see L</"Secrets">. Open the file without an encoding
4256 layer: the lines are UTF-8 already.
4257  
4258 =head2 Locking
4259  
4260 C<< lock =E<gt> 1 >> protects a step against a second copy of the same pipeline running
4261 it at the same time. The first run to reach the step takes a lock on its
4262 outputs; a second run that reaches it meanwhile says it is waiting, waits, and
4263 then finds the outputs made and skips the step:
4264  
4265 my $t = task(
4266 cmd => 'long-step > out.txt',
4267 'output_file' => 'out.txt',
4268 lock => 1,
4269 );
4270  
4271 The lock files are kept in C<.simpleflow/> in the working directory (the one
4272 C<dir> names, if it is given), as Snakemake keeps its locks in C<.snakemake/>,
4273 so two runs see each other only when they share a working directory. The files
4274 are left there afterwards, since removing one that another process is waiting
4275 on would let two runs through. A step with no declared outputs has nothing to
4276 lock, and a dry run takes no lock. The locks are C<flock> locks, which some
4277 network filesystems do not honour.
4278  
4279 An output is locked under its real directory and its own name, so C<out> and
4280 C<sub/../out>, or a name reached through a linked directory, are one output
4281 here; an output that is itself a symbolic link is locked under what it points
4282 at as well. A step also takes a shared lock on every directory above each of
4283 its outputs, so that a step whose output is a directory, and one whose output
4284 is a file inside it, do not run at once. Two hard links to one file are still
4285 two outputs.
4286  
4287 C<.simpleflow/>, and C<.simpleflow/cmd/> under it, must be directories, not
4288 symbolic links: C<task> refuses a link there, and opens nothing inside them
4289 through one. These guard against a link planted by someone else; they do not
4290 make a working directory others can write to safe to run a pipeline in.
4291  
4292 =head2 Re-running a changed command
4293  
4294 By default a step whose outputs exist is skipped even if its command has been
4295 edited since they were made. C<< stale_cmd =E<gt> 1 >> re-runs it, as Snakemake's
4296 C<params> and C<code> rerun triggers do:
4297  
4298 my $t = task(
4299 cmd => 'bwa mem -t 8 -k 19 ref.fa reads.fq > aln.sam',
4300 'output_file' => 'aln.sam',
4301 'stale_cmd' => 1,
4302 );
4303  
4304 Changing the command, its C<env>, its C<threads>, or what it runs inside (its
4305 container, conda environment, executor or wrapper) makes C<cmd.changed> C<1> and
4306 the step run again. What made each set of outputs is kept, as a digest, in
4307 C<.simpleflow/cmd/> in the working directory, and written only after a
4308 successful run. Outputs that exist with nothing on record, made before
4309 C<stale_cmd> was used, or by hand, are not re-run: the command is recorded
4310 against them, so that the next change is seen.
4311  
4312 A step run I<without> C<stale_cmd> over outputs that have a command on record
4313 still replaces them, so after it succeeds its own command is recorded in place
4314 of the old one, and a later C<stale_cmd> run of the old command runs again
4315 rather than taking the other's outputs as its own. With nothing on record, a
4316 step without C<stale_cmd> records nothing.
4317  
4318 =head2 Hooks
4319  
4320 C<on_success> and C<on_failure> are called with the record once a command has
4321 run, after the record is printed and logged:
4322  
4323 local %SimpleFlow::DEFAULTS = (
4324 'on_failure' => sub { my $r = shift; notify("$r->{cmd} failed: exit $r->{exit}") },
4325 );
4326  
4327 C<on_failure> runs before C<task> dies, so it runs under the default C<< die =E<gt> 1 >>
4328 as well. Neither is called for a step that is skipped or dry-run. A hook that
4329 dies stops C<task> there, with its own exception. Set in C<%SimpleFlow::DEFAULTS>,
4330 they are the pipeline-wide C<onsuccess> and C<onerror> of Snakemake.
4331  
4332 =head2 Containers, conda and clusters
4333  
4334 A command can be run inside a container, a conda environment, a SLURM job
4335 step, or any wrapper you name:
4336  
4337 my $t = task(
4338 cmd => ['samtools', 'index', 'x.bam'],
4339 container => 'biocontainers/samtools:1.19', # with docker, by default
4340 );
4341 my $u = task(
4342 cmd => 'python train.py',
4343 'conda_env' => 'analysis',
4344 executor => 'slurm',
4345 threads => 8,
4346 mem => '16G',
4347 walltime => '2:00:00',
4348 );
4349  
4350 C<container> runs C<docker run --rm> (or C<podman run>) with the working directory
4351 mounted at its own path and used as the container's working directory, and,
4352 for docker, with your own user and group, so that the files the command makes
4353 are yours. C<< container_engine =E<gt> 'singularity' >> or C<'apptainer'> runs
4354 C<singularity exec> with the working directory bound instead. The variables
4355 C<env> sets are passed into a docker or podman container by name; singularity
4356 and apptainer pass the whole environment through themselves.
4357  
4358 C<conda_env> runs C<< conda run -n E<lt>nameE<gt> >>, or C<< -p E<lt>pathE<gt> >> for a path.
4359  
4360 C<< executor =E<gt> 'slurm' >> runs the command through C<srun>, which waits for the job
4361 step and passes its exit status back, asking for C<threads> CPUs, C<mem> memory
4362 and C<walltime> time; C<executor_args> adds any other C<srun> arguments. With
4363 L<parallel|/"Running steps in parallel">, several steps run on the cluster at
4364 once. C<threads> is also given to the command, wherever it runs, as
4365 C<SIMPLEFLOW_THREADS>, for it to pass to its own option for threads.
4366  
4367 C<wrapper> runs the command inside any other command, given as an array ref,
4368 such as C<['nice', '-n', '10']> or C<['env', 'LC_ALL=C']>.
4369  
4370 These nest, outermost first, as executor, container, conda environment,
4371 wrapper. A string C<cmd> is run by C</bin/sh -c> (C<cmd.exe /c> on MSWin32) inside
4372 all of them, so it keeps its pipes and redirections. The record's C<wrapped.cmd>
4373 is what was actually run, and a dry run prints it.
4374  
4375 =head2 Running without a shell
4376  
4377 Giving C<cmd> an array ref runs the command directly, with no shell in between:
4378  
4379 my $t = task(
4380 cmd => ['gzip', '-9', $file], # $file needs no quoting
4381 'output_file' => "$file.gz",
4382 );
4383  
4384 This is the form to reach for when an argument comes from data — a filename
4385 with a space, a quote, or a C<$> in it is passed through untouched instead of
4386 being re-parsed by the shell. You lose shell features (C<< E<gt> >>, C<|>, C<*>, C<&&>) in
4387 exchange; use the string form when you want them.
4388  
4389 This holds for a one-element array ref too: C<< cmd =E<gt> ['gzip -9 x'] >> looks for a
4390 program literally named C<gzip -9 x>, and fails, rather than handing the string
4391 to the shell as Perl's own C<system> does with a list of one.
4392  
4393 =head2 Quiet runs
4394  
4395 Every C<task> prints its record to the terminal. Error diagnostics — the
4396 arguments and file lists printed before C<task> dies or warns — go to C<STDERR>,
4397 so redirecting standard output does not hide them. Over a hundred-step pipeline
4398 that is a lot of scrollback, so C<< quiet =E<gt> 1 >> suppresses it:
4399  
4400 my $t = task(
4401 cmd => 'one of very many steps',
4402 'log_fh' => $log,
4403 quiet => 1,
4404 );
4405  
4406 The log filehandle still receives the full record, and error messages still go
4407 to C<STDERR>: asking for less noise is not the same as asking to be kept in the
4408 dark about a failure.
4409  
4410 =head2 Standard input
4411  
4412 The command is run with its standard input on the null device, so a command
4413 that stops to ask a question gets an immediate end-of-file and carries on
4414 instead of waiting for an answer:
4415  
4416 my $t = task(cmd => 'rm -r some/tree'); # "remove write-protected file?"
4417  
4418 This matters because C<task> captures the command's output. A prompt is written
4419 to standard error, which has been redirected into the capture, so nothing
4420 reaches the terminal: before 0.17 such a command hung with no visible reason —
4421 for ever with no C<timeout>, and with one it was killed and reported as
4422 C<timed.out>, blaming the clock for what was really an unanswered question.
4423  
4424 Shell redirection inside the command is unaffected, since that is the shell's
4425 business rather than C<task>'s:
4426  
4427 my $t = task(cmd => 'sort < unsorted.txt > sorted.txt');
4428  
4429 To hand the command the caller's own standard input instead — a pipeline step
4430 that really does read the data your script was given — ask for it:
4431  
4432 my $t = task(cmd => 'sort > sorted.txt', stdin => 'inherit');
4433  
4434 C<'inherit'> is the behaviour of 0.162 and earlier, and comes with its hazards:
4435 the command consumes input your own script can then no longer read, and a
4436 command that prompts will hang exactly as it used to. The caller's standard
4437 input is saved and restored around every run either way, including when the
4438 command dies, and a caller that had closed it keeps it closed. A C<STDIN> that
4439 is not descriptor 0, such as one opened on an in-memory scalar, is not the
4440 command's standard input in any case: it is left alone, and descriptor 0 is
4441 pointed at the null device and put back instead.
4442  
4443 =head2 Dry runs
4444  
4445 Useful for inspecting a pipeline without executing anything expensive:
4446  
4447 my $t = task(
4448 cmd => 'a long-running, time-consuming command',
4449 'dry_run' => 1,
4450 'log_fh' => $fh,
4451 );
4452  
4453 The command is printed (and logged) but not run; C<will.do> is C<"no: dry run">.
4454 The record is printed and logged as for any other step.
4455  
4456 A dry run makes nothing, so a later step's input — an earlier step's output —
4457 is legitimately absent. A dry run therefore does not die over a missing
4458 C<input_files> entry, as a real run does; it lists it under "these input files
4459 do not exist yet", and the dry run of the whole pipeline carries on.
4460  
4461 =head2 Failure behaviour
4462  
4463 By default (C<< die =E<gt> 1 >>) C<task> dies if the command exits non-zero, is killed by
4464 a signal, exceeds its C<timeout>, or leaves any declared C<output_files> missing
4465 afterwards, so a broken step stops the pipeline immediately. The message names
4466 every one of those that happened, for instance
4467 C<"make all" exited 2; these output files should have been made but are missing:
4468 a.out, from build.pl line 12>. When the command wrote anything to standard
4469 error, the message ends with its last six lines, which is where a compiler, a
4470 traceback or C<make> says what went wrong.
4471  
4472 Whichever of those happened, every declared output that I<does> exist is moved to
4473 C<< E<lt>fileE<gt>.failed >> (replacing any C<.failed> left from before), and the new names are
4474 listed in the record's C<failed.outputs> and on C<STDERR>. A name declared twice
4475 is moved once; a file inside a declared directory moves with the directory,
4476 under its own name; and when one output is named like another's C<.failed>, as
4477 C<out> and C<out.failed> are, the longer name is moved first, so that neither is
4478 lost. When the message quotes standard error from a C<stderr_file> that was one
4479 of the outputs, it is read before the file is moved. A command that fails
4480 part-way often leaves a truncated file behind; left under its own name, it would
4481 pass the L<skip test|/"Skipping completed work"> on the next run and become the
4482 result for good. Snakemake deletes a failed job's outputs for the same reason;
4483 moving them keeps the partial contents for debugging.
4484  
4485 With C<< die =E<gt> 0 >>, C<task> instead warns and returns its result hash with
4486 C<< will.do =E<gt> "FAILED" >>, letting you decide what to do:
4487  
4488 my $t = task(cmd => 'a step that may fail', die => 0);
4489 if ($t->{'will.do'} eq 'FAILED') {
4490 ... # $t->{'exit'}, $t->{signal}, $t->{stderr} and $t->{'timed.out'} say why
4491 }
4492  
4493 =head2 Defaults for a whole pipeline
4494  
4495 C<%SimpleFlow::DEFAULTS> gives a value to any key a C<task> call leaves undefined:
4496  
4497 local %SimpleFlow::DEFAULTS = (
4498 'dry_run' => 1, # dry-run the whole pipeline
4499 'log_fh' => $log,
4500 quiet => 1,
4501 env => { LC_ALL => 'C' },
4502 );
4503  
4504 A task that sets a key itself keeps its own value. C<env> is the one exception:
4505 a task's own C<env> is merged with the default one, its own entries winning, and its own C<env_secret> is added to the default one.
4506 Keys that name a particular step (C<cmd>, the C<input.*> and C<output.*> lists,
4507 C<stdout_file> and C<stderr_file>) are refused in C<%DEFAULTS>, since every step
4508 would then run the same command or claim the same files, and so is any key
4509 C<task> does not accept.
4510  
4511 =head2 C<say2>
4512  
4513 say2($message, $filehandle);
4514  
4515 "Say to two places": prints C<$message> to standard output B<and> to the given
4516 log filehandle, prefixed with the calling file and line number so log entries
4517 are traceable. The filehandle must be open, or C<say2> dies.
4518  
4519 open my $log, '>', 'run.log';
4520 say2('starting equilibration', $log); # -> STDOUT and run.log
4521 close $log;
4522  
4523 =head1 Running steps in parallel
4524  
4525 C<parallel> runs independent steps at the same time, at most C<jobs> at once,
4526 and returns their records in the order given:
4527  
4528 my @records = parallel(
4529 jobs => 4,
4530 tasks => [
4531 map { { cmd => "gzip -9 $_", 'input_file' => $_, 'output_file' => "$_.gz" } } @samples
4532 ],
4533 );
4534  
4535 Each entry of C<tasks> is the arguments of one C<task>, which runs in full, in a
4536 child process of its own: its checks, its log, its record, its options, and
4537 C<%SimpleFlow::DEFAULTS>. Each record's C<source.file> and C<source.line> are the
4538 C<parallel> call's. Output from several steps at once interleaves, a record at
4539 a time, on the terminal, in a shared log and in a shared L<trace|/"Tracing">:
4540 each step writes its record holding a lock, so that no two records are mixed
4541 within a line.
4542  
4543 When a step fails, and C<task> would die, no further step is started; those
4544 already running are left to finish, and then C<parallel> dies with every
4545 failure. C<< 'keep_going' =E<gt> 1 >> runs every step regardless, and dies at the end if
4546 any failed, as Snakemake's C<--keep-going> does. Under C<< die =E<gt> 0 >> a failed step
4547 is only a record with C<< will.do =E<gt> "FAILED" >>, and C<parallel> returns.
4548  
4549 A C<TERM>, C<HUP>, C<INT> or C<QUIT> sent to your script while C<parallel> runs is
4550 passed to every running step, which passes it to its command; once they have
4551 ended, the signal is passed on to your script. A signal your script ignores
4552 stays ignored, by C<parallel> and by the commands.
4553  
4554 C<jobs> above 1 needs a real C<fork()>, so it is refused on C<MSWin32>, where perl
4555 emulates one with threads. C<< jobs =E<gt> 1 >> runs the steps one after another, and
4556 works everywhere.
4557  
4558 The order of steps that depend on each other is still yours: C<parallel> runs
4559 the ones it is given at once, so give it only steps that can run together, and
4560 call it again for the next stage.
4561  
4562 =head1 Reports
4563  
4564 C<report> turns a L<trace|/"Tracing"> into a single HTML page:
4565  
4566 report(trace => 'trace.jsonl', html => 'report.html', title => 'RNA-seq, batch 3');
4567  
4568 The page counts the tasks by status, and lists each with its status, command,
4569 note, start time, duration, CPU time, exit code, signal, attempts and where in
4570 your script it was called, alongside a timeline of when each ran. It is one
4571 self-contained file, with no scripts and nothing fetched, which follows the
4572 reader's light or dark setting, so that it can be mailed or archived as it
4573 is. C<report> returns the number of tasks it read, and dies naming the line of
4574 the trace it could not read: one that is not strict JSON in UTF-8, nests more
4575 than 512 deep, or has a time that is not a number of seconds, a command or
4576 C<dir> that is not a string, or file and directory names that are not a list of
4577 strings. A C<title> may be a character string or UTF-8 bytes.
4578  
4579 =head2 Flow diagrams
4580  
4581 C<svg> writes the pipeline's flow diagram as an SVG image, like Snakemake's
4582 C<--dag> and Nextflow's C<-with-dag>:
4583  
4584 report(trace => 'trace.jsonl', html => 'report.html', svg => 'flow.svg');
4585  
4586 Each task is a box, numbered as in the page and colored by its status, showing
4587 its command, clipped to 33 characters. An arrow runs from a task to each later
4588 task that reads what it wrote: an input file or directory is linked to the
4589 most recent earlier task that declared it as an output, or declared a directory
4590 it is in. Names are compared as absolute paths, each relative to the C<dir> its
4591 step ran in, so C<a.txt> and C<./a.txt> are the same file, and the same name in
4592 two directories is two. Each is then resolved, as far as it exists when
4593 C<report> runs, through symbolic links and C<..>, so a file named through a link
4594 to its directory, such as C</tmp> on macOS, is the file its real path names;
4595 C<x/../a.txt> is C<a.txt> while C<x> exists, and otherwise is not.
4596 The flow runs left to right, each task one column to the right of the furthest
4597 of its sources. Hovering over a box shows the whole command, the note and the
4598 names, and over an arrow, the names that link the two tasks. A pipeline run
4599 twice onto one trace draws two separate flows.
4600  
4601 The diagram is drawn from what each step declared, not from what its command
4602 did: a file a command reads without declaring it as an input is not linked.
4603  
4604 C<report> takes C<html>, C<svg> or both. The HTML page shows the same diagram
4605 below the table, when at least one task uses another's output. The image, like
4606 the page, follows the reader's light or dark setting, and needs nothing else to
4607 be shown. Each file is written under a temporary name beside it and renamed
4608 into place once all are written in full, so a C<report> that dies, on a full
4609 disk or a missing directory, leaves the page and the diagram as they were.
4610  
4611 =head1 Dependencies
4612  
4613 Core/runtime modules used by SimpleFlow:
4614  
4615 =over
4616  
4617 =item * L<Data::Printer> (C<DDP>) pretty result/record printing
4618  
4619 =item * L<Devel::Confess> stack traces, in colour on a
4620 terminal, for errors and warnings raised inside C<task> and C<say2>. It is
4621 switched on only for the length of each call, so your own program's C<die>
4622 and C<warn> are left exactly as you wrote them.
4623  
4624 =item * C<List::Util>, C<Scalar::Util>, C<Time::HiRes>, C<Cwd>, C<POSIX>, C<File::Spec>,
4625 C<File::Temp>, C<File::Find>, C<File::Path>, C<Fcntl>, C<Digest::MD5>, C<Storable>
4626 core utilities; C<stdout> and C<stderr> are captured with
4627 C<POSIX::dup2> onto temporary files
4628  
4629 =back
4630  
4631 The test suite additionally uses C<Test::More>,
4632 L<JSON::PP> (core from perl 5.14) and
4633 L<Test::Exception>; it captures
4634 output with its own small helper, C<t/lib/CaptureStd.pm>.
4635  
4636 =head1 Changes
4637  
4638 The release notes are in the C<Changes> file at the root of the
4639 distribution, in the format CPAN itself reads.
4640  
4641 =head1 COPYRIGHT AND LICENSE
4642  
4643 This software is free. It is licensed under the same terms as Perl itself
4644  
4645 =head1 Thanks
4646  
4647 A lot of this work used Claude AI, which was paid for by the University of Idaho's IMCI, and to Brett Estrade and Hexmeister for help.
↑ Summary