Lines 95.23% 20 / 21
Methods 80.00% 4 / 5
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 prepareLatestRelease 100.00% 1 / 1 100.00% 1 / 1 1
 findCheckFailure 100.00% 8 / 8 100.00% 1 / 1 4
 stageRelease 0.00% 0 / 1 0.00% 0 / 1 2
 runEntrypoint 100.00% 10 / 10 100.00% 1 / 1 2
14final readonly class ReleaseScript
15{
16    private const string ENTRYPOINT = 'stewart-entrypoint';
17
18    private const string UNEXPLAINED_CHECK_FAILURE = 'stewart check failed without saying why';
19
20    public function __construct(
21        private ExternalCommandRunner $commands,
22        private GitDeployConfig $gitDeploy,
23        private DaemonLaunchOptions $launch,
24    ) {}
25
26    /**
27     * @throws DeployException
28     * @throws CancelledException
29     */
30    public function prepareLatestRelease(Cancellation $cancellation): PreparedRelease
31    {
32        return PreparedRelease::fromScriptOutput($this->runEntrypoint(['release-prepare'], $cancellation)->output);
33    }
34
35    /**
36     * @throws DeployException
37     * @throws CancelledException
38     */
39    public function findCheckFailure(CommitId $commit, Cancellation $cancellation): ?string
40    {
41        $arguments = ['release-check', $commit->value];
42
43        if ($this->launch->configFile !== null) {
44            $arguments[] = '--config=' . $this->launch->configFile;
45        }
46
47        $result = $this->commands->runCommand([self::ENTRYPOINT, ...$arguments], $this->gitDeploy->prepareTimeout, $cancellation);
48
49        if ($result->isSuccessful()) {
50            return null;
51        }
52
53        $reason = $result->findFirstErrorLine();
54
55        return $reason === '' ? self::UNEXPLAINED_CHECK_FAILURE : $reason;
56    }
57
58    /**
59     * @throws DeployException
60     * @throws CancelledException
61     */
62    public function stageRelease(CommitId $commit, Cancellation $cancellation): void
63    {
64        $this->runEntrypoint(['release-stage', $commit->value], $cancellation);
65    }
66
67    /**
68     * @param list<string> $arguments
69     * @throws DeployException
70     * @throws CancelledException
71     */
72    private function runEntrypoint(array $arguments, Cancellation $cancellation): ExternalCommandResult
73    {
74        $command = [self::ENTRYPOINT, ...$arguments];
75        $result = $this->commands->runCommand($command, $this->gitDeploy->prepareTimeout, $cancellation);
76
77        if (!$result->isSuccessful()) {
78            throw DeployException::createForReason(
79                DeployError::CommandFailed,
80                command: implode(' ', $command),
81                exitCode: $result->exitCode,
82                detail: $result->findLastErrorLine(),
83            );
84        }
85
86        return $result;
87    }
88}