Lines 100.00% 11 / 11
Methods 100.00% 1 / 1
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 runCommand 100.00% 11 / 11 100.00% 1 / 1 4
20final readonly class AmpExternalCommandRunner implements ExternalCommandRunner
21{
22    public function runCommand(array $command, Duration $timeout, Cancellation $cancellation, array $environmentOverrides = []): ExternalCommandResult
23    {
24        // A non-empty environment replaces the inherited one, so the overrides go on top of it.
25        $process = Process::start($command, environment: $environmentOverrides === [] ? [] : [...getenv(), ...$environmentOverrides]);
26        $process->getStdin()->close();
27        // Both pipes drain while the command runs, so a chatty composer install cannot fill one and stall.
28        /** @var Future<string> $output */
29        $output = async(static fn(): string => buffer($process->getStdout()));
30        /** @var Future<string> $errorOutput */
31        $errorOutput = async(static fn(): string => buffer($process->getStderr()));
32
33        try {
34            $exitCode = $process->join(new CompositeCancellation($cancellation, new TimeoutCancellation($timeout->toSeconds())));
35        } catch (CancelledException $e) {
36            $process->kill();
37
38            if ($cancellation->isRequested()) {
39                throw $e;
40            }
41
42            throw DeployException::createForReason(DeployError::CommandTimedOut, $e, command: implode(' ', $command), timeout: (string) $timeout);
43        }
44
45        return new ExternalCommandResult($exitCode, $output->await(), $errorOutput->await());
46    }
47}