Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/BrefCloudClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,29 @@ public function getCommand(int $id): array
return $result;
}

/**
* The output of the command from $offset: what has not been printed yet.
*
* @return array{
* status: 'not_started'|'started'|'success'|'failed',
* output: string,
* offset: int,
* error: string|null,
* } `offset`: where the next call starts. `error`: why the command failed, when known.
*
* @throws HttpExceptionInterface
* @throws ExceptionInterface
*/
public function getCommandOutput(int $id, int $offset): array
{
/** @var array{status: 'not_started'|'started'|'success'|'failed', output: string, offset: int, error: string|null} $result */
$result = $this->client->request('GET', "/api/v1/commands/$id", [
'query' => ['offset' => $offset],
])->toArray();

return $result;
}

/**
* @return list<array{id: int, name: string, role_arn: string, team_id: int}>
*
Expand Down
65 changes: 16 additions & 49 deletions src/Commands/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,68 +48,35 @@ protected function execute(InputInterface $input, OutputInterface $output): int

IO::spin('running');

// Timeout after 2 minutes and 10 seconds
$timeout = 130;
$startTime = time();

$offset = 0;
while (true) {
$invocation = $brefCloud->getCommand($id);
$invocation = $brefCloud->getCommandOutput($id, $offset);
$offset = $invocation['offset'];

if ($invocation['status'] === 'success') {
if ($invocation['output'] !== '') {
// The output shows that the command runs
IO::spinClear();
// As is: the output of the command is not formatted for Symfony Console
IO::writeRaw($invocation['output']);
return 0;
// As is: the output of the command is not formatted for Symfony Console.
// Complete lines, and writeRaw() ends each with a line break.
$output = $invocation['output'];
IO::writeRaw(str_ends_with($output, "\n") ? substr($output, 0, -1) : $output);
}

if ($invocation['status'] === 'failed') {
if ($invocation['status'] === 'success') {
IO::spinClear();
$this->writeErrorDetails($invocation['output']);
return 1;
return 0;
}

if ((time() - $startTime) > $timeout) {
if ($invocation['status'] === 'failed') {
IO::spinClear();
IO::writeln(Styles::red('Timed out'));
IO::writeln(Styles::gray('The execution timed out after 2 minutes, the command might still be running'));
IO::writeln([
'',
Styles::bold(Styles::red('ERROR')) . ' ' . Styles::gray($invocation['error'] ?? 'The command failed'),
]);
return 1;
}

delay(1);
}
}

private function writeErrorDetails(string $output): void
{
try {
$errorDetails = json_decode($output, true, 512, JSON_THROW_ON_ERROR);
if (! is_array($errorDetails)
|| ! isset($errorDetails['errorType'], $errorDetails['errorMessage'])
|| ! is_string($errorDetails['errorType'])
|| ! is_string($errorDetails['errorMessage'])) {
IO::writeRaw(Styles::red($output));
return;
}

$errorType = $errorDetails['errorType'];
if ($errorType === 'Bref\ConsoleRuntime\CommandFailed') {
// No need to show this class, it's noise
$errorType = '';
}

IO::writeln([
'',
Styles::bold(Styles::red('ERROR')) . ' ' . Styles::gray($errorType),
'',
]);
// The output of the command
IO::writeRaw($errorDetails['errorMessage']);
if (isset($errorDetails['stackTrace']) && is_array($errorDetails['stackTrace'])) {
$stackTrace = array_values(array_filter($errorDetails['stackTrace'], 'is_string'));
IO::verbose($stackTrace);
}
} catch (JsonException) {
IO::writeRaw(Styles::red($output));
}
}
}
39 changes: 31 additions & 8 deletions tests/Commands/CommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,29 +47,52 @@ public function test_the_output_is_printed_as_is(): void
// Text that looks like Symfony Console tags is not interpreted: it's the output of the application
$output = 'Hello <info>world</info>, <href=https://example.com>a link</>';

[$status, $display] = $this->runCommand(decorated: true, command: ['status' => 'success', 'output' => $output]);
[$status, $display] = $this->runCommand(decorated: true, responses: [['status' => 'success', 'output' => $output, 'offset' => 10, 'error' => null]]);
$this->assertSame(0, $status, $display);
$this->assertStringContainsString($output, $display);
}

public function test_the_output_is_printed_while_the_command_runs(): void
{
[$status, $display] = $this->runCommand(decorated: false, responses: [
['status' => 'started', 'output' => "Migrating\n", 'offset' => 10, 'error' => null],
['status' => 'started', 'output' => '', 'offset' => 10, 'error' => null],
['status' => 'success', 'output' => "Migrated\n", 'offset' => 19, 'error' => null],
]);

$this->assertSame(0, $status, $display);
$this->assertStringEndsWith("› Running\nMigrating\nMigrated\n", $display);
// Each call asks for what has not been printed yet
$this->assertSame(['/api/v1/commands/5?offset=0', '/api/v1/commands/5?offset=10', '/api/v1/commands/5?offset=10'], array_values(array_filter(
$this->requests,
fn (string $request) => str_starts_with($request, '/api/v1/commands/5'),
)));
}

[$status, $display] = $this->runCommand(decorated: false, command: [
'status' => 'failed',
'output' => json_encode(['errorType' => 'Bref\ConsoleRuntime\CommandFailed', 'errorMessage' => $output]),
public function test_a_failed_command_shows_why(): void
{
[$status, $display] = $this->runCommand(decorated: false, responses: [
['status' => 'failed', 'output' => "Migrating\n", 'offset' => 10, 'error' => 'The command exited with code 1'],
]);

$this->assertSame(1, $status, $display);
$this->assertStringContainsString($output, $display);
$this->assertStringEndsWith("› Running\nMigrating\n\nERROR The command exited with code 1\n", $display);
}

/**
* @param array{status: string, output: string} $command What Bref Cloud returns for the command
* @param list<array{status: string, output: string, offset: int, error: string|null}> $responses What Bref Cloud returns for the command, call after call
* @return array{int, string} The exit code and the output
*/
private function runCommand(bool $decorated, array $command = ['status' => 'success', 'output' => "\e[32mLaravel\e[39m 13"]): array
private function runCommand(bool $decorated, array $responses = [['status' => 'success', 'output' => "\e[32mLaravel\e[39m 13", 'offset' => 20, 'error' => null]]): array
{
$this->requestBodies = [];
$this->requests = [];
$command = new Command($this->brefCloud([
'/api/v1/environments/find' => $this->environment(),
'/api/v1/commands/start' => ['id' => 5],
'/api/v1/commands/5' => $command,
'/api/v1/commands/5' => function () use (&$responses) {
return $this->json(array_shift($responses));
},
]));
$input = new ArrayInput(['args' => 'about', '--config' => $this->configFile]);
$input->setInteractive(false);
Expand Down
Loading