view release on metacpan or search on metacpan
.githooks/pre-commit view on Meta::CPAN
my ($command, %options) = @_;
return App::Actions::Process::capture($command, %options);
}
# Not a git work tree - an unpacked distribution, say: there is no commit to
# guard and no index to read. git says so itself; its message is not this
# hook's to repeat, so it is dropped.
my ($root, $root_status) = run_command(
[qw(git rev-parse --show-toplevel)],
quiet_stderr => 1,
);
if ($root_status) {
print "$label: not a git work tree, so nothing was checked.\n" if $explicit;
exit 0;
}
chomp $root;
chdir $root or do {
print STDERR "$label: cannot change to '$root': $!\n";
exit 0;
.githooks/pre-commit view on Meta::CPAN
# skipping a file the checks would have read.
if ($worktree) {
%wanted = map { $_ => 1 } @check_names;
} else {
# Nothing staged that could move either agreement: the commit cannot be
# the half-applied change this guards against. An unborn HEAD makes both
# diffs fail, and the first commit is checked like any other, so both
# checks run.
my ($schema_changed, $schema_status) = run_command(
[ 'git', 'diff', '--cached', '--name-only', 'HEAD', '--', @schema_relevant ],
quiet_stderr => 1,
);
my ($live_changed, $live_status) = run_command(
[ 'git', 'diff', '--cached', '--name-only', 'HEAD', '--', @live_relevant ],
quiet_stderr => 1,
);
$wanted{'schema'} = 1 if $schema_status || $schema_changed =~ /\S/;
$wanted{'live knobs'} = 1 if $live_status || $live_changed =~ /\S/;
}
my @checks = map { { name => $_, path => $check_path{$_} } }
grep { $wanted{$_} } @check_names;
# One line per check: what happened to it. A check that ran shows how many
.githooks/pre-commit view on Meta::CPAN
my $snapshot = $root;
if (!$worktree) {
$snapshot = tempdir(
'app-actions pre-commit XXXX',
TMPDIR => 1, CLEANUP => 1,
);
(my $prefix = $snapshot) =~ s{\\}{/}g;
my ($checkout_error, $checkout_status) = run_command(
[ 'git', 'checkout-index', '-a', '-f', "--prefix=$prefix/" ],
merge_stderr => 1,
);
# A conflicted index cannot be written out. A merge commit is not the
# half-applied change this is for, and refusing it would block the merge.
if ($checkout_status) {
print STDERR "$label: the staged files could not be read, so the "
. "checks were skipped.\n";
print STDERR "$checkout_error\n" if length $checkout_error;
exit 0;
}
.githooks/pre-commit view on Meta::CPAN
my (@failed, %results);
for my $check (@checks) {
my ($output, $status);
{
local $ENV{HARNESS_ACTIVE};
local $ENV{HARNESS_VERSION};
local $ENV{HARNESS_OPTIONS};
($output, $status) = run_command(
[ $^X, "-I$lib", $check->{path} ],
merge_stderr => 1,
);
}
# The plan, "1..N", says how many tests ran; done_testing prints it last.
my ($tests) = $output =~ /^1\.\.(\d+)/m;
$results{ $check->{name} } = { passed => !$status, tests => $tests };
next unless $status;
# The temporary directory is gone by the time anyone reads this, so its
â projectDir? = ⥠⧠abs(workflowFile?) â (PATH â "/.github/workflows/" â NAME)
â â raises ProjectDirRequired
â let root == (projectDir? â ⥠â abs(projectDir?))
â â§ (projectDir? = ⥠â repository(abs(workflowFile?)))
â root â directories â raises ProjectDirMissing
â actions!.workflow = Workflow.Load(abs(workflowFile?))
â actions!.project_dir = root
â actions!.options = settings
â let logged == (logger? â ⥠â logger?)
â â§ (logger? = ⥠⧠logger â dom configured â configured(logger))
â â§ (logger? = ⥠⧠logger â dom configured â stderrLogger)
â where configured == fileConfig(App__Actions) â envConfig(App__Actions__)
â -- fileConfig includes the UNIVERSAL section of universal.yaml
â actions!.logger â LogAbstraction
â logged = NULL â actions!.logger = silentLogger
â logged â NULL â actions!.logger = toLogger(logged)
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
The workflowFile? and projectDir? above are the values in settings, so a
configuration file or environment variable can replace them too.
```
lib/App/Actions.pm view on Meta::CPAN
â projectDir? = ⥠⧠abs(workflowFile?) â (PATH â "/.github/workflows/" â NAME)
â â raises ProjectDirRequired
â let root == (projectDir? â ⥠â abs(projectDir?))
â â§ (projectDir? = ⥠â repository(abs(workflowFile?)))
â root â directories â raises ProjectDirMissing
â actions!.workflow = Workflow.Load(abs(workflowFile?))
â actions!.project_dir = root
â actions!.options = settings
â let logged == (logger? â ⥠â logger?)
â â§ (logger? = ⥠⧠logger â dom configured â configured(logger))
â â§ (logger? = ⥠⧠logger â dom configured â stderrLogger)
â where configured == fileConfig(App__Actions) â envConfig(App__Actions__)
â -- fileConfig includes the UNIVERSAL section of universal.yaml
â actions!.logger â LogAbstraction
â logged = NULL â actions!.logger = silentLogger
â logged â NULL â actions!.logger = toLogger(logged)
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
The workflowFile? and projectDir? above are the values in settings, so a
configuration file or environment variable can replace them too.
lib/App/Actions/Docker.pm view on Meta::CPAN
}
}
my @commands = map {
[ $self->_command('pull', $self->platform_args, $_) ]
} @$images;
my %redirect;
if ($quiet) {
my $devnull = File::Spec->devnull;
%redirect = (stdout => $devnull, stderr => $devnull);
}
my $codes = App::Actions::Process::run_parallel(
\@commands,
concurrency => $options{concurrency} || 4,
%redirect,
);
my %results;
for my $index (0 .. $#$images) {
lib/App/Actions/Docker.pm view on Meta::CPAN
return $self->_capture(1, 0, @args);
}
# Capture both of the command's streams, as if it had been run with 2>&1.
sub capture_merged {
my ($self, @args) = @_;
return $self->_capture(1, 1, @args);
}
sub _capture {
my ($self, $quiet_stderr, $merge_stderr, @args) = @_;
return ('', 0) unless $self->_announce(@args);
my ($command, $hidden) = $self->_hide_variables(@args);
local @ENV{ keys %{$hidden} } = values %{$hidden};
return App::Actions::Process::capture(
[ $self->_command(@{$command}) ],
quiet_stderr => $quiet_stderr,
merge_stderr => $merge_stderr,
);
}
sub redact {
my ($self, $text) = @_;
return $text unless defined $text;
# Longest first: when one secret contains another, replacing the shorter
# one first would leave the rest of the longer one in the text ("abc" and
lib/App/Actions/Process.pm view on Meta::CPAN
return $count if $count > 0;
}
my $count = eval { POSIX::sysconf(POSIX::_SC_NPROCESSORS_ONLN()) };
return $count + 0 if defined $count && $count =~ /\A[1-9][0-9]*\z/;
return 1;
}
# Run $command (an array reference) and capture its standard output.
# Standard error is passed through to the caller unless quiet_stderr is true.
# Returns the output and the exit code.
sub capture {
my ($command, %options) = @_;
croak 'No command given' unless ref $command eq 'ARRAY' && @$command;
my $temp = File::Temp->new(
TEMPLATE => 'app-actions-XXXXXX',
TMPDIR => 1,
UNLINK => 1,
);
my $status = run(
$command,
stdout => $temp->filename,
stderr => $options{quiet_stderr} ? File::Spec->devnull : undef,
merge_stderr => $options{merge_stderr} ? 1 : 0,
);
seek $temp, 0, 0 or croak "Unable to rewind captured output: $!";
local $/;
my $output = <$temp>;
$output = '' unless defined $output;
$output =~ s/\r\n/\n/g;
return ($output, $status);
}
lib/App/Actions/Process.pm view on Meta::CPAN
}
return system { $args[0] } @args;
}
# Run $command with both streams discarded.
sub run_quiet {
my ($command) = @_;
my $devnull = File::Spec->devnull;
return run($command, stdout => $devnull, stderr => $devnull);
}
# Run $command with its output going straight to the caller's streams.
sub stream {
my ($command) = @_;
croak 'No command given' unless ref $command eq 'ARRAY' && @$command;
STDOUT->flush;
STDERR->flush;
lib/App/Actions/Process.pm view on Meta::CPAN
return exit_code($?);
}
# Point a child's standard streams at the files the caller chose. This runs
# after fork() and before exec(), so a failure is reported by the child and
# ends it rather than escaping into the parent.
sub _redirect_child {
my (%redirect) = @_;
for my $stream (qw(stdout stderr)) {
my $file = $redirect{$stream};
next unless defined $file;
my $handle = $stream eq 'stdout' ? \*STDOUT : \*STDERR;
open $handle, $redirect{append} ? '>>' : '>', $file or do {
print STDERR __PACKAGE__->i18n('process.redirect_failed', {
stream => $stream, file => $file, error => "$!",
}), "\n";
POSIX::_exit(127);
};
lib/App/Actions/Process.pm view on Meta::CPAN
# The child ends with POSIX::_exit, which flushes nothing, so a
# buffered handle would lose the message that says why exec failed.
$handle->autoflush(1);
}
return;
}
# Run several commands at the same time, at most $concurrency of them at once,
# with their output going straight to the caller's streams (or to the files
# named by stdout and stderr). Returns one exit code per command, in the
# order the commands were given.
#
# Only the running is concurrent: the results are collected by index, so a
# caller reports the same failures in the same order whichever command was
# slowest. fork() is used only where it is reliable. On Windows the child of
# Perl's emulated fork() shares the parent's handles, so the commands are run
# one after another there instead.
sub run_parallel {
my ($commands, %options) = @_;
croak 'No commands given' unless ref $commands eq 'ARRAY';
return [] unless @$commands;
my $concurrency = $options{concurrency} || 4;
$concurrency = @$commands if $concurrency > @$commands;
# A caller that wants the output kept out of its own streams names where
# it should go instead, and gets the same treatment one command at a time.
my %redirect;
$redirect{stdout} = $options{stdout} if defined $options{stdout};
$redirect{stderr} = $options{stderr} if defined $options{stderr};
# Every program's output goes to the same files. Each program opening
# them afresh would keep only the last one's, so they are emptied once
# here and each program adds to them.
if (%redirect) {
my %seen;
for my $file (grep { !$seen{$_}++ } values %redirect) {
next if $file eq File::Spec->devnull;
open my $handle, '>', $file or croak "Unable to open '$file': $!";
close $handle or croak "Unable to open '$file': $!";
lib/App/Actions/Process.pm view on Meta::CPAN
croak 'No command given' unless ref $command eq 'ARRAY' && @$command;
my $stdout = defined $options{stdout} ? $options{stdout} : File::Spec->devnull;
# Anything already buffered belongs before the child's output.
STDOUT->flush;
STDERR->flush;
open my $saved_stdout, '>&', \*STDOUT
or croak "Unable to duplicate STDOUT: $!";
open my $saved_stderr, '>&', \*STDERR
or croak "Unable to duplicate STDERR: $!";
# append adds to the files rather than replacing them, which is how
# run_parallel sends several programs to one file.
my $mode = $options{append} ? '>>' : '>';
my $error;
my $redirected = open STDOUT, $mode, $stdout;
if ($redirected && $options{merge_stderr}) {
# The shell's 2>&1: standard error is a duplicate of the handle
# standard output was just opened to, so the two share one offset and
# the child's writes arrive in the order it made them.
$redirected = open STDERR, '>&', \*STDOUT;
} elsif ($redirected && defined $options{stderr}) {
$redirected = open STDERR, $mode, $options{stderr};
}
$error = $! unless $redirected;
my $status = 0;
if ($redirected) {
# Perl announces a program it cannot start; the exit status carries the
# same information, and the caller reports it in its own words.
local $SIG{__WARN__} = sub {
my $warning = shift;
warn $warning unless $warning =~ /^Can't exec /;
};
_system($command);
$status = $?;
}
open STDOUT, '>&', $saved_stdout
or croak "Unable to restore STDOUT: $!";
open STDERR, '>&', $saved_stderr
or croak "Unable to restore STDERR: $!";
croak "Unable to redirect command output: $error" unless $redirected;
return exit_code($status);
}
1;
__END__
lib/App/Actions/Process.pm view on Meta::CPAN
my ($output, $status) = App::Actions::Process::capture(\@command, %options);
Runs a program and returns what it printed.
=head3 ARGUMENTS
=over 4
=item * C<\@command> - the program and its arguments. Not empty.
=item * C<quiet_stderr> - optional. True to throw away the error output.
Otherwise it goes to your terminal.
=item * C<merge_stderr> - optional. True to include the error output in the
returned text, in the order the program wrote it (like the shell's
C<2E<gt>&1>).
=back
=head3 RETURNS
A list of two values: the output, and the exit status. Windows line ends
(C<\r\n>) in the output become C<\n>.
lib/App/Actions/Process.pm view on Meta::CPAN
=head3 EXAMPLE
my ($version) = App::Actions::Process::capture(['perl', '-e', 'print $]']);
=head3 API SPECIFICATION
=head4 INPUT
{
command => { type => 'arrayref', min => 1 },
quiet_stderr => { type => 'boolean', optional => 1 },
merge_stderr => { type => 'boolean', optional => 1 },
}
=head4 OUTPUT
{ type => 'array', min => 2, max => 2 } # (string, integer)
=head3 MESSAGES
+------------------------------------------+---------------------------------+---------------------------+
| Exception (croak) | Meaning | What to do |
lib/App/Actions/Process.pm view on Meta::CPAN
=head3 ARGUMENTS
=over 4
=item * C<\@command> - the program and its arguments. Not empty.
=item * C<stdout> - optional. The file for the output. Default: the null
device (the output is thrown away).
=item * C<stderr> - optional. The file for the error output. Default: your
terminal.
=item * C<merge_stderr> - optional. True to send the error output to the
C<stdout> file too. It wins over C<stderr>.
=item * C<append> - optional. True to add to the C<stdout> and C<stderr>
files rather than replace what is in them.
=back
=head3 RETURNS
The exit status.
=head3 SIDE EFFECTS
Replaces the files named by C<stdout> and C<stderr>. While the program runs,
this process's own C<STDOUT> and C<STDERR> point to those files; they are
put back afterwards.
=head3 EXAMPLE
my $status = App::Actions::Process::run(['make'], stdout => 'build.log', merge_stderr => 1);
=head3 API SPECIFICATION
=head4 INPUT
{
command => { type => 'arrayref', min => 1 },
stdout => { type => 'string', optional => 1 },
stderr => { type => 'string', optional => 1 },
merge_stderr => { type => 'boolean', optional => 1 },
append => { type => 'boolean', optional => 1 },
}
=head4 OUTPUT
{ type => 'integer', min => 0, max => 255 }
=head3 MESSAGES
As for L</capture>, except the "rewind" message.
lib/App/Actions/Process.pm view on Meta::CPAN
=head3 ARGUMENTS
=over 4
=item * C<\@commands> - a list of commands, each a list reference as for
L</stream>.
=item * C<concurrency> - optional. The most programs that run at the same
time. Default 4.
=item * C<stdout>, C<stderr> - optional. Files for every program's output,
as for L</run>. Each file is emptied once, before the first program starts,
and then every program adds to it, so it holds the output of them all.
Without them, the output goes to your terminal, mixed together.
=back
=head3 RETURNS
An array reference of exit statuses, in the same order as C<\@commands>.
An empty list gives an empty array reference.
lib/App/Actions/Process.pm view on Meta::CPAN
my @failed = grep { $statuses->[$_] != 0 } 0 .. $#files;
=head3 API SPECIFICATION
=head4 INPUT
{
commands => { type => 'arrayref' },
concurrency => { type => 'integer', min => 1, optional => 1, default => 4 },
stdout => { type => 'string', optional => 1 },
stderr => { type => 'string', optional => 1 },
}
=head4 OUTPUT
{ type => 'arrayref', element_type => 'integer' }
=head3 MESSAGES
+--------------------------+----------------------------------+------------------------------+
| Message | Meaning | What to do |
+--------------------------+----------------------------------+------------------------------+
| No commands given (croak)| \@commands is not an array ref | pass an array reference |
| Unable to open 'F': ERR | the stdout or stderr file could | check the path |
| (croak) | not be emptied before the start | |
| Unable to run 'P': ERR | (printed by the child) program P | install P or fix its path; |
| | could not start; status 127 | the status is 127 |
| Unable to redirect | (printed by the child) the file | check the path; status 127 |
| STREAM to 'F': ERR | could not be opened | |
+--------------------------+----------------------------------+------------------------------+
=head2 quote_win32
my $argument = App::Actions::Process::quote_win32($text);
lib/App/Actions/Process.pm view on Meta::CPAN
â merge? â r! = (crlf_to_lf(out â err), s) â : in time order
â ¬merge? â r! = (crlf_to_lf(out), s)
â ¬merge? ⧠¬quiet? â err goes to the caller's STDERR
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 run
ââ Run âââââââââââââââââââââââââââââââââââââââââââââ
â ÎHost
â command? : COMMAND
â stdout?, stderr? : optional FILE
â merge?, append? : ð¹
â r! : STATUS
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â (s, out, err) = exec(command?)
â r! = s
â let before(F) == (if append? then contents(F) else â¨â©)
â contents'(stdout? or null) = before(stdout?) â (out â (if merge? then err else â¨â©))
â ¬merge? â§ stderr? â ⥠â contents'(stderr?) = before(stderr?) â err
â STDOUT' = STDOUT â§ STDERR' = STDERR
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 run_quiet
ââ RunQuiet ââââââââââââââââââââââââââââââââââââââââ
â Run[stdout? := null, stderr? := null]
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 stream
ââ Stream ââââââââââââââââââââââââââââââââââââââââââ
â ÎHost
â command? : COMMAND
â r! : STATUS
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â (s, out, err) = exec(command?) â§ r! = s
lib/App/Actions/Process.pm view on Meta::CPAN
ââ RunParallel âââââââââââââââââââââââââââââââââââââ
â ÎHost
â commands? : seq COMMAND
â concurrency? : ââ
â r! : seq STATUS
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â #r! = #commands?
â â i â dom commands? ⢠r!(i) = first(exec(commands?(i)))
â at no time do more than min(concurrency?, #commands?) commands run
â â F â {stdout?, stderr?} ⢠contents'(F) = â { i â dom commands? ⢠output_F(i) }
â Windows ⨠concurrency? < 2 â the commands run one after another
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 quote_win32
ââ QuoteWin32 ââââââââââââââââââââââââââââââââââââââ
â arg? : optional seq CHAR
â r! : seqâ CHAR
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â arg? = ⥠⨠arg? = â¨â© â r! = "\"\""
lib/App/Actions/Runner.pm view on Meta::CPAN
# _git
# Purpose: Ask git about the project.
# Entry: @args - git's arguments.
# Exit status: Returns its output, or '' when git fails or is absent.
# Side effects: Runs git (not fork plus a piped open, which Windows does not
# reliably support).
sub _git {
my ($self, @args) = @_;
my ($output) = App::Actions::Process::capture([ 'git', '-C', $self->{project_dir}, @args ], quiet_stderr => 1);
return defined $output ? $output : '';
}
# _run_groups
# Purpose: Run every selected job, each after the jobs it needs.
# Entry: None; _select_jobs has run.
# Exit status: Returns a hash reference of job id to its group result.
# Side effects: Runs the jobs.
sub _run_groups {
lib/App/Actions/Runner.pm view on Meta::CPAN
â r! : Runner
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â dom options? â dom optionRules
â isDirectory(projectDir?)
â ¬ (options?(pull) â§ options?(no_pull))
â r!.pullConcurrency =
â first(options?(pull_concurrency), env(ACTION_RUN_PULL_CONCURRENCY), 4) â ââ
â r!.parallel = (if options?(parallel) â ââ then options?(parallel) else 1)
â r!.dryRun = options?(dry_run) ⨠options?(explain)
â r!.keepImages = (if options?(keep_images) = ⥠then true else options?(keep_images))
â r!.logger = (if options?(logger) = ⥠then stderrLogger else options?(logger))
â â part : {images, containers, steps, parallel, report} ⢠part.logger = r!.logger
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 option_rules
ââ OptionRules âââââââââââââââââââââââââââââââââââââ
â rules! : OPTION ⸠RULE
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â rules! = optionRules
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
lib/App/Actions/Runner/Parallel.pm view on Meta::CPAN
# _run_here
# Purpose: Run a job in this process, for a host where fork() failed,
# with its output redirected to its log as a child's would be.
# Entry: $entry.
# Exit status: Returns nothing.
# Side effects: Redirects and restores STDOUT and STDERR; runs the job;
# collects its result.
sub _run_here {
my ($self, $entry) = @_;
my ($saved_stdout, $saved_stderr);
{
no autodie qw(open);
open($saved_stdout, '>&', \*STDOUT) or $self->throw('runner.parallel.dup_failed', { handle => 'STDOUT' });
open($saved_stderr, '>&', \*STDERR) or $self->throw('runner.parallel.dup_failed', { handle => 'STDERR' });
open(STDOUT, '>', $entry->{log}) or $self->throw('runner.file_write_failed', { file => $entry->{log}, error => "$!" });
open(STDERR, '>&', \*STDOUT) or $self->throw('runner.parallel.dup_failed', { handle => 'STDOUT' });
}
STDOUT->autoflush(1);
STDERR->autoflush(1);
# As in a child, the job's plain prints go to its log whatever handle
# the caller had selected; the caller's choice is put back afterwards.
my $selected = select STDOUT;
$self->_run_job($entry);
select $selected;
{
no autodie qw(open);
open(STDOUT, '>&', $saved_stdout) or $self->throw('runner.parallel.restore_failed', { handle => 'STDOUT' });
open(STDERR, '>&', $saved_stderr) or $self->throw('runner.parallel.restore_failed', { handle => 'STDERR' });
}
$self->_collect($entry);
return;
}
# _stream
# Purpose: Show the part of a job's log not shown yet, a line at a time,
# with the job named on each line. A partial last line waits
lib/App/Actions/Runner/Support.pm view on Meta::CPAN
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â s! = rtrim(string(error?))
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 default_logger
ââ DefaultLogger âââââââââââââââââââââââââââââââââââ
â logger! : LogAbstraction
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â â level : LEVEL; m : seq CHAR â¢
â logger!.log(level, m) â stderr' = stderr â m â â¨NEWLINEâ©
â logger!.history = â¨â©
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 null_logger
ââ NullLogger ââââââââââââââââââââââââââââââââââââââ
â logger! : LogAbstraction
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â â level : LEVEL; m : seq CHAR ⢠logger!.log(level, m) â stderr' = stderr
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 trim_error
ââ TrimError âââââââââââââââââââââââââââââââââââââââ
â error? : VALUE
â s! : optional seq CHAR
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â error? = ⥠⨠string(error?) = â¨â© â s! = â¥
â otherwise s! = Describe(error?)
t/archive-crlf.t view on Meta::CPAN
}
return $directory;
}
sub audit {
my ($directory) = @_;
my ($output, $status) = App::Actions::Process::capture(
[ $^X, $script, $directory ],
merge_stderr => 1,
);
$output =~ s/\r\n/\n/g;
return ($output, $status);
}
{
my ($output, $status) = audit(make_archive());
t/archive-crlf.t view on Meta::CPAN
sub run_in {
my ($directory, @command) = @_;
my $original = File::Spec->rel2abs(File::Spec->curdir);
chdir $directory or die "cannot change to '$directory': $!\n";
my ($output, $status, $error);
my $ran = eval {
($output, $status) = App::Actions::Process::capture(
\@command, merge_stderr => 1,
);
1;
};
$error = $@ unless $ran;
chdir $original or die "cannot return to '$original': $!\n";
die $error if defined $error;
return ($output, $status);
}
t/archive-crlf.t view on Meta::CPAN
is(scalar @archives, 1, 'make dist writes one gzipped tarball');
BAIL_OUT('make dist did not write exactly one tarball')
unless @archives == 1;
my $archive = File::Spec->catfile($checkout, $archives[0]);
# make dist runs tar and then gzip. Checking the compressed archive
# with gzip and extracting it with tar's gzip support exercises both
# steps on the bytes the release publishes; comparing every shipped
# file with the CRLF checkout then proves neither step rewrote them.
my $gzip_errors = File::Spec->catfile($work, 'gzip.stderr');
my $gzip_status = App::Actions::Process::run(
[ $gzip, '-t', $archive ],
stdout => File::Spec->devnull,
stderr => $gzip_errors,
);
is($gzip_status, 0, 'gzip accepts the archive make dist wrote')
or diag(-s $gzip_errors ? read_bytes($gzip_errors) : '');
BAIL_OUT('the distribution tarball is not valid gzip')
if $gzip_status;
my $unpacked = tempdir(
'unpacked XXXX', DIR => $work, CLEANUP => 1,
);
my ($untar_output, $untar_status) = run_in(
t/bin/fake-docker view on Meta::CPAN
my $name = $args[-1];
# FAKE_CONTAINER_EXITS names a container that has stopped, and its last
# output is what a run is expected to quote back: FAKE_CONTAINER_LOGS on
# standard output, FAKE_CONTAINER_ERR on standard error, so a capture that
# loses one of the two streams is noticed. A restarting container prints
# the same thing after every attempt, which is why its policy cannot cure
# it, so it quotes the same output.
if (_container_died($name) || _restarting_container($name)) {
my $stdout = $ENV{FAKE_CONTAINER_LOGS};
my $stderr = $ENV{FAKE_CONTAINER_ERR};
# The two streams are written to the same file description when a
# caller merges them, so the buffered one has to go first for the
# lines to keep the order the container printed them in.
local $| = 1;
print $stdout if defined $stdout;
print STDERR $stderr if defined $stderr && length $stderr;
exit 0;
}
# A container that is still up has printed nothing this fake did not see:
# an unset FAKE_CONTAINER_LOGS means no output, which is also how a test
# asks for none - Windows cannot hold an empty string in the environment,
# so setting one there deletes the variable instead.
exit 0;
}
sub useful_text {
my ($text) = @_;
return '' unless defined $text;
$text =~ s/\r\n/\n/g;
return $text;
}
sub run_cli {
my (@args) = @_;
my ($stdout, $stderr, $status) = capture {
system($^X, '-I' . $lib, $script, @args);
};
# $? carries the POSIX-compatible status on Windows too.
return (useful_text($stdout), useful_text($stderr), $status >> 8);
}
sub image_marker {
my ($image) = @_;
(my $name = $image) =~ s/[^A-Za-z0-9_.-]/_/g;
return File::Spec->catfile($ENV{FAKE_DOCKER_STATE}, "image-$name");
}
sub mark_image {
unlike($out, qr/^ unknown:1\b/m,
'an image without a last use is left out');
like($out, qr/^1 image, 117\.7 MB on disk\.$/m,
'the totals count only the images shown');
($out, $err, $exit) = run_cli(
'cache', '--json', '--older-than', '2d', '--docker', $fake_docker,
);
is($exit, 0, 'cache --json --older-than exits 0');
my $document = eval { JSON::PP->new->decode($out) };
ok($document, 'the filtered document decodes') or diag "stderr: $err";
is_deeply(
[ map { $_->{image} } @{ $document->{images} } ],
['old:1'],
'the document holds only the images older than the threshold',
);
is($document->{totals}{images}, 1,
'the document totals only the images shown');
($out, $err, $exit) = run_cli(
'cache', '--older-than', '1y', '--docker', $fake_docker,
# A prune document lists the whole record that remains, not just what the
# filter selected, so a caller can see the newer images the prune kept.
($out, $err, $exit) = run_cli(
'cache', '--prune', '--older-than', '2d', '--json',
'--docker', $fake_docker,
);
is($exit, 0, 'a filtered prune with nothing left to remove exits 0');
my $prune_document = eval { JSON::PP->new->decode($out) };
ok($prune_document, 'the filtered prune document decodes')
or diag "stderr: $err";
is($prune_document->{prune}{removed}, 0,
'the filtered prune removed nothing the second time');
is_deeply(
[ map { $_->{image} } @{ $prune_document->{images} } ],
[ 'new:1', 'unknown:1' ],
'the prune document lists the newer and unknown images it kept',
);
}
{
App::Actions::Cache->new->remember('alpine:3.20');
open my $marker, '>', image_marker('alpine:3.20') or die $!;
print {$marker} 'alpine:3.20';
close $marker;
my ($out, $err, $exit) = run_cli('cache', '--json', '--docker', $fake_docker);
is($exit, 0, 'cache --json exits 0');
is($err, '', 'cache --json writes nothing to standard error');
my $document = eval { JSON::PP->new->decode($out) };
ok($document, 'cache --json prints one JSON object') or diag "stderr: $err";
is($document->{schema_version}, App::Actions::Cache->json_schema_version,
'the document carries the version it was written for');
is($document->{cache_file}, $ENV{ACTION_RUN_CACHE_FILE},
'the document names the record it read');
cmp_ok($document->{generated_at}, '>', 0,
'the document records when it was made');
cmp_ok($document->{generated_at}, '>=', $document->{images}[0]{last_used},
'the image age is measured from generated_at');
is($document->{docker}{bin}, $fake_docker, 'the document names the Docker command');
ok($document->{docker}{reachable}, 'a working daemon is reported as reachable');
is($document->{totals}{size}, 123_456_789, 'the document totals the size');
is($document->{totals}{present}, 1, 'the document counts the present images');
is($document->{totals}{missing}, 0, 'the document counts the missing images');
is($document->{prune}, undef, 'a listing reports no prune');
($out, $err, $exit) = run_cli('cache', '--prune', '--json', '--docker', $fake_docker);
is($exit, 0, 'cache --prune --json exits 0');
is($err, '', 'cache --prune --json writes nothing to standard error');
$document = eval { JSON::PP->new->decode($out) };
ok($document, 'the prune document decodes') or diag "stderr: $err";
cmp_ok($document->{generated_at}, '>', 0,
'the prune document records when it was made');
is($document->{prune}{removed}, 1, 'the document says what the prune removed');
is($document->{prune}{freed}, 123_456_789, 'the document says what the prune freed');
is($document->{prune}{forgotten}, 0, 'the document says nothing was merely forgotten');
is_deeply($document->{prune}{failed}, [], 'the document says every removal worked');
is_deeply($document->{images}, [], 'the prune left no images in the document');
is($document->{totals}{images}, 0, 'the prune left nothing to total');
}
local $ENV{FAKE_IMAGE_REMOVE_FAILURE} = 'postgres:15';
my ($out, $err, $exit) = run_cli(
'cache', '--prune', '--json', '--docker', $fake_docker,
);
is($exit, 1, 'a prune that could not remove an image exits 1');
is($err, '', 'the failure is reported in the document, not on standard error');
my $document = eval { JSON::PP->new->decode($out) };
ok($document, 'the failed-prune document decodes') or diag "stderr: $err";
is($document->{prune}{removed}, 1, 'the document counts the image it removed');
is_deeply($document->{prune}{failed}, ['postgres:15'],
'the document names the image it could not remove');
is_deeply(
[ map { $_->{image} } @{ $document->{images} } ],
['postgres:15'],
'the image that stayed in the record is still listed',
);
my $cache = App::Actions::Cache->new;
like($out, qr/^The Docker daemon is not reachable, so the sizes are unknown\.$/m,
'the listing says why the sizes are unknown');
my ($json_out, $json_err, $json_exit) = run_cli(
'cache', '--json', '--docker', $fake_docker,
);
is($json_exit, 0, 'cache --json still exits 0 with the daemon stopped');
is($json_err, '', 'cache --json says nothing on standard error without a daemon');
my $document = eval { JSON::PP->new->decode($json_out) };
ok($document, 'the document decodes without a daemon') or diag "stderr: $json_err";
ok(!$document->{docker}{reachable}, 'the document says the daemon was not reached');
cmp_ok($document->{generated_at}, '>', 0,
'the document still records when it was made without a daemon');
is(
$document->{images}[0]{age},
$document->{generated_at} - $document->{images}[0]{last_used},
'the age is still known when the daemon is not',
);
is($document->{images}[0]{size}, undef,
'a size that could not be discovered is null');
local $ENV{FAKE_BAD_MOUNT} = $options{bad_mount} ? 1 : 0;
local $ENV{FAKE_MOUNT_FAILURE} = $options{mount_failure} ? 1 : 0;
local $ENV{FAKE_ENTRY_COUNT} = $options{entry_count};
my $check = App::Actions::Check->new(
docker_bin => defined $options{docker_bin} ? $options{docker_bin} : $fake_docker,
directory => $options{directory},
(%{ $options{args} || {} }),
);
my ($stdout, $stderr, $exit) = capture { $check->run };
my $log_text = '';
if (-f $log) {
open my $handle, '<', $log or die $!;
local $/;
$log_text = <$handle>;
close $handle;
$log_text = '' unless defined $log_text;
}
return {
stdout => useful_text($stdout),
stderr => useful_text($stderr),
exit => $exit,
log => useful_text($log_text),
};
}
sub write_file {
my ($path, $contents) = @_;
open my $handle, '>', $path or die $!;
print {$handle} $contents;
$schema_at >= 0 && $schema_at < $verdict_at,
'the schema is named, and before the verdict',
);
my $untold = run_check(args => { schema_line => 0 });
unlike($untold->{stdout}, qr/^ {2}schema/m,
'a caller that prints its own contract can leave the line out');
unlike($ready->{stdout}, qr{/check-project}, 'no project directory is probed unless asked');
unlike($ready->{stdout}, qr/^ {2}remedy/m, 'a ready environment suggests nothing');
is($ready->{stderr}, '', 'nothing is written to standard error');
my $project = tempdir(CLEANUP => 1);
write_file(File::Spec->catfile($project, 'first.txt'), "one\n");
write_file(File::Spec->catfile($project, 'second.txt'), "two\n");
make_path(File::Spec->catdir($project, 'subdirectory'));
my $with_directory = run_check(directory => $project);
is($with_directory->{exit}, 0, 'a project directory is ready');
like($with_directory->{stdout}, qr{-> /check-project: OK \(3 entries\)$}m,
'the project directory is visible inside the container');
sub useful_text {
my ($text) = @_;
return '' unless defined $text;
$text =~ s/\r\n/\n/g;
return $text;
}
sub run_cli {
my (@args) = @_;
my ($stdout, $stderr, $status) = capture {
system($^X, '-I' . $lib, $script, @args);
};
# $? carries the POSIX-compatible status on Windows too.
return (useful_text($stdout), useful_text($stderr), $status >> 8);
}
# Windows pulls one image at a time whatever is asked for, and the preflight
# reports the number the puller was given rather than the number requested.
sub effective_concurrency {
my ($asked) = @_;
return $^O eq 'MSWin32' ? 1 : $asked;
}
is($rc, 0, 'the wrapper receives the Docker arguments');
is($output, "pull|alpine:3.20\n", 'arguments are passed through unchanged');
my (undef, $fail_rc) = $docker->capture_silent('fail');
is($fail_rc, 9, 'a failing wrapper status is reported');
my $silent_rc = $docker->run_silent('fail');
is($silent_rc, 9, 'run_silent reports the wrapper status');
my $run_rc;
my ($stdout, $stderr) = capture {
$run_rc = $docker->run('pull', 'perl:5.38');
};
is($run_rc, 0, 'run executes the wrapper');
like(useful_text($stdout), qr/^pull\|perl:5\.38$/m, 'run streams the wrapper output');
# The program is a file rather than -e code: Win32 Perl does not quote "-e"
# arguments containing double quotes reliably.
my $native_script = File::Spec->catfile($dir, 'native.pl');
open my $native_handle, '>', $native_script or die $!;
binmode $native_handle;
t/fake-docker.t view on Meta::CPAN
# The container's run arguments, as written by "docker run --name".
my $container = File::Spec->catfile($state, 'container-checkjob');
open my $state_handle, '>', $container or die $!;
binmode $state_handle;
my $mount = File::Spec->catdir($root, 'runner') . ':/github/actions-runner';
print {$state_handle} join("\t", '-v', $mount);
close $state_handle;
my $status;
my ($stdout, $stderr) = capture {
local $ENV{FAKE_DOCKER_STATE} = $state;
$status = App::Actions::Process::stream([
$^X, $fake_docker, 'exec', 'checkjob', 'sh', '-c',
'sh /github/actions-runner/scripts/step-1.sh',
]);
};
return ($stdout, $stderr, $status);
}
my ($lf_out, $lf_err, $lf_status) = run_step_script("#!/bin/sh\n# FAKE_EXIT: 3\n");
is($lf_status, 3, 'an LF script is read and emulated');
like(
$lf_out,
qr{executing /github/actions-runner/scripts/step-1\.sh},
'the script being executed is reported',
);
is($lf_err, '', 'an LF script produces no diagnostics');
t/function.t view on Meta::CPAN
}
}
};
subtest 'capture' => sub {
# binmode, so a Windows child writes the CRLF itself rather than its
# text layer turning the \n into a second one.
my ($output, $status) = App::Actions::Process::capture(perl_command('binmode STDOUT; print qq{a\r\nb}; exit 3'));
is($output, "a\nb", 'standard output is captured with CRLF made LF');
is($status, $STATUS{failed}, 'with the status');
($output) = App::Actions::Process::capture(perl_command('print STDERR q{noise}; print q{data}'), quiet_stderr => 1);
is($output, 'data', 'quiet_stderr keeps standard error out');
($output) = App::Actions::Process::capture(perl_command('$|=1; print q{1}; print STDERR q{2}; print q{3}'), merge_stderr => 1);
is($output, '123', 'merge_stderr interleaves the two streams in order');
($output, $status) = App::Actions::Process::capture([ File::Spec->catfile(tempdir(CLEANUP => 1), 'missing') ]);
is_deeply([ $output, $status ], [ '', $STATUS{not_started} ], 'a missing program is no output and 255');
# The command is a list, never a shell string: metacharacters are data.
($output) = App::Actions::Process::capture(perl_command('print join q{|}, @ARGV', 'a;echo pwned', '$(id)', '`x`'));
is($output, 'a;echo pwned|$(id)|`x`', 'shell metacharacters reach the program untouched');
for my $bad (undef, [], 'echo hi', { 0 => 'echo' }) {
throws_ok { App::Actions::Process::capture($bad) } qr/\ANo command given at /, 'refused: ' . explain($bad);
}
t/function.t view on Meta::CPAN
my $codes = App::Actions::Process::run_parallel([ perl_command('exit 3'), perl_command('exit 0'), perl_command('exit 1') ],
concurrency => 2);
returns_ok($codes, { type => 'arrayref' }, 'an array reference');
is_deeply($codes, [ 3, 0, 1 ], 'with each status in the slot of its command');
is_deeply(App::Actions::Process::run_parallel([]), [], 'no commands, no statuses');
is_deeply(App::Actions::Process::run_parallel([ perl_command('exit 3') ], concurrency => 1), [ 3 ], 'one at a time');
my $dir = tempdir(CLEANUP => 1);
my $err = File::Spec->catfile($dir, 'err');
$codes = App::Actions::Process::run_parallel([ [ File::Spec->catfile($dir, 'missing') ], perl_command('exit 0') ],
concurrency => 2, stderr => $err);
is_deeply($codes, [ $STATUS{not_found}, 0 ], 'a program that cannot run is 127, and the others still run');
open my $handle, '<', $err or die $!;
like(do { local $/; <$handle> }, qr/\AUnable to run '\Q$dir\E/, 'and says why, where it was told to');
close $handle;
# Every program writes to the same file; each must add to it, not
# replace what the others wrote, and what was there before is gone.
my $shared = write_file('shared.out', "stale\n", $dir);
for my $concurrency (1, 3) {
App::Actions::Process::run_parallel([ map { perl_command("print qq{$_\\n}") } qw(one two three) ],
t/function.t view on Meta::CPAN
throws_ok {
App::Actions::Process::run_parallel([ perl_command('exit 0'), perl_command('sleep 60') ], concurrency => 2);
} qr/\Ainterrupted$/, 'the exception propagates';
cmp_ok(time - $started, '<', 30, 'and the sleeping child was killed, not waited for');
};
subtest 'run' => sub {
my $dir = tempdir(CLEANUP => 1);
my $out = File::Spec->catfile($dir, 'out');
my $err = File::Spec->catfile($dir, 'err');
is(App::Actions::Process::run(perl_command('print q{o}; print STDERR q{e}; exit 3'), stdout => $out, stderr => $err),
$STATUS{failed}, 'the status');
open my $handle, '<', $out or die $!;
is(do { local $/; <$handle> }, 'o', 'standard output went to its file');
open $handle, '<', $err or die $!;
is(do { local $/; <$handle> }, 'e', 'standard error to its own');
close $handle;
my @warnings;
{
local $SIG{__WARN__} = sub { push @warnings, @_ };
t/function.t view on Meta::CPAN
[qw(stream logs --tail 200 c)],
[qw(stream logs --tail 5 c)],
[qw(run_quiet rm -f c)],
], 'each runs the docker command it is named for, quietly or not');
};
subtest 'container_start_captured and container_log_text' => sub {
my $guard = $fake_process->([ "id\n", 0 ], [ 'error', 125 ], [ "last lines\n", 0 ]);
is_deeply([ $docker->()->container_start_captured('img') ], [ "id\n", 0 ], 'the output and status of the start');
is_deeply([ $docker->()->container_start_captured('img') ], [ 'error', 125 ], 'a failed start says why');
ok($calls[0]{options}{merge_stderr}, 'with standard error merged in');
is($docker->()->container_log_text('c'), "last lines\n", 'the last lines of a log');
is_deeply([ @{ $calls[2]{command} }[ 1 .. 4 ] ], [qw(logs --tail 10 c)], 'ten by default');
is($docker->(dry_run => 1)->container_log_text('c'), '', 'a dry run has no logs');
};
subtest 'container state' => sub {
{
my $guard = $fake_process->([ "true\n", 0 ], [ "false\n", 0 ], [ "true\n", 1 ]);
is($docker->()->container_running('c'), 1, 'running');
is($docker->()->container_running('c'), 0, 'stopped');
t/function.t view on Meta::CPAN
is($printed->(sub { is($docker->(dry_run => 1)->_announce('ps'), 0, 'a dry run does not go ahead') }),
"[dry-run] docker ps\n", 'and says so');
is($printed->(sub { $docker->(dry_run => 1, quiet => 1)->_announce('ps') }), '', 'quietly when asked');
};
subtest 'capture, capture_silent, capture_merged and _capture' => sub {
my $guard = $fake_process->(([ "out\n", 0 ]) x 3);
is_deeply([ $docker->()->capture('ps') ], [ "out\n", 0 ], 'capture returns output and status');
$docker->()->capture_silent('ps');
$docker->()->capture_merged('ps');
is_deeply([ map { [ $_->{options}{quiet_stderr}, $_->{options}{merge_stderr} ] } @calls ], [ [ 0, 0 ], [ 1, 0 ], [ 1, 1 ] ],
'each asks for its own treatment of standard error');
is_deeply([ $docker->(dry_run => 1, quiet => 1)->capture('ps') ], [ '', 0 ], 'a dry run captures nothing and succeeds');
delete local $ENV{TOKEN};
$docker->()->capture('run', '-e', App::Actions::Docker::Variable->new('TOKEN', 'v'));
is($calls[-1]{token}, 'v', 'a captured command gets its variables in the environment too');
ok(!exists $ENV{TOKEN}, 'only while it runs');
};
subtest 'redact' => sub {
my $object = $docker->(secrets => { SHORT => 'abc', LONG => 'abcdef', META => 'a.c*' });
t/function.t view on Meta::CPAN
is(chomp_error(" kept"), ' kept', 'leading white space stays');
is(chomp_error(undef), '', 'undef is empty');
is(chomp_error(App::Actions::Error->new(code => 'x.y', message => 'm', location => "\n")), 'm', 'an object reads as its text');
is(trim_error("lost at lib/X.pm line 3.\n"), 'lost', 'the location is cut off');
is(trim_error(undef), undef, 'undef has no description');
is(trim_error(''), undef, 'nor has an empty error');
keeps_topic(sub { chomp_error("x\n"); trim_error("x\n") }, 'chomp_error and trim_error');
};
subtest 'default_logger and null_logger' => sub {
my $stderr = '';
{
local *STDERR;
open STDERR, '>', \$stderr or die $!;
default_logger()->warn('careful');
default_logger()->error('broken');
null_logger()->error('never seen');
}
is($stderr, "careful\nbroken\n", 'the default logger prints plain lines; the null logger prints nothing');
isa_ok(default_logger(), 'Log::Abstraction');
isnt(default_logger(), default_logger(), 'each call is a fresh logger');
};
subtest 'resolve_env' => sub {
my $expression = App::Actions::Expression->new;
my $env = resolve_env($expression, [ { A => 'a', B => 'x' }, 'not a layer', { B => '${{ env.A }}-b' } ], {});
is_deeply($env, { A => 'a', B => 'a-b' }, 'later layers win, and refer to earlier values');
# A chain longer than one pass settles whatever order keys come in.
t/function.t view on Meta::CPAN
ok(!-e $marker, 'which were killed');
};
subtest '_run_here' => sub {
# fork() can fail (too many processes); the job then runs in this
# process, its output still going to its own log. fork itself is
# compiled in and cannot be mocked, so the fallback is called directly.
my $dir = tempdir(CLEANUP => 1);
my $entry = { plan => { display_name => 'here' }, log => File::Spec->catfile($dir, 'job.log'),
result_path => File::Spec->catfile($dir, 'job.json'), shown => 0, pending => '' };
my $object = $parallel->(run_job => sub { print "inline\n"; print STDERR "to stderr\n"; return { result => 'success', pid => $$ } });
my ($out_before, $err_before) = (fileno(STDOUT), fileno(STDERR));
my $text = $printed->(sub { $object->_run_here($entry) });
is($entry->{result}{pid}, $$, 'the job ran here');
is(App::Actions::Runner::Parallel::_read_from($entry->{log}, 0), "inline\nto stderr\n", 'into its log');
is_deeply([ fileno(STDOUT), fileno(STDERR) ], [ $out_before, $err_before ], 'and STDOUT and STDERR are put back');
is($text, '', 'nothing reached the caller\'s selected handle');
my $unwritable = { %{$entry}, log => File::Spec->catfile($dir, 'no', 'job.log') };
my $error = throws_code(sub { $object->_run_here($unwritable) }, 'runner.file_write_failed', undef,
'a log that cannot be opened is refused');
like($error->message, qr/\AUnable to write '\Q$unwritable->{log}\E': /, 'naming it');
is(fileno(STDOUT), $out_before, 'and STDOUT is still standard output');
};
t/function.t view on Meta::CPAN
subtest '_logger' => sub {
my $object = Local::Logger->new;
is(App::Actions::_logger($object), $object, 'an object is used as it is');
my @lines;
my $array = App::Actions::_logger(\@lines);
isa_ok($array, 'Log::Abstraction');
$array->warn('collected');
ok(scalar(grep { /collected/ } map { ref $_ ? $_->{message} : $_ } @lines), 'an array collects the messages');
my $null = App::Actions::_logger('NULL');
isa_ok($null, 'Log::Abstraction');
my $stderr = '';
{
local *STDERR;
open STDERR, '>', \$stderr or die $!;
$null->error('never seen');
}
is($stderr, '', 'NULL is silent');
isa_ok(App::Actions::_logger({ level => 'error' }), 'Log::Abstraction', 'a hash of options');
throws_ok { App::Actions->new(workflow_file => $file, logger => sub { }) } qr/'logger'/, 'a code reference is not one of the forms';
};
subtest 'the logger argument wins over the configuration' => sub {
my $config = tempdir(CLEANUP => 1);
write_file('app-actions.yml', "App__Actions:\n logger:\n level: debug\n", $config);
local $ENV{CONFIG_DIR} = $config;
my $mine = Local::Logger->new;
is($actions->(logger => $mine)->{logger}, $mine, 'a logger given to new is kept');
t/function.t view on Meta::CPAN
};
subtest 'a French child process message' => sub {
local $ENV{ACTION_RUN_LANG} = 'fr';
my $dir = tempdir(CLEANUP => 1);
my $err = File::Spec->catfile($dir, 'err');
my $missing = File::Spec->catfile($dir, 'missing');
# Two commands at once, so each runs in a child of its own; a single
# command is run in this process, where a missing program is 255.
my $codes = App::Actions::Process::run_parallel([ [ $missing ], perl_command('exit 0') ],
concurrency => 2, stderr => $err);
is_deeply($codes, [ $STATUS{not_found}, 0 ], 'a program that cannot run is still 127');
open my $handle, '<', $err or die $!;
like(do { local $/; <$handle> }, qr/\AImpossible d.ex.cuter '\Q$missing\E' : /, 'and the child says why in French');
close $handle;
# run_parallel opens the output files before it forks, so a file the
# child cannot open is only reached by calling the child's routine in
# a child: a directory is not a file it can write.
my $pid = fork;
die "fork: $!" unless defined $pid;
chdir $repository or die "cannot change to '$repository': $!\n";
my ($output, $status) = App::Actions::Process::capture(
[
'git',
'-c', 'user.name=App::Actions test',
'-c', 'user.email=test@example.com',
'-c', 'commit.gpgsign=false',
@$command,
],
merge_stderr => 1,
);
chdir $cwd or die "cannot change to '$cwd': $!\n";
return ($output, $status);
}
sub run_in_repository {
my (@command) = @_;
my $cwd = File::Spec->rel2abs(File::Spec->curdir);
chdir $repository or die "cannot change to '$repository': $!\n";
my ($output, $exit) = App::Actions::Process::capture(
\@command, merge_stderr => 1,
);
chdir $cwd or die "cannot change to '$cwd': $!\n";
return ($output, $exit);
}
sub run_hook {
my (@args) = @_;
t/integration.t view on Meta::CPAN
my ($daemon) = @_;
return [ map { $_->[3] } grep { $_->[0] eq 'run' && $_->[1] eq '-d' } @{ commands($daemon) } ];
}
# Runs $code, capturing what it prints, and returns that with its result.
sub captured {
my ($code) = @_;
my $result;
my ($stdout, $stderr) = capture { $result = $code->() };
s/\r\n/\n/g for $stdout, $stderr;
return { result => $result, stdout => $stdout, stderr => $stderr };
}
# The result each job had, from the run's summary.
sub summary {
my ($stdout) = @_;
my ($block) = $stdout =~ /^=== Workflow summary ===\n(.*?)^Workflow /ms;
return { map { /\A {2}(.+?)\s{2,}(\S+)\z/ ? ($1, $2) : () } split /\n/, defined $block ? $block : '' };
}
t/integration.t view on Meta::CPAN
# logger rather than to standard error.
my @logger;
my $actions = actions(project($CASCADE), logger => \@logger);
my $run = with_daemon(daemon(), {}, sub { captured(sub { $actions->run }) });
verbose_diag('cascade', $run);
is($run->{result}, $config{exit}{failure}, 'the run reports that a job failed');
is_deeply(summary($run->{stdout}), { build => 'failure', test => 'skipped', docs => 'success' },
'the job that needs the failed one is skipped, and the other one still runs');
like(messages(\@logger, 'error')->[0], qr/\b$config{step_status}\b/, 'the logger is told the status the step exited with');
is($run->{stderr}, '', 'and nothing is printed to standard error');
};
subtest 'preflight prepares the images and returns a valid document' => sub {
# preflight runs the check and the image preparation a run makes before
# its first job, without starting one. Strategy: the first preflight
# pulls, the second finds the image present, and both documents match
# the published schema.
my $actions = actions(project($PASSING));
my $daemon = daemon();
my $schema = App::Actions->json_schema('preflight');
t/integration.t view on Meta::CPAN
my ($workflow, $docker) = @ARGV;
my $schema = App::Actions->json_schema('check');
my $exit = App::Actions->new(workflow_file => $workflow, docker_bin => $docker, dry_run => 1, quiet => 1, logger => 'NULL')->run;
print "$exit $schema->{title}\n";
PERL
my %seen;
for my $mask (0 .. 2**@optional - 1) {
my @hidden = map { $optional[$_] } grep { $mask & (1 << $_) } 0 .. $#optional;
my @switches = @hidden ? ('-MTest::Without::Module=' . join(',', @hidden)) : ();
my ($stdout, $stderr, $status) = capture {
system($^X, "-I$LIB", @switches, $program, $project->{workflow}, $FAKE_DOCKER);
};
my $label = @hidden ? 'without ' . join(', ', @hidden) : 'with everything installed';
is($status, 0, "a run $label works") or diag($stderr);
$seen{$stdout}++;
}
is(scalar keys %seen, 1, 'and every combination gives the same answer');
verbose_diag('outcomes', \%seen);
};
done_testing();
t/locales.t view on Meta::CPAN
local $ENV{ACTION_RUN_LANG} = 'de';
throws_ok { App::Actions::Workflow->load($missing_workflow) }
qr/^Die Workflow-Datei '\Q$missing_workflow\E' existiert nicht/,
'ACTION_RUN_LANG, not the locale, chooses the language';
});
diag("$locale is not installed here; the C locale was in force") unless $applied;
# The command a user runs: the error must still be raised, reported
# on standard error and given the infrastructure exit status.
local $ENV{LC_ALL} = $locale;
my ($stdout, $stderr, $status) = capture {
system($^X, "-I$lib", $script, $missing_workflow);
};
is($status >> 8, 2, "action-run exits 2 for a missing workflow under $locale");
like($stderr, qr/^action-run: Workflow file '.*absent\.yml' does not exist$/m,
'and says why on standard error');
};
}
done_testing();
sub useful_text {
my ($text) = @_;
return '' unless defined $text;
$text =~ s/\r\n/\n/g;
return $text;
}
sub run_cli {
my (@args) = @_;
my ($stdout, $stderr, $status) = capture {
system($^X, '-I' . $lib, $script, @args);
};
return (useful_text($stdout), useful_text($stderr), $status >> 8);
}
sub write_file {
my ($path, $text) = @_;
open my $handle, '>', $path or die "Unable to write '$path': $!";
binmode $handle;
print {$handle} $text;
close $handle or die "Unable to write '$path': $!";
like($out, qr/\Q20261018-090000-def456\E\s+job-1-test\.log\s+4\.0 KB/,
'the command lists the old log');
unlike($out, qr/\Q20261021-140000-abc123\E/,
'the command leaves out the newer log');
like($out, qr/^1 log, 4\.0 KB on disk\.$/m,
'the command totals only the logs it selected');
($out, $err, $exit) = run_cli('logs', '--json', '--older-than', '1d');
is($exit, 0, 'logs --json --older-than exits 0');
my $document = eval { JSON::PP->new->decode($out) };
ok($document, 'the filtered document decodes') or diag "stderr: $err";
is_deeply(
[ map { $_->{name} } @{ $document->{logs} } ],
['job-1-test.log'],
'the document holds only the old log',
);
is($document->{totals}{logs}, 1,
'the document totals only the selected log');
is($document->{totals}{size}, 4096,
'the document totals only the selected bytes');
ok(-d $new_run, 'the run directory holding the newer log is still there');
# As with the cache, a filtered prune document shows the whole record that
# remains, not just the filter's empty selection the second time.
($out, $err, $exit) = run_cli(
'logs', '--prune', '--json', '--older-than', '1d',
);
is($exit, 0, 'a filtered prune with nothing left to remove exits 0');
my $prune_document = eval { JSON::PP->new->decode($out) };
ok($prune_document, 'the filtered prune document decodes')
or diag "stderr: $err";
is($prune_document->{prune}{removed}, 0,
'the filtered prune removed nothing the second time');
is_deeply(
[ map { $_->{name} } @{ $prune_document->{logs} } ],
['job-1-test.log'],
'the prune document lists the newer log it kept',
);
}
{
$ENV{ACTION_RUN_LOG_DIR}, '20261021-130000-abc123',
);
make_path($json_run);
write_file(File::Spec->catfile($json_run, 'job-1-test.log'), 'a' x 512);
my ($out, $err, $exit) = run_cli('logs', '--json');
is($exit, 0, 'logs --json exits 0');
is($err, '', 'logs --json writes nothing to standard error');
my $document = eval { JSON::PP->new->decode($out) };
ok($document, 'logs --json prints one JSON object') or diag "stderr: $err";
is($document->{schema_version}, App::Actions::Logs->json_schema_version,
'the document carries the version it was written for');
is($document->{logs_directory}, $ENV{ACTION_RUN_LOG_DIR},
'the document names the directory it read');
cmp_ok($document->{generated_at}, '>', 0,
'the document records when it was made');
is($document->{logs}[0]{run}, '20261021-130000-abc123', 'the run is named');
is($document->{logs}[0]{name}, 'job-1-test.log', 'the log is named');
is($document->{logs}[0]{size}, 512, 'the size is bytes rather than text');
ok(defined $document->{logs}[0]{age}, 'the age is in seconds in the document');
is($document->{totals}{runs}, 1, 'the document counts the runs');
is($document->{totals}{logs}, 1, 'the document counts the logs');
is($document->{totals}{size}, 512, 'the document totals the bytes');
is($document->{prune}, undef, 'a listing has no prune report');
($out, $err, $exit) = run_cli('logs', '--prune', '--json');
is($exit, 0, 'logs --prune --json exits 0');
is($err, '', 'logs --prune --json writes nothing to standard error');
$document = eval { JSON::PP->new->decode($out) };
ok($document, 'the prune document decodes') or diag "stderr: $err";
ok(defined $document->{generated_at}, 'the prune document records when it was made');
is($document->{prune}{removed}, 1, 'the document says what the prune removed');
is($document->{prune}{freed}, 512, 'the document says what the prune freed');
is_deeply($document->{prune}{failed}, [], 'the document says every removal worked');
is_deeply($document->{logs}, [], 'the prune left no logs in the document');
ok(!-e $json_run, 'the command removed the run directory');
}
{
# A document that does not match the schema is not returned, even though
t/process.t view on Meta::CPAN
'a shell command is quoted as one argument');
my $hello = write_program("print \"hello\\n\";\n");
my ($output, $status) = App::Actions::Process::capture([ $^X, $hello ]);
is($status, 0, 'capture reports success');
is($output, "hello\n", 'capture returns standard output');
my $both = write_program("print \"out\\n\";\nprint STDERR \"noise\\n\";\n");
($output, $status) = App::Actions::Process::capture(
[ $^X, $both ],
quiet_stderr => 1,
);
is($output, "out\n", 'quiet_stderr still captures standard output');
is($status, 0, 'quiet_stderr reports success');
# A caller that builds a message from a command's output wants the child's
# standard error in it too, in the order the child wrote it and without
# escaping to the caller's own streams.
my $both_streams = write_program(
"\$| = 1;\nprint \"out\\n\";\nprint STDERR \"err\\n\";\n"
);
my ($merged_out, $merged_status);
my ($unexpected) = capture {
($merged_out, $merged_status) = App::Actions::Process::capture(
[ $^X, $both_streams ],
merge_stderr => 1,
);
};
is($merged_status, 0, 'merge_stderr reports success');
is($merged_out, "out\nerr\n", 'merge_stderr captures both streams in the order written');
is($unexpected, '', 'the merged streams do not also reach the caller');
my $crlf = write_program("binmode STDOUT;\nprint \"a\\r\\nb\\r\\n\";\n");
($output, $status) = App::Actions::Process::capture([ $^X, $crlf ]);
is($output, "a\nb\n", 'CRLF output is normalised on every platform');
my $failing = write_program("exit 7;\n");
($output, $status) = App::Actions::Process::capture([ $^X, $failing ]);
is($status, 7, 'the exit code is reported');
t/process.t view on Meta::CPAN
my $spaced_dir = File::Spec->catdir(tempdir(CLEANUP => 1), 'with space');
make_path($spaced_dir);
my $spaced = write_program("print \"spaced\\n\";\n", directory => $spaced_dir);
my ($spaced_out, $spaced_status) = App::Actions::Process::capture([ $^X, $spaced ]);
is($spaced_status, 0, 'a script below a path with spaces runs');
is($spaced_out, "spaced\n", 'the output of a script below a path with spaces is captured');
# Capturing must not disturb an enclosing Capture::Tiny, and output buffered
# before the command has to be flushed first so that the order is preserved.
my $inner = write_program("print \"inner\\n\";\n");
my ($stdout, $stderr) = capture {
print "before\n";
my ($inner_out) = App::Actions::Process::capture([ $^X, $inner ]);
is($inner_out, "inner\n", 'the command output is captured inside Capture::Tiny');
print "after\n";
};
is($stdout, "before\nafter\n", 'the enclosing capture keeps its output in order');
is($stderr, '', 'standard error is left alone');
# Several commands can run together. Their results keep the order of the
# commands even when a later one finishes first, and their output goes
# straight to the caller's streams.
my $marks = File::Spec->catfile(tempdir(CLEANUP => 1), 'marks.txt');
my $timed = write_program(<<'PERL');
use Time::HiRes qw(time sleep);
my ($marks, $name, $delay, $status) = @ARGV;
print "$name\n";
for my $phase ('start', 'end') {
t/process.t view on Meta::CPAN
# built without a command's noise ending up in it.
my $redirected;
my ($leaked) = capture {
$redirected = App::Actions::Process::run_parallel(
[
[ $^X, $timed, $marks, 'quiet-one', 0.05, 0 ],
[ $^X, $timed, $marks, 'quiet-two', 0.05, 4 ],
],
concurrency => 2,
stdout => File::Spec->devnull,
stderr => File::Spec->devnull,
);
};
is_deeply($redirected, [ 0, 4 ], 'redirected commands still report their status');
is($leaked, '', 'redirected output does not reach the caller streams');
SKIP: {
skip 'commands run one at a time where fork() is not used', 3
if $^O eq 'MSWin32';
ok(
t/real-docker-preflight.t view on Meta::CPAN
close $handle;
my $actions = App::Actions->new(
workflow_file => $file,
project_dir => $project,
docker_bin => $docker,
image => $image,
%options,
);
my ($stdout, $stderr, $exit) = capture { $actions->run };
return {
stdout => useful_text($stdout),
stderr => useful_text($stderr),
exit => $exit,
project => $project,
};
}
# The containers a run starts are named action-run-*, so they can be listed
# and compared with what was there beforehand. Every state counts: a
# container that stopped instead of being removed is still one the run left
# behind. A developer machine may already have one from an interrupted run;
# that is worth saying, but it is not this test's leak.
t/real-docker-preflight.t view on Meta::CPAN
- run: echo never
YAML
is($failed_probe->{exit}, 2, 'a probe that cannot run its container stops the run');
like($failed_probe->{stdout}, qr/^Result: not ready \(1 problem\)$/m,
'the check reports the environment as not ready');
like($failed_probe->{stdout}, qr/probe container failed \(exit \d+\)/,
'the problem is the probe container, not a guess');
like($failed_probe->{stdout}, qr/^ {2}remedy\s+\S/m,
'the problem comes with a remedy');
like($failed_probe->{stderr}, qr/the environment is not ready/,
'the run says the environment is at fault');
like($failed_probe->{stderr}, qr/--skip-check/,
'the run points at --skip-check');
unlike($failed_probe->{stdout}, qr/==> Job:/, 'no job starts in a broken environment');
# Every image the job will need is prepared first, including the service
# image and the image of a docker:// action. --pull makes the pulls visible
# even when Docker has the images cached.
my $with_images = <<"YAML";
name: Prepared images
on: push
jobs:
t/real-docker-preflight.t view on Meta::CPAN
# path that exists in it: a bare "hello" is looked up on PATH and is
# not there, which is a failed action rather than a busy one.
args: /hello
- run: echo after
YAML
my $prepared = run_workflow($with_images, pull => 1);
if ($prepared->{exit} != 0) {
diag "stdout:\n$prepared->{stdout}";
diag "stderr:\n$prepared->{stderr}" if length $prepared->{stderr};
}
is($prepared->{exit}, 0, 'a workflow with service and action images runs');
like($prepared->{stdout}, qr/Workflow succeeded/, 'the run reports success');
unlike($prepared->{stdout}, qr/^Result: ready$/m,
'a passing probe prints no report');
my $job_start = index($prepared->{stdout}, '==> Job: test');
ok($job_start > 0, 'the job starts');
t/real-docker-preflight.t view on Meta::CPAN
broken:
image: $missing_image
steps:
- run: echo never
YAML
my $broken = run_workflow($broken_service);
if ($broken->{exit} != 2) {
diag "stdout:\n$broken->{stdout}";
diag "stderr:\n$broken->{stderr}" if length $broken->{stderr};
}
is($broken->{exit}, 2, 'an unpullable service image stops the run');
like(
$broken->{stderr},
qr/cannot prepare the image '\Q$missing_image\E', needed by service 'broken' of job 'test'/,
'the failure names the image, the service, and the job',
);
unlike($broken->{stderr}, qr/ at \S+ line \d+/,
'the failure reads as a sentence, not a source location');
unlike($broken->{stdout}, qr/==> Job:/, 'no job container is started');
# Nothing this test started is still running, on Windows or anywhere else.
my %already = map { $_ => 1 } @$before;
my @leftovers = grep { !$already{$_} } @{ action_run_containers($daemon) };
is_deeply(\@leftovers, [], 'no action-run containers are left behind');
# A failure here is only actionable with the containers named, not with the
# bare IDs the assertion prints.
t/real-docker.t view on Meta::CPAN
close $handle;
my $actions = App::Actions->new(
workflow_file => $workflow_file,
project_dir => $project,
docker_bin => $docker,
image => $image,
verbose => 1,
);
my ($stdout, $stderr, $exit) = capture { $actions->run };
$stdout = useful_text($stdout);
$stderr = useful_text($stderr);
diag "stdout:\n$stdout" if $exit != 0;
diag "stderr:\n$stderr" if length $stderr;
is($exit, 0, 'the workflow succeeds against real Docker');
like($stdout, qr/Workflow succeeded/, 'the run reports success');
like($stdout, qr/^ {2}test\s+success$/m, 'the job summary reports success');
# Trailing carriage returns in a script would break these two, so they also
# guard the LF line endings written for the container.
unlike($stdout, qr/Check the environment \(skipped\)/,
'GITHUB_ENV reaches later steps through a real bind mount');
unlike($stdout, qr/Check the output \(skipped\)/,
t/real-docker.t view on Meta::CPAN
my $smoke_exit;
my ($smoke_out, $smoke_err) = capture {
$smoke_exit = App::Actions::Process::stream([
$^X, $smoke, '--docker', $docker, '--image', $image, '--directory', $project,
]);
};
$smoke_out = useful_text($smoke_out);
diag "smoke stdout:\n$smoke_out" if $smoke_exit != 0;
diag "smoke stderr:\n" . useful_text($smoke_err) if length $smoke_err;
is($smoke_exit, 0, 'the smoke script passes against the real daemon');
like($smoke_out, qr/^Result: smoke test passed$/m, 'the smoke script reports a pass');
like($smoke_out, qr/^ {2}workflow\s+one job/m, 'the smoke script reports the workflow it runs');
# Nothing this test started should be left running, the smoke run included.
my %already = map { $_ => 1 } @$before;
my @leftovers = grep { !$already{$_} } @{ _action_run_containers($daemon) };
is_deeply(\@leftovers, [], 'no action-run containers are left behind');
local $ENV{FAKE_INSPECT_FAILURE} = $options{fake_inspect_failure} ? 1 : 0;
my $actions = App::Actions->new(
workflow_file => $workflow_file,
project_dir => $project,
docker_bin => $fake_docker,
image => 'ubuntu:latest',
actions_options(%options),
);
my ($stdout, $stderr, $exit) = capture { $actions->run };
$stdout = useful_text($stdout);
$stderr = useful_text($stderr);
my ($log_text, $argv_text) = map { slurp_if_present($_) } ($log, "$log.argv");
return {
stdout => $stdout,
stderr => $stderr,
exit => $exit,
log => $log_text,
argv_log => $argv_text,
project => $project,
state => $state,
};
}
# A preflight run returns its outcome as data rather than reporting it, so a
# CI job can assert on the images instead of reading the pulls.
my $actions = App::Actions->new(
workflow_file => $workflow_file,
project_dir => $project,
docker_bin => $fake_docker,
image => 'ubuntu:latest',
actions_options(%options),
);
my $result;
my ($stdout, $stderr) = capture {
$result = $actions->preflight(json => $options{json});
};
my $log_text = '';
if (-f $log) {
open my $log_handle, '<', $log or die $!;
local $/;
$log_text = <$log_handle>;
close $log_handle;
$log_text = '' unless defined $log_text;
}
return {
result => $result,
stdout => useful_text($stdout),
stderr => useful_text($stderr),
log => $log_text,
project => $project,
};
}
my $matrix_yaml = <<'YAML';
name: Matrix
on: push
jobs:
test:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Fail
run: |
FAKE_EXIT: 7
YAML
is($failure->{exit}, 1, 'failing workflow exits 1');
like($failure->{stderr}, qr/step exited with status 7/, 'step failure is reported');
like($failure->{log}, qr/^rm\t-f\t/m, 'failed runs still clean up containers');
# Warnings and errors go through a Log::Abstraction logger. The default one
# prints them to standard error, as above; a logger given to the run gets
# them instead, with their level, and 'NULL' drops them.
my $failing_workflow = <<'YAML';
name: Failure
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Fail
run: |
FAKE_EXIT: 7
YAML
my @logged;
my $captured = run_workflow($failing_workflow, logger => \@logged);
is($captured->{exit}, 1, 'a run with its own logger still fails the job');
unlike($captured->{stderr}, qr/step exited with status 7/,
'the step failure goes to the given logger, not standard error');
ok(
(grep { $_->{level} eq 'error' && $_->{message} =~ /step exited with status 7/ } @logged),
'and is logged at the error level',
) or diag explain \@logged;
my $silenced = run_workflow($failing_workflow, logger => 'NULL');
is($silenced->{exit}, 1, 'a run with logging turned off still fails the job');
unlike($silenced->{stderr}, qr/step exited with status 7/, "logger => 'NULL' drops the message");
# A logger in the configuration replaces the default, and a logger argument
# replaces that: Object::Configure would let the configuration win over an
# argument other than an array.
{
my $config_dir = tempdir(CLEANUP => 1);
my $log_file = File::Spec->catfile($config_dir, 'action-run.log');
open my $config, '>', File::Spec->catfile($config_dir, 'local.yaml') or die $!;
print {$config} "---\nApp__Actions:\n logger:\n file: $log_file\n level: debug\n";
close $config;
local $ENV{CONFIG_DIR} = $config_dir;
my $configured = run_workflow($failing_workflow);
unlike($configured->{stderr}, qr/step exited with status 7/,
'a configured logger takes the message off standard error');
like(slurp_if_present($log_file), qr/step exited with status 7/, 'and writes it where it was told to');
my @argument_log;
unlink $log_file;
run_workflow($failing_workflow, logger => \@argument_log);
ok((grep { $_->{message} =~ /step exited with status 7/ } @argument_log),
'a logger argument wins over the configured one');
is(slurp_if_present($log_file), '', 'which then logs nothing');
- run: echo never
YAML
fake_container_exits => '-svc-',
fake_container_status => 7,
fake_container_logs => "starting up\nport 5432 is already in use\n",
fake_container_err => "fatal: could not bind\n",
);
is($stopped_service->{exit}, 2, 'a service that stops is an infrastructure failure');
like(
$stopped_service->{stderr},
qr/^action-run: Service 'helper' did not stay running \(exit 7\);/m,
'the failure names the service and the status it exited with',
);
like($stopped_service->{stderr}, qr/^ {2}starting up$/m,
'the service output is quoted');
like($stopped_service->{stderr}, qr/^ {2}port 5432 is already in use$/m,
'the last lines are quoted, not the first ones');
like($stopped_service->{stderr}, qr/^ {2}fatal: could not bind$/m,
'the service standard error is quoted too');
unlike($stopped_service->{stderr}, qr/\s+at\s+\S+ line \d+/,
'the failure reads as a sentence, not a source location');
unlike($stopped_service->{stdout}, qr/--- Step:/,
'no step runs when its service has stopped');
# A service that said nothing at all is reported as silent rather than being
# left with an empty quotation.
my $silent_service = run_workflow(
<<'YAML',
name: Silent service
on: push
image: postgres:16
steps:
- run: echo never
YAML
fake_container_exits => '-svc-',
fake_container_logs => '',
);
is($silent_service->{exit}, 2, 'a silent service is still a failure');
like(
$silent_service->{stderr},
qr/did not stay running \(exit 1\); it printed nothing/m,
'a service that printed nothing says so',
);
# A container the daemon will not describe, because it has already gone, is
# not the same as one that exited 0: the message says the status is unknown
# rather than inventing one.
my $unreadable = run_workflow(
<<'YAML',
name: Unreadable service
steps:
- run: echo never
YAML
fake_container_exits => '-svc-',
fake_container_logs => "gone before it could be asked\n",
fake_inspect_failure => 1,
);
is($unreadable->{exit}, 2, 'an unreadable service status is a failure');
like(
$unreadable->{stderr},
qr/did not stay running \(its exit status could not be read\); its last output was:/m,
'a status that cannot be read is reported as unknown, not guessed',
);
like($unreadable->{stderr}, qr/^ {2}gone before it could be asked$/m,
'the output is still quoted when the status is unknown');
# A service whose restart policy brings it back is not serving, even though
# Docker reports it as running between attempts: asking only whether it is
# running would let the steps talk to a container that keeps dying.
my $restarting_service = run_workflow(
<<'YAML',
name: Restarting service
on: push
jobs:
steps:
- run: echo never
YAML
fake_container_restarts => '-svc-',
fake_restart_count => 3,
fake_container_logs => "starting up\nport 5432 is already in use\n",
);
is($restarting_service->{exit}, 2, 'a service that keeps restarting is an infrastructure failure');
like(
$restarting_service->{stderr},
qr/^action-run: Service 'helper' is restarting \(restart count 3\);/m,
'the failure names the service and how often it was restarted',
);
like($restarting_service->{stderr}, qr/^ {2}port 5432 is already in use$/m,
'the output the restarts repeat is quoted');
unlike($restarting_service->{stdout}, qr/--- Step:/,
'no step runs against a service that is restarting');
unlike($restarting_service->{log}, qr/^run\t-d\t.*-job-/m,
'no job container is started for a restarting service');
like($restarting_service->{log}, qr/^rm\t-f\taction-run-\S+-svc-\S+$/m,
'the restarting service is removed');
# A service caught between attempts is described as restarting rather than as
# one that never stayed up, which is what its restart policy is doing.
- run: echo never
YAML
fake_container_restarts => '-svc-',
fake_restart_count => 0,
fake_container_state => 'restarting',
fake_container_logs => "could not connect to the server\n",
);
is($backing_off->{exit}, 2, 'a service backing off is an infrastructure failure');
like(
$backing_off->{stderr},
qr/^action-run: Service 'helper' is restarting; its last output was:/m,
'a service between attempts is described as restarting',
);
like($backing_off->{stderr}, qr/^ {2}could not connect to the server$/m,
'the output that made it give up is quoted');
# A restart that happens while the job runs is caught too: the service was
# serving when it was started, so only the check after the steps can see it.
my $restarted_later = run_workflow(
<<'YAML',
name: Restarted during the run
on: push
jobs:
test:
fake_container_restarts => '-svc-',
fake_restart_count => 2,
fake_restart_after_exec => 1,
fake_container_logs => "server closed the connection unexpectedly\n",
);
is($restarted_later->{exit}, 2, 'a service that restarts during the run fails it');
like($restarted_later->{stdout}, qr/--- Step: /,
'the step had already run when the restart was noticed');
like(
$restarted_later->{stderr},
qr/^action-run: Service 'helper' is restarting \(restart count 2\);/m,
'the late restart is reported with its count',
);
like($restarted_later->{stderr}, qr/^ {2}server closed the connection unexpectedly$/m,
'the late restart quotes what the container printed');
# The job container is held to the same standard. A container that stops
# before any step has run is an infrastructure failure, and its status and last
# output are what tell a bad image from a bad entrypoint or a missing command.
my $stopped_job = run_workflow(
<<'YAML',
name: Stopped job container
on: push
jobs:
- run: echo never
YAML
fake_container_exits => '-job-',
fake_container_status => 7,
fake_container_logs => "could not set up the runner\n",
fake_container_err => "fatal: no such entrypoint\n",
);
is($stopped_job->{exit}, 2, 'a job container that stops is an infrastructure failure');
like(
$stopped_job->{stderr},
qr/^action-run: Job container '\S+' did not stay running \(exit 7\);/m,
'the failure names the job container and its exit status',
);
like($stopped_job->{stderr}, qr/^ {2}could not set up the runner$/m,
'the job container output is quoted');
like($stopped_job->{stderr}, qr/^ {2}fatal: no such entrypoint$/m,
'the job container standard error is quoted too');
unlike($stopped_job->{stderr}, qr/\s+at\s+\S+ line \d+/,
'the failure reads as a sentence, not a source location');
unlike($stopped_job->{stdout}, qr/--- Step:/,
'no step runs in a job container that stopped');
like(
$stopped_job->{log},
qr/^rm\t-f\taction-run-\S+-job-\S+$/m,
'the job container that stopped is removed',
);
# A job container that printed nothing is reported as silent rather than left
image: alpine:3.20
steps:
- run: echo never
YAML
fake_container_exits => '-job-',
fake_container_logs => '',
);
is($silent_job->{exit}, 2, 'a silent job container is still a failure');
like(
$silent_job->{stderr},
qr/Job container '\S+' did not stay running \(exit 1\); it printed nothing/m,
'a job container that printed nothing says so',
);
# A container the daemon refuses to start has no output of its own to quote:
# the daemon's message is the only account of the failure, and it names the
# part of the request it could not use. Quoting it back with that name is what
# tells a missing image from an entrypoint the image does not have.
my $refused_job = run_workflow(
<<'YAML',
- run: echo never
YAML
fake_start_failure => '-job-',
fake_start_error => "Unable to find image 'alpine:3.20' locally\n"
. "docker: Error response from daemon: No such image: alpine:3.20\n",
);
is($refused_job->{exit}, 2,
'a job container the daemon will not start is an infrastructure failure');
like(
$refused_job->{stderr},
qr/^action-run: Job container '\S+' could not be started \(exit 125\); at fault: the image 'alpine:3\.20'; the daemon said:$/m,
'the failure names the container, the status and the image at fault',
);
like($refused_job->{stderr}, qr/^ {2}Unable to find image 'alpine:3\.20' locally$/m,
'what the daemon said is quoted');
like(
$refused_job->{stderr},
qr/^ {2}docker: Error response from daemon: No such image: alpine:3\.20$/m,
'every line the daemon said is quoted, not just the first',
);
unlike($refused_job->{stderr}, qr/\s+at\s+\S+ line \d+/,
'the failure reads as a sentence, not a source location');
unlike($refused_job->{stdout}, qr/--- Step:/,
'no step runs in a container that would not start');
like(
$refused_job->{log},
qr/^rm\t-f\taction-run-\S+-job-\S+$/m,
'the container the daemon would not start is removed',
);
# The same status with another message is another fault: a runtime that cannot
steps:
- run: echo never
YAML
fake_start_failure => '-job-',
fake_start_exit => 127,
fake_start_error => 'docker: Error response from daemon: failed to create task for container: '
. 'exec: "/bin/sh": stat /bin/sh: no such file or directory: unknown.' . "\n",
);
like(
$no_entrypoint->{stderr},
qr/could not be started \(exit 127\); at fault: the entrypoint '\/bin\/sh'; the daemon said:$/m,
'a missing entrypoint is named, with the status that reported it',
);
like(
$no_entrypoint->{stderr},
qr/^ {2}docker: Error response from daemon: .*stat \/bin\/sh: no such file or directory/m,
'the runtime message that named it is quoted too',
);
# A daemon that said nothing, and one whose message names nothing this run can
# point at, are reported as they are rather than being given a verdict.
my $silent_start = run_workflow(
<<'YAML',
name: Silent start failure
on: push
container:
image: alpine:3.20
steps:
- run: echo never
YAML
fake_start_failure => '-job-',
fake_start_error => '',
);
like(
$silent_start->{stderr},
qr/Job container '\S+' could not be started \(exit 125\); the daemon said nothing$/m,
'a start the daemon refused silently says so',
);
unlike($silent_start->{stderr}, qr/at fault:/,
'no fault is invented when the daemon said nothing');
my $unrecognised_start = run_workflow(
<<'YAML',
name: Unrecognised start failure
on: push
jobs:
test:
runs-on: ubuntu-latest
container:
image: alpine:3.20
steps:
- run: echo never
YAML
fake_start_failure => '-job-',
fake_start_error => "docker: Error response from daemon: the daemon went away\n",
);
like($unrecognised_start->{stderr},
qr/could not be started \(exit 125\); the daemon said:$/m,
'a message that names nothing recognised is quoted without a verdict');
like($unrecognised_start->{stderr},
qr/^ {2}docker: Error response from daemon: the daemon went away$/m,
'the daemon output is still quoted');
unlike($unrecognised_start->{stderr}, qr/at fault:/,
'no part of the request is blamed without the daemon naming it');
my $docker_action = run_workflow(<<'YAML');
name: Docker action
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Action
run: echo after
YAML
SKIP: {
skip 'the fake daemon cannot run a container command on this host', 5
if $^O eq 'MSWin32';
is($failing_action->{exit}, 1, 'a docker action that exits non-zero fails the run');
like($failing_action->{stdout}, qr/^about-to-fail$/m,
'the failing action ran, and its output came back');
like($failing_action->{stderr}, qr/docker action exited with status 3/,
'the failure says what the action exited with');
unlike($failing_action->{stdout}, qr/^after$/m,
'the step after a failed action does not run');
like($failing_action->{log}, qr/^rm\t-f\t/m,
'a failed action still cleans up its container');
}
my $no_bash = run_workflow(<<'YAML', fake_no_bash => 1);
name: No bash
on: push
test:
runs-on: ubuntu-latest
container:
image: alpine:3.20
steps:
- run: echo hello
shell: bash
YAML
is($explicit_bash->{exit}, 1, 'explicit bash fails when bash is absent');
like($explicit_bash->{stderr}, qr/Shell 'bash' is not available/,
'missing explicit shell is reported');
my $strict = run_workflow(<<'YAML', strict_actions => 1);
name: Strict
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: some/unknown-action@v1
YAML
is($strict->{exit}, 1, 'strict mode fails on an unknown action');
like($strict->{stderr}, qr/skipped: remote JavaScript and composite actions are not supported/,
'strict mode explains the unsupported action');
my $keep = run_workflow(<<'YAML', keep => 1);
name: Keep
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- run: echo hello
test:
name: Auth ${{ secrets.TOKEN }}
runs-on: ubuntu-latest
steps:
- run: echo "${{ secrets.TOKEN }}"
YAML
is($redacted->{exit}, 0, 'secret dry-run succeeds');
like($redacted->{stdout}, qr/\*\*\*/, 'secret values are redacted in dry-run scripts');
unlike($redacted->{stdout}, qr/super-secret-value/, 'secret values do not appear in output');
unlike($redacted->{stderr}, qr/super-secret-value/, 'secret values do not appear in error output');
# A process's arguments can be read by every user of the host, so the job's
# variables reach docker through its environment instead: the container is
# given the secret, and no docker command line carries it.
my $hidden = run_workflow(<<'YAML', secrets => { TOKEN => 'super-secret-value' });
name: Hidden
on: push
jobs:
test:
runs-on: ubuntu-latest
test:
runs-on: ubuntu-latest
steps:
- uses: ./.github/actions/js
YAML
'.github/actions/js/action.yml' => $js_action,
'.github/actions/js/main.js' => "// FAKE_OUTPUT: answer=42\n",
}, fake_no_node => 1);
is($no_node->{exit}, 1, 'a JavaScript action without node fails');
like($no_node->{stderr}, qr/needs Node\.js/, 'missing node is explained');
my $missing_action = run_workflow(<<'YAML');
name: Missing action
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: ./.github/actions/absent
YAML
is($missing_action->{exit}, 1, 'a missing local action fails');
like($missing_action->{stderr}, qr/Local action .* does not exist/,
'a missing local action is reported');
unlike($missing_action->{stderr}, qr/cannot prepare the image/,
'the preflight leaves a missing action to the step that uses it');
my $escaping_action = run_workflow(<<'YAML');
name: Escaping action
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: ../../etc
YAML
is($escaping_action->{exit}, 1, 'a local action outside the project fails');
like($escaping_action->{stderr}, qr/must not escape the project/,
'a local action outside the project is rejected');
my $broken_action = run_workflow(<<'YAML', files => {
name: Broken action
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: ./.github/actions/broken
YAML
'.github/actions/broken/action.yml' => "name: Broken\n",
});
is($broken_action->{exit}, 1, 'an action without runs fails');
like($broken_action->{stderr}, qr/has no 'runs' mapping/,
'broken action metadata is reported');
# The environment is probed before any job starts, using the image the job
# will use, and the probe is silent when it passes.
my $simple = <<'YAML';
name: Plain
on: push
jobs:
test:
runs-on: ubuntu-latest
my $probe_image_missing = run_workflow(
$simple,
fake_run_needs_image => 1,
fake_pull_failure => 'perl:5.38',
);
is($probe_image_missing->{exit}, 2, 'a probe whose image cannot be pulled stops the run');
like($probe_image_missing->{stdout}, qr/probe container failed \(exit 125\)/,
'the report names the probe container and its exit status');
like($probe_image_missing->{stdout}, qr/^ {2}remedy\s+\S/m,
'the failed probe comes with a remedy');
like($probe_image_missing->{stderr}, qr/the environment is not ready/,
'the run stops for the environment, not for the job');
unlike($probe_image_missing->{log}, qr/^run\t-d\t/m, 'no job container is started');
# Probe image: the job's own image, so a working setup needs no extra pull.
unlike($probed->{log}, qr/^pull\t.*alpine:3\.20/m,
'the probe does not pull an image the run does not need');
like($probed->{log}, qr/:ro\tperl:5\.38\t/,
'the probe uses the image the job will use');
my $verbose_probe = run_workflow($simple, verbose => 1);
is($verbose_probe->{exit}, 0, 'a verbose run passes the probe');
like($verbose_probe->{stdout}, qr/^ {2}mount\s+\S.* -> \/check-project: OK/m,
'a verbose run shows the probe report');
# A broken environment stops the run before a job container is started.
my $not_ready = run_workflow($simple, fake_os_type => 'windows');
is($not_ready->{exit}, 2, 'a broken environment stops the run');
like($not_ready->{stderr}, qr/the environment is not ready/,
'the run says the environment is at fault');
like($not_ready->{stderr}, qr/--skip-check/, 'the run points at --skip-check');
unlike($not_ready->{stderr}, qr/ at \S+ line \d+/,
'the failure message is not decorated with a source location');
unlike($not_ready->{log}, qr/^exec\t/m, 'no step runs in a broken environment');
my $hidden_project = run_workflow($simple, fake_entry_count => 0);
is($hidden_project->{exit}, 2, 'a project the container cannot see stops the run');
like($hidden_project->{stderr}, qr/the environment is not ready/,
'the unshared drive is reported before the job starts');
unlike($hidden_project->{log}, qr/^exec\t/m, 'nothing runs with an unreadable project');
# --skip-check is the escape hatch.
my $unchecked = run_workflow($simple, fake_os_type => 'windows', skip_check => 1);
is($unchecked->{exit}, 0, 'skip_check runs the workflow anyway');
like($unchecked->{stdout}, qr/Workflow succeeded/, 'the workflow runs with skip_check');
unlike($unchecked->{log}, qr/--network\tnone\t/m, 'skip_check skips the probes');
like($unchecked->{log}, qr/^info\t/m, 'skip_check still asks whether Docker is there');
# --skip-check skips the preflight, so each job prepares its own image; the
# image is still fetched once, by the job that reaches it first.
my $skip_pull = run_workflow($shared_image_yaml, pull => 1, skip_check => 1);
is($skip_pull->{exit}, 0, '--pull runs with --skip-check');
is(scalar(() = $skip_pull->{log} =~ /^pull\tperl:5\.38$/mg), 1,
'--pull pulls a shared image once even without the preflight');
my $service_broken = run_workflow($with_images, fake_pull_failure => 'postgres:15');
is($service_broken->{exit}, 2, 'an unpullable service image stops the run');
like(
$service_broken->{stderr},
qr/cannot prepare the image 'postgres:15', needed by service 'db' of job 'test'/,
'the failure names the image and the service that needs it',
);
unlike($service_broken->{stderr}, qr/ at \S+ line \d+/,
'the image failure reads as a sentence, not a source location');
unlike($service_broken->{log}, qr/^run\t-d\t/m, 'no job container is started');
unlike($service_broken->{log}, qr/^exec\t/m, 'no step runs');
my $strict_pull = run_workflow($with_images, no_pull => 1);
is($strict_pull->{exit}, 2, '--no-pull with a missing image stops the run');
like($strict_pull->{stderr}, qr/is not available locally \(--no-pull\)/,
'the --no-pull problem is explained before any container starts');
unlike($strict_pull->{stderr}, qr/ at \S+ line \d+/, 'that message reads as a sentence too');
unlike($strict_pull->{log}, qr/^run\t-d\t/m, 'no job container is started by --no-pull');
my $action_broken = run_workflow($with_images, fake_pull_failure => 'alpine:3.20');
is($action_broken->{exit}, 2, 'an unpullable action image stops the run');
like(
$action_broken->{stderr},
qr/cannot prepare the image 'alpine:3\.20', needed by action 'docker:\/\/alpine:3\.20'/,
'the failure names the action that needs it',
);
unlike($action_broken->{log}, qr/^run\t-d\t/m, 'no job container is started');
# Images inside local composite actions are found by reading the action up
# front, rather than when the step that uses it happens to run.
my $image_action = <<'YAML';
name: Run an image
runs:
steps:
- uses: ./.github/actions/run-image
- run: echo hello
YAML
files => { '.github/actions/run-image/action.yml' => $image_action },
fake_pull_failure => 'busybox:1.36',
);
is($local_broken->{exit}, 2, 'an unpullable image in a local action stops the run');
like(
$local_broken->{stderr},
qr/cannot prepare the image 'busybox:1\.36', needed by action 'docker:\/\/busybox:1\.36' in local action '\.\/\.github\/actions\/run-image' of job 'test'/,
'the failure names the image, the action, and the job',
);
unlike($local_broken->{log}, qr/^run\t-d\t/m, 'no job container is started');
unlike($local_broken->{log}, qr/^exec\t/m, 'no step runs');
# An action that uses itself must not make the preflight descend forever.
my $self_action = <<'YAML';
name: Self
runs:
}
}
# A pull that fails is still reported in the order the run needs the images,
# even though the pulls themselves finish in any order.
my $failing_pair = run_workflow(
$many_images, fake_pull_failure => 'second:1', keep_images => 0,
);
is($failing_pair->{exit}, 2, 'one unpullable image among several stops the run');
like(
$failing_pair->{stderr},
qr/cannot prepare the image 'second:1', needed by service 'second' of job 'test'/,
'the failing image is named, not whichever pull happened to finish first',
);
unlike($failing_pair->{log}, qr/^run\t-d\t/m, 'no job container is started');
# Images that did arrive are removed again when the run was told not to keep
# them, even though it stopped.
like($failing_pair->{log}, qr/^image\trm\t-f\tperl:5\.38$/m,
'the job image is removed after a failed preflight');
like($failing_pair->{log}, qr/^image\trm\t-f\tthird:1$/m,
is($shared_run->{exit}, 0, 'two jobs sharing an image run');
my $pulls = () = $shared_run->{log} =~ /^pull\tperl:5\.38$/mg;
is($pulls, 1, 'a shared image is pulled once');
# --skip-check leaves the images to be pulled when they are first used.
my $skipped_images = run_workflow(
$with_images, fake_pull_failure => 'postgres:15', skip_check => 1,
);
is($skipped_images->{exit}, 2, 'skip_check fails later, inside the job');
like($skipped_images->{stdout}, qr/==> Job: test/, 'the job starts with skip_check');
like($skipped_images->{stderr}, qr/Failed to pull Docker image 'postgres:15'/,
'the pull failure surfaces at use time');
# A dry run must not touch the registry.
my $dry = run_workflow($with_images, dry_run => 1);
is($dry->{exit}, 0, 'a dry run with services succeeds');
unlike($dry->{log}, qr/^pull\t/m, 'a dry run pulls nothing');
# The images are named when verbose, which is how a stuck pull is diagnosed.
my $verbose_images = run_workflow($with_images, verbose => 1);
is($verbose_images->{exit}, 0, 'a verbose run with services passes');
image: busybox:${{ steps.pick.outputs.image }}
steps:
- id: pick
run: |
FAKE_OUTPUT: image=1.37
- run: echo hello
YAML
is($step_job_image->{exit}, 2, 'a job image a step would decide stops the run');
like(
$step_job_image->{stderr},
qr/cannot resolve the image 'busybox:\$\{\{ steps\.pick\.outputs\.image \}\}', needed by job 'test'/,
'the failure names the expression and the job',
);
unlike($step_job_image->{log}, qr/^run\t-d\t/m, 'nothing is started for it');
my $deferred_preflight = preflight_workflow($step_decided, json => 1);
is($deferred_preflight->{result}{exit}, 0, 'a deferred image does not fail the preflight');
my $deferred_summary = $deferred_preflight->{result}{summary};
is($deferred_summary->{images}[1]{status}, 'deferred',
'the image the preflight cannot name is deferred');
defined $needs_pull && @needs_starts == 1 && $needs_pull < $needs_starts[0],
'the deferred image is prepared before the job that needs it starts',
);
my $needs_failure = run_workflow(
$needs_image, fake_pull_failure => 'busybox:success',
);
is($needs_failure->{exit}, 2,
'an unusable image named by another job stops the run before the job starts');
like(
$needs_failure->{stderr},
qr/cannot prepare the image 'busybox:success', needed by service 'helper' of job 'test'/,
'the failure names the image, the service and the job',
);
my $needs_started = () = $needs_failure->{log} =~ /^run\t-d\t/mg;
is($needs_started, 1, 'only the job that had already run started a container');
# The probe still runs first: an image problem is reported after the
# environment report, not instead of it.
my $broken_environment = run_workflow(
$with_images, fake_os_type => 'windows', fake_pull_failure => 'postgres:15',
[ map { $_->{status} } @{ $summary->{images} } ],
[ 'pulled', 'pulled', 'pulled' ],
'each image is reported as pulled',
);
is($summary->{images}[0]{source}, "job 'test'", 'the job image names the job');
is($summary->{images}[1]{source}, "service 'db' of job 'test'",
'the service image names the service');
is($summary->{images}[2]{source}, "action 'docker://alpine:3.20' in job 'test'",
'the action image names the action');
is($preflight->{stdout}, '', 'a JSON preflight prints nothing itself');
is($preflight->{stderr}, '', 'a JSON preflight writes no errors');
unlike($preflight->{log}, qr/^run\t-d\t/m, 'the preflight starts no job container');
my $preflight_failure = preflight_workflow(
$with_images, json => 1, fake_pull_failure => 'postgres:15',
);
is($preflight_failure->{result}{exit}, 2, 'an unpullable image fails the preflight');
my $failed_summary = $preflight_failure->{result}{summary};
ok(!$failed_summary->{ready}, 'the summary says the run cannot start');
is($failed_summary->{problems}, 1, 'the failed image is counted');
open my $handle, '>', $path or die "Unable to write '$path': $!";
print {$handle} $text;
close $handle;
return;
}
sub run_cli {
my (@args) = @_;
my ($stdout, $stderr, $status) = capture {
system($^X, '-I' . $lib, $script, @args);
};
return ($stdout, $stderr, $status >> 8);
}
# The schemas come from the modules, which is where the command prints them
# from, so these tests hold the contract a CI job fetches rather than a copy
# of it that could drift.
my $check_schema = App::Actions::Check->json_schema;
my $preflight_schema = App::Actions::Runner->json_schema;
my $cache_schema = App::Actions::Cache->json_schema;
my $logs_schema = App::Actions::Logs->json_schema;
);
# CI should not have to read this file to find the contract, so the command
# prints it: the same document the tests above hold the examples to.
for my $document (qw(check preflight cache logs)) {
my ($out, $err, $exit) = run_cli('schema', $document);
is($exit, 0, "schema $document exits 0");
is($err, '', "schema $document writes nothing to standard error");
my $printed = eval { JSON::PP->new->decode($out) };
ok($printed, "schema $document prints one JSON object") or diag "stderr: $err";
my $module = $shipped_schema{$document};
is(
JSON::PP->new->canonical->encode($printed),
JSON::PP->new->canonical->encode($module),
"schema $document prints the schema the module produces",
);
}
YAML
local $ENV{FAKE_DOCKER_STATE} = tempdir(CLEANUP => 1);
my ($check_out, $check_err, $check_exit) = run_cli(
'--docker', $fake, 'check', '--json', $project,
);
is($check_exit, 0, 'check --json exits 0 against the fake daemon');
my $check_doc = eval { JSON::PP->new->decode($check_out) };
ok($check_doc, 'the check document decodes') or diag "stderr: $check_err";
is_deeply([ validate($check_doc, $check_schema) ], [],
'the check document the command prints matches the schema');
is($check_doc->{schema_version}, App::Actions::Check->json_schema_version,
'the printed check document carries the module version');
is_deeply([ sort keys %$check_doc ], [ sort keys %$check_example ],
'the printed check document has the keys the example shows');
my ($preflight_out, $preflight_err, $preflight_exit) = run_cli(
'--docker', $fake, 'preflight', '--json', $workflow, $project,
);
is($preflight_exit, 0, 'preflight --json exits 0 against the fake daemon');
my $preflight_doc = eval { JSON::PP->new->decode($preflight_out) };
ok($preflight_doc, 'the preflight document decodes') or diag "stderr: $preflight_err";
is_deeply([ validate($preflight_doc, $preflight_schema) ], [],
'the preflight document the command prints matches the schema');
is($preflight_doc->{schema_version}, App::Actions::Runner->preflight_schema_version,
'the printed preflight document carries the module version');
is_deeply([ sort keys %$preflight_doc ], [ sort keys %$preflight_example ],
'the printed preflight document has the keys the example shows');
{
# A cache document needs a record and a daemon that knows the image; the
# fake daemon reports a size for a marker, which is what makes the size
or die "Unable to write '$marker': $!";
print {$marker_handle} 'alpine:3.20';
close $marker_handle;
my ($cache_out, $cache_err, $cache_exit) = run_cli(
'cache', '--json', '--docker', $fake,
);
is($cache_exit, 0, 'cache --json exits 0 against the fake daemon');
my $cache_doc = eval { JSON::PP->new->decode($cache_out) };
ok($cache_doc, 'the cache document decodes') or diag "stderr: $cache_err";
is_deeply([ validate($cache_doc, $cache_schema) ], [],
'the cache document the command prints matches the schema');
is($cache_doc->{schema_version}, App::Actions::Cache->json_schema_version,
'the printed cache document carries the module version');
cmp_ok($cache_doc->{generated_at}, '>=', $cache_doc->{images}[0]{last_used},
'the printed cache document carries the clock its image ages use');
is_deeply([ sort keys %$cache_doc ], [ sort keys %$cache_example ],
'the printed cache document has the keys the example shows');
is($cache_doc->{cache_file}, $record, 'the document names the record it read');
is($cache_doc->{images}[0]{image}, 'alpine:3.20', 'the recorded image is listed');
local $ENV{ACTION_RUN_LOG_DIR} = $logs_dir;
my $run = File::Spec->catdir($logs_dir, '20261021-120000-abc123');
make_path($run);
write_file(File::Spec->catfile($run, 'job-1-test.log'), 'x' x 512);
my ($logs_out, $logs_err, $logs_exit) = run_cli('logs', '--json');
is($logs_exit, 0, 'logs --json exits 0');
my $logs_doc = eval { JSON::PP->new->decode($logs_out) };
ok($logs_doc, 'the logs document decodes') or diag "stderr: $logs_err";
is_deeply([ validate($logs_doc, $logs_schema) ], [],
'the logs document the command prints matches the schema');
is($logs_doc->{schema_version}, App::Actions::Logs->json_schema_version,
'the printed logs document carries the module version');
is_deeply([ sort keys %$logs_doc ], [ sort keys %$logs_example ],
'the printed logs document has the keys the example shows');
is($logs_doc->{logs_directory}, $logs_dir, 'the document names the directory it read');
is($logs_doc->{logs}[0]{run}, '20261021-120000-abc123', 'the run is named');
is($logs_doc->{logs}[0]{name}, 'job-1-test.log', 'the log is named');
is($logs_doc->{logs}[0]{size}, 512, 'the document carries the size rather than text');
is($logs_doc->{totals}{runs}, 1, 'the document counts the runs');
is($logs_doc->{totals}{logs}, 1, 'the document counts the logs');
is($logs_doc->{totals}{size}, 512, 'the document totals the size');
is($logs_doc->{prune}, undef, 'a listing has no prune report');
($logs_out, $logs_err, $logs_exit) = run_cli('logs', '--prune', '--json');
is($logs_exit, 0, 'logs --prune --json exits 0');
$logs_doc = eval { JSON::PP->new->decode($logs_out) };
ok($logs_doc, 'the prune document decodes') or diag "stderr: $logs_err";
is_deeply([ validate($logs_doc, $logs_schema) ], [],
'the prune document matches the schema');
is($logs_doc->{prune}{removed}, 1, 'the document says what the prune removed');
is($logs_doc->{prune}{freed}, 512, 'the document says what the prune freed');
is_deeply($logs_doc->{prune}{failed}, [], 'the document says every removal worked');
is_deeply($logs_doc->{logs}, [], 'the prune left no logs in the document');
}
# The step the fake daemon answers decides an image name, so this document has
# a deferred record too; the example shows that shape, and the schema allows
# values, which is what the schema claims.
{
local $ENV{FAKE_OS_TYPE} = 'windows';
my ($broken_out, $broken_err, $broken_exit) = run_cli(
'--docker', $fake, 'preflight', '--json', $workflow, $project,
);
is($broken_exit, 2, 'a preflight on a broken environment exits 2');
my $broken = eval { JSON::PP->new->decode($broken_out) };
ok($broken, 'the failing preflight document decodes') or diag "stderr: $broken_err";
is_deeply([ validate($broken, $preflight_schema) ], [],
'the failing preflight document matches the schema');
ok(!$broken->{ready}, 'the failing document is not ready');
cmp_ok($broken->{problems}, '>', 0, 'the failing document counts a problem');
is_deeply([ sort keys %$broken ], [ sort keys %$preflight_example ],
'a failing document has the keys the example shows');
}
# The same for an image that could not be pulled: the failed shape carries an
# error and leaves the run unready.
{
local $ENV{FAKE_PULL_FAILURE} = 'postgres:15';
my ($failed_out, $failed_err, $failed_exit) = run_cli(
'--pull', '--docker', $fake, 'preflight', '--json', $workflow, $project,
);
is($failed_exit, 2, 'a preflight with an unpullable image exits 2');
my $failed = eval { JSON::PP->new->decode($failed_out) };
ok($failed, 'the failed preflight document decodes') or diag "stderr: $failed_err";
is_deeply([ validate($failed, $preflight_schema) ], [],
'the failed preflight document matches the schema');
my @failed = grep { $_->{status} eq 'failed' } @{ $failed->{images} };
is(scalar @failed, 1, 'the image that could not be pulled is marked');
like($failed[0]{error}, qr/Failed to pull Docker image 'postgres:15'/,
'a failed image reports the reason');
}
# A preflight that skips the probes still reports the host it can see locally,
# so its document has the shape the schema claims rather than empty objects.
{
my ($skipped_out, $skipped_err, $skipped_exit) = run_cli(
'--skip-check', '--docker', $fake, 'preflight', '--json', $workflow, $project,
);
is($skipped_exit, 0, 'a preflight with --skip-check exits 0');
my $skipped = eval { JSON::PP->new->decode($skipped_out) };
ok($skipped, 'the skipped-probe document decodes') or diag "stderr: $skipped_err";
is_deeply([ validate($skipped, $preflight_schema) ], [],
'the skipped-probe document matches the schema');
is($skipped->{host}{os}, $^O, 'the host is reported even when it was not probed');
}
# The commands hold themselves to the contract rather than only being tested
# against it: a document that no longer matches the shipped schema is not
# printed at all. Replacing the schema for the length of a block is the drift
# a forgotten schema change would cause.
{
t/self_test.t view on Meta::CPAN
or die "Unable to open '$lock_path': $!";
flock($live_lock, LOCK_EX)
or die "Unable to lock '$lock_path': $!";
%already = map { $_ => 1 } @{ action_run_containers($daemon) };
diag 'action-run containers already present before this test: '
. join ' ', sort keys %already
if %already;
}
my ($stdout, $stderr, $exit) = run_workflow_file($docker, $workflow);
diag "stdout:\n$stdout" if $exit != 0;
diag "stderr:\n$stderr" if length $stderr;
is($exit, 0, 'action-run runs the workflow it ships');
like($stdout, qr/^==> Job: self-test$/m, 'the job the workflow defines runs');
like($stdout, qr/^ {2}self-test\s+success$/m, 'the job summary reports success');
like($stdout, qr/^Workflow succeeded$/m, 'the run reports success');
# A step's own output is what shows the script ran rather than a log line
# saying it was found. The fake daemon executes scripts on a host with a
# POSIX shell; on Windows it emulates them, so there is nothing to quote there
# and the live run is the one that covers a real container.
SKIP: {
t/self_test.t view on Meta::CPAN
like($stdout, qr/the project is visible in the container/,
'the project is mounted where the step can read it');
like($stdout, qr/the environment reached the step/,
'a step environment variable reached the container');
}
# The second shipped workflow runs the tool itself inside a Perl image:
# "action-run schema" and "action-run validate" are exercised from inside the
# container for every check, preflight, cache and logs fixture, through the
# command a user runs.
my ($cli_stdout, $cli_stderr, $cli_exit) = run_workflow_file($docker, $cli_workflow);
diag "stdout:\n$cli_stdout" if $cli_exit != 0;
diag "stderr:\n$cli_stderr" if length $cli_stderr;
is($cli_exit, 0, 'action-run runs the second workflow it ships');
like($cli_stdout, qr/^==> Job: self-test-cli$/m,
'the Perl-image job runs');
like($cli_stdout, qr/^ {2}self-test-cli\s+success$/m,
'the Perl-image job summary reports success');
like($cli_stdout, qr/^Workflow succeeded$/m,
'the second workflow reports success');
SKIP: {
sub useful_text {
my ($text) = @_;
return '' unless defined $text;
$text =~ s/\r\n/\n/g;
return $text;
}
sub run_smoke {
my (@args) = @_;
my ($stdout, $stderr, $status) = capture {
system($^X, '-I' . $lib, $script, @args);
};
# $? carries the POSIX-compatible status on Windows too.
return (useful_text($stdout), useful_text($stderr), $status >> 8);
}
my ($version_out, undef, $version_exit) = run_smoke('--version');
is($version_exit, 0, '--version exits 0');
like($version_out, qr/^action-run-smoke 0\.002\.1$/m, '--version prints the version');
my ($help_out, undef, $help_exit) = run_smoke('--help');
is($help_exit, 0, '--help exits 0');
like($help_out, qr/Usage:/, '--help prints usage');
like($help_out, qr/--directory/, '--help lists the options');
t/space-path.t view on Meta::CPAN
ok(@tests, 'the copy contains the test suite');
my @failed;
{
my $original = File::Spec->rel2abs(File::Spec->curdir);
chdir $copy or die "cannot change to '$copy': $!\n";
for my $test (@tests) {
my $file = File::Spec->catfile($tests, $test);
my ($stdout, $stderr, $status) = capture {
local $ENV{APP_ACTIONS_SPACE_PATH_CHILD} = 1;
App::Actions::Process::stream([ $^X, '-I' . $lib, $file ]);
};
my $ok = ok(
$status == 0,
"$test passes when the suite is run from a path with spaces",
);
next if $ok;
push @failed, $test;
diag "stdout:\n$stdout" if length $stdout;
diag "stderr:\n$stderr" if length $stderr;
}
chdir $original or die "cannot return to '$original': $!\n";
}
is_deeply(\@failed, [], 'every test file passes from a path with spaces');
done_testing;
for my $hostile ('0', '-2', 'lots', '4; rm -rf /', '') {
local $ENV{NUMBER_OF_PROCESSORS} = $hostile;
cmp_ok(App::Actions::Process::cpu_count(), '>=', 1, 'a NUMBER_OF_PROCESSORS of ' . shown($hostile) . ' is not believed');
}
};
subtest 'capture' => sub {
my ($output, $status) = App::Actions::Process::capture(perl_command('binmode STDOUT; print qq{a\r\nb}; exit 4'));
is($output, "a\nb", 'the output, with CRLF made LF');
is($status, 4, 'and the status');
is(output_of(stderr => sub { ($output) = App::Actions::Process::capture(perl_command('print STDERR q{noise}; print q{d}')) }),
'noise', 'the error output goes to the terminal by default');
is($output, 'd', 'and is not in the output');
is(output_of(stderr => sub { ($output) = App::Actions::Process::capture(perl_command('print STDERR q{x}; print q{d}'),
quiet_stderr => 1) }), '', 'quiet_stderr throws it away');
($output) = App::Actions::Process::capture(perl_command('$| = 1; print 1; print STDERR 2; print 3'), merge_stderr => 1);
is($output, '123', 'merge_stderr includes it, in order');
is_deeply([ App::Actions::Process::capture([ File::Spec->catfile(tempdir(CLEANUP => 1), 'none') ]) ], [ '', 255 ],
'a missing program is no output and 255');
($output) = App::Actions::Process::capture(perl_command('print join q{|}, @ARGV', 'a;echo no', '$(id)', '`x`', '*'));
is($output, 'a;echo no|$(id)|`x`|*', 'arguments are never read by a shell');
throws_ok { App::Actions::Process::capture($_) } qr/\ANo command given at /, 'refused: ' . shown($_)
for undef, [], 'echo', { 0 => 'echo' };
settle('text Process: No command given');
{
qr/\AUnable to rewind captured output: \S/, 'a temporary file that cannot be rewound';
}
settle('text Process: Unable to rewind captured output');
keeps_globals(sub { App::Actions::Process::capture(perl_command('print 1')) }, 'capture', io => 1);
};
subtest 'run' => sub {
my $dir = tempdir(CLEANUP => 1);
my $out = File::Spec->catfile($dir, 'out');
my $err = File::Spec->catfile($dir, 'err');
is(App::Actions::Process::run(perl_command('print q{o}; print STDERR q{e}'), stdout => $out, stderr => $err), 0, 'run');
my $read = sub { open my $in, '<', $_[0] or die $!; local $/; my $text = <$in>; return defined $text ? $text : '' };
is($read->($out), 'o', 'the output goes to stdout');
is($read->($err), 'e', 'the error output to stderr');
App::Actions::Process::run(perl_command('print q{p}'), stdout => $out, append => 1);
is($read->($out), 'op', 'append adds to the file');
App::Actions::Process::run(perl_command('$| = 1; print 1; print STDERR 2'), stdout => $out, stderr => $err, merge_stderr => 1);
is($read->($out), '12', 'merge_stderr wins over stderr');
is(output_of(stdout => sub { App::Actions::Process::run(perl_command('print q{gone}')) }), '',
'without stdout the output is thrown away');
throws_ok { App::Actions::Process::run(perl_command('1'), stdout => $dir) }
qr/\AUnable to redirect command output: \S/, 'an output file that cannot be opened';
settle('text Process: Unable to redirect command output');
is(output_of(stdout => sub { print "still here\n" }), "still here\n", 'and STDOUT works afterwards');
for my $stream (qw(STDOUT STDERR)) {
my $handle = $stream eq 'STDOUT' ? \*STDOUT : \*STDERR;
}
open(($stream eq 'STDOUT' ? \*STDOUT : \*STDERR), '>&', $keep) or die $!;
like($error, qr/\AUnable to restore $stream: \S/, "a $stream that cannot be restored");
}
settle('text Process: Unable to restore STDOUT/STDERR');
keeps_globals(sub { App::Actions::Process::run(perl_command('exit 0')) }, 'run', io => 1);
};
subtest 'run_quiet and stream' => sub {
my $quiet;
is(output_of(stderr => sub { is(output_of(stdout => sub {
$quiet = App::Actions::Process::run_quiet(perl_command('print q{o}; print STDERR q{e}; exit 2')) }), '', 'run_quiet: no output') }),
'', 'and no error output');
is($quiet, 2, 'run_quiet: the status');
my $status;
is(output_of(stdout => sub { $status = App::Actions::Process::stream(perl_command('print q{live}; exit 5')) }), 'live',
'stream: the output reaches the terminal');
is($status, 5, 'stream: the status');
throws_ok { App::Actions::Process::stream($_) } qr/\ANo command given at /, 'stream refuses ' . shown($_) for undef, [];
throws_ok { App::Actions::Process::run_quiet([]) } qr/\ANo command given at /, 'run_quiet refuses an empty command';
keeps_globals(sub { App::Actions::Process::run_quiet(perl_command('1')) }, 'run_quiet', io => 1);
App::Actions::Process::run_parallel([ perl_command('print q{new}') ], stdout => $out);
open $in, '<', $out or die $!;
is(do { local $/; <$in> }, 'new', 'which is emptied once, first');
close $in;
is_deeply(App::Actions::Process::run_parallel([]), [], 'no commands, no statuses');
is_deeply(App::Actions::Process::run_parallel([ (perl_command('exit 1')) x 3 ]), [ 1, 1, 1 ], 'the default concurrency');
# A program a child cannot start is 127, and the child says why.
my $err = File::Spec->catfile($dir, 'err');
my $missing = File::Spec->catfile($dir, 'missing');
$statuses = App::Actions::Process::run_parallel([ [ $missing ], perl_command('exit 0') ], concurrency => 2, stderr => $err);
is_deeply($statuses, [ 127, 0 ], 'a program a child cannot start is 127');
settle('status Process: 127 child could not start');
open $in, '<', $err or die $!;
like(do { local $/; <$in> }, qr/\AUnable to run '\Q$missing\E': \S/, 'and the child says so');
close $in;
settle('message process.exec_failed');
# A file the child cannot open: the parent emptied it, the child's
# append is refused.
my $said;
{
local $FAIL{open} = sub { defined $_[1] && $_[1] eq '>>' };
$said = output_of(stderr => sub {
$statuses = App::Actions::Process::run_parallel([ perl_command('1'), perl_command('1') ], concurrency => 2, stdout => $out);
});
}
is_deeply($statuses, [ 127, 127 ], 'an output a child cannot open is 127');
like($said, qr/^Unable to redirect stdout to '\Q$out\E': \S/m, 'and the child says so');
settle('message process.redirect_failed');
throws_ok { App::Actions::Process::run_parallel($_) } qr/\ANo commands given at /, 'refused: ' . shown($_)
for undef, 'echo', {};
settle('text Process: No commands given');
my $missing = File::Spec->catfile(tempdir(CLEANUP => 1), 'none');
throws_ok { App::Actions::Docker->new(bin => $missing)->check }
qr/\ADocker executable '\Q$missing\E' was not found or is not usable at /, 'no docker program';
with_docker([ [ '^--version', 1 ] ], sub {
throws_ok { docker()->check } qr/\ADocker executable '.*' was not found or is not usable at /, 'a docker that fails';
});
settle("text Docker: Docker executable 'BIN' was not found or is not usable");
my $said;
with_docker([ [ '^info', 1, '', "daemon down\\n" ] ], sub {
$said = output_of(stderr => sub {
throws_ok { docker()->check }
qr/\ACannot connect to the Docker daemon\. Is Docker running, and can this user access it\? at /,
'no daemon';
});
});
like($said, qr/daemon down/, "docker's own reason is shown");
with_docker([ [ '^info', 1, '', "daemon down\\n" ] ], sub {
$said = output_of(stderr => sub { eval { docker(quiet => 1)->check } });
});
is($said, '', 'but not when quiet');
settle('text Docker: Cannot connect to the Docker daemon');
with_docker([ [ '^--version', 0, "Docker version 99\\n" ] ], sub {
is(output_of(stdout => sub { docker(verbose => 1)->check }), "+ $fake_docker --version\nDocker version 99\n"
. "+ $fake_docker info --format '{{.ServerVersion}}'\n", 'verbose shows the commands and the version');
});
with_docker([], sub { keeps_globals(sub { docker()->check }, 'check', io => 1) });
};
});
my $results;
$log = with_docker([ [ 'pull bad', 2 ] ], sub {
$results = docker()->pull_many([ 'good', 'bad', 'fine' ], concurrency => 2);
});
returns_ok($results, { type => 'hashref' }, 'pull_many: a hash reference');
is_deeply($results, { good => 0, bad => 2, fine => 0 }, 'the status of each pull');
is(scalar @{ $log->{argv} }, 3, 'one pull each');
with_docker([ [ 'pull', 0, "noise\\n", "more\\n" ] ], sub {
is(output_of(stderr => sub { is(output_of(stdout => sub { docker()->pull_many([ 'a' ], quiet => 1) }), '',
'quiet: no output') }), '', 'and no error output');
is(output_of(stdout => sub { docker(verbose => 1)->pull_many([ 'a', 'b' ], quiet => 1) }), '', 'even when verbose');
like(output_of(stdout => sub { docker(verbose => 1)->pull_many([ 'a', 'b' ]) }),
qr/\A\+ \Q$fake_docker\E pull a\n\+ \Q$fake_docker\E pull b\n/, 'verbose: the commands first');
});
is(output_of(stdout => sub { $results = docker(dry_run => 1, platform => 'x/y')->pull_many([ 'a', 'b' ]) }),
"[dry-run] $fake_docker pull --platform x/y a\n[dry-run] $fake_docker pull --platform x/y b\n",
'a dry run prints the pulls');
is_deeply($results, { a => 0, b => 0 }, 'and says they worked');
is(output_of(stdout => sub { docker(dry_run => 1, explain => 1)->pull_many([ 'a' ]) }), '', 'unless it is explaining');
is_deeply([ $dry->container_exit_code('x'), $dry->container_status('x'), $dry->container_restart_count('x') ],
[ 0, 'running', 0 ], 'a dry run: exit 0, running, never restarted');
$log = with_docker([ [ '^rm', 1 ] ], sub { is(docker()->container_remove('j'), 1, 'container_remove: the status') });
is_deeply($log->{argv}, [ [ qw(rm -f j) ] ], 'rm -f');
};
subtest 'run, run_silent and the captures' => sub {
with_docker([ [ '^ps', 0, "out\\r\\n", "err\\n" ], [ '^die', 'TERM' ] ], sub {
my ($status, $error);
is(output_of(stdout => sub { $error = output_of(stderr => sub { $status = docker()->run('ps') }) }), "out\r\n",
'run shows the output as it is');
is($error, "err\n", 'and the error output');
is($status, 0, 'and returns the status');
is(docker()->run('die'), 128 + 15, 'a signal is 128 plus its number');
is(output_of(stdout => sub { $error = output_of(stderr => sub { $status = docker()->run_silent('ps') }) }), '',
'run_silent shows nothing');
is($error, '', 'not even errors');
my ($output);
$error = output_of(stderr => sub { ($output, $status) = docker()->capture('ps') });
is_deeply([ $output, $status ], [ "out\n", 0 ], 'capture: the output, CRLF made LF, and the status');
is($error, "err\n", 'the error output goes to the terminal');
$error = output_of(stderr => sub { ($output) = docker()->capture_silent('ps') });
is_deeply([ $output, $error ], [ "out\n", '' ], 'capture_silent throws the error output away');
($output) = docker()->capture_merged('ps');
is($output, "out\nerr\n", 'capture_merged includes it');
});
for my $method (qw(capture capture_silent capture_merged)) {
is_deeply([ docker(dry_run => 1, quiet => 1)->$method('ps') ], [ '', 0 ], "$method: ('', 0) in a dry run");
}
is(docker(dry_run => 1, quiet => 1)->run('ps'), 0, 'run: 0 in a dry run');
# What is printed: [dry-run] or +, quoted so it could be pasted, with
my %status = ('success()' => 1, 'always ()' => 1, '${{ failure() }}' => 1, 'cancelled()' => 1, 'github.success' => 0,
q{'success'} => 0, '' => 0);
is_returned(App::Actions::Runner::Support::has_status_function($_), { type => 'boolean' }, $status{$_},
'has_status_function: ' . shown($_)) for sort keys %status;
is(App::Actions::Runner::Support::has_status_function(undef), 0, 'undef has none');
};
subtest 'default_logger and null_logger' => sub {
my $logger = App::Actions::Runner::Support::default_logger();
returns_ok($logger, { type => 'object', isa => 'Log::Abstraction' }, 'default_logger');
is(output_of(stderr => sub { $logger->warn('the image cache could not be written') }),
"the image cache could not be written\n", 'prints the message as written, on standard error');
is(output_of(stderr => sub { $logger->error("two\nlines") }), "two\nlines\n", 'several lines as they are');
is(output_of(stderr => sub { $logger->debug('detail') }), "detail\n", 'every level');
is(output_of(stdout => sub { $logger->warn('x') }), '', 'nothing on standard output');
my $null = App::Actions::Runner::Support::null_logger();
returns_ok($null, { type => 'object', isa => 'Log::Abstraction' }, 'null_logger');
is(output_of(stderr => sub { $null->error('gone') }), '', 'throws every message away');
keeps_globals(sub { App::Actions::Runner::Support::default_logger() }, 'default_logger');
};
subtest 'resolve_env' => sub {
my $context = { matrix => { perl => '5.40' }, github => { event => { message => 'see ${{ env.SECRET }}' } } };
my $env = App::Actions::Runner::Support::resolve_env($expression, [
{ A => 'workflow', B => 'b-${{ env.C }}', MESSAGE => '${{ github.event.message }}', SECRET => 'hidden' },
'not a layer',
{ A => 'job', C => 'c-${{ env.a }}-${{ matrix.perl }}' },
undef,