Skip to content
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
86 changes: 86 additions & 0 deletions src/Console/DeployCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

namespace Laravel\Nightwatch\Console;

use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Laravel\Nightwatch\NightwatchDeployException;
use SensitiveParameter;
use Symfony\Component\Console\Attribute\AsCommand;
use Throwable;

use function config;
use function report;

/**
* @internal
*/
#[AsCommand(name: 'nightwatch:deploy', description: 'Notify Nightwatch of a deployment.')]
final class DeployCommand extends Command
{
/**
* @var string
*/
protected $signature = 'nightwatch:deploy';

/**
* @var string
*/
protected $description = 'Notify Nightwatch of a deployment.';

/**
* @var bool
*/
protected $hidden = true;

public function __construct(
#[SensitiveParameter] private ?string $token,
) {
parent::__construct();
}

public function handle(): int
{
if (! $this->token) {
$this->components->error('Please configure the [NIGHTWATCH_TOKEN] environment variable.');

report(new NightwatchDeployException('NIGHTWATCH_TOKEN environment variable is not configured.'));

return 0;
}

$version = config('nightwatch.deployment') ?? '';

$baseUrl = ! empty($_SERVER['NIGHTWATCH_BASE_URL']) ? $_SERVER['NIGHTWATCH_BASE_URL'] : 'https://nightwatch.laravel.com';

try {
Http::connectTimeout(5)
->timeout(10)
->acceptJson()
->withToken($this->token)
->post("{$baseUrl}/api/deployments", [
'v' => 1,
'timestamp' => CarbonImmutable::now()->timestamp,
'version' => $version,
])
->throw();

$this->components->info('Deployment sent to Nightwatch successfully.');
} catch (RequestException $e) {
$message = Str::limit($e->response->json('message') ?? "[{$e->getCode()}] {$e->response->body()}", 1000, '[...]'); // @phpstan-ignore argument.type

report(new NightwatchDeployException($message, previous: $e));

$this->components->error("Deployment could not be sent to Nightwatch: {$message}");
} catch (Throwable $e) {
report(new NightwatchDeployException($e->getMessage(), previous: $e));

$this->components->error("Deployment could not be sent to Nightwatch: {$e->getMessage()}");
}

return 0;
}
}
10 changes: 10 additions & 0 deletions src/NightwatchDeployException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Laravel\Nightwatch;

use RuntimeException;

class NightwatchDeployException extends RuntimeException
{
//
}
10 changes: 10 additions & 0 deletions src/NightwatchServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
use Illuminate\Support\Facades\Context;
use Illuminate\Support\ServiceProvider;
use Laravel\Nightwatch\Console\AgentCommand;
use Laravel\Nightwatch\Console\DeployCommand;
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Factories\Logger;
use Laravel\Nightwatch\Hooks\ArtisanStartingListener;
Expand Down Expand Up @@ -194,6 +195,7 @@ private function registerBindings(): void
$this->registerLogger();
$this->registerMiddleware();
$this->registerAgentCommand();
$this->registerDeployCommand();
$this->buildAndRegisterCore();
}

Expand Down Expand Up @@ -228,6 +230,13 @@ private function registerAgentCommand(): void
));
}

private function registerDeployCommand(): void
{
$this->app->singleton(DeployCommand::class, fn () => new DeployCommand(
token: $this->nightwatchConfig['token'] ?? null,
));
}

private function buildAndRegisterCore(): void
{
$clock = new Clock;
Expand Down Expand Up @@ -299,6 +308,7 @@ private function registerCommands(): void
$this->commands([
Console\AgentCommand::class,
Console\StatusCommand::class,
Console\DeployCommand::class,
]);
}

Expand Down
142 changes: 142 additions & 0 deletions tests/Feature/Console/DeployCommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<?php

namespace Tests\Feature\Console;

use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Laravel\Nightwatch\Console\DeployCommand;
use Laravel\Nightwatch\NightwatchDeployException;
use Orchestra\Testbench\Attributes\WithEnv;
use Tests\TestCase;
use Throwable;

use function env;
use function json_encode;
use function now;

class DeployCommandTest extends TestCase
{
#[WithEnv('NIGHTWATCH_TOKEN', 'test-token')]
#[WithEnv('NIGHTWATCH_DEPLOY', 'v1.2.3')]
public function test_it_can_run_the_deploy_command(): void
{
$this->freezeTime();
Http::fake([
'*/api/deployments' => function (Request $request) {
$this->assertEquals(['Bearer '.env('NIGHTWATCH_TOKEN')], $request->header('Authorization'));
$this->assertEquals([
'v' => 1,
'timestamp' => now()->getTimestamp(),
'version' => 'v1.2.3',
], $request->data());

return Http::response('OK');
},
]);

$this->artisan('nightwatch:deploy')
->expectsOutputToContain('Deployment sent to Nightwatch successfully.')
->assertExitCode(0);
}

#[WithEnv('NIGHTWATCH_TOKEN', 'test-token')]
public function test_it_can_run_the_deploy_command_without_a_version(): void
{
$this->freezeTime();
Http::fake([
'*/api/deployments' => function (Request $request) {
$this->assertEquals(['Bearer '.env('NIGHTWATCH_TOKEN')], $request->header('Authorization'));
$this->assertEquals([
'v' => 1,
'timestamp' => now()->getTimestamp(),
'version' => '',
], $request->data());

return Http::response('OK');
},
]);

$this->artisan('nightwatch:deploy')
->expectsOutputToContain('Deployment sent to Nightwatch successfully.')
->assertExitCode(0);
}

public function test_it_fails_when_the_deploy_command_is_run_without_a_token(): void
{
$reported = null;
$this->app->make(ExceptionHandler::class)->reportable(function (Throwable $e) use (&$reported) {
$reported = $e;
});
$this->app->singleton(DeployCommand::class, fn () => new DeployCommand(token: null));

$this->artisan('nightwatch:deploy')
->expectsOutputToContain('Please configure the [NIGHTWATCH_TOKEN] environment variable.')
->assertExitCode(0);

$this->assertInstanceOf(NightwatchDeployException::class, $reported);
$this->assertSame('NIGHTWATCH_TOKEN environment variable is not configured.', $reported?->getMessage());
}

#[WithEnv('NIGHTWATCH_TOKEN', 'test-token')]
public function test_it_handles_error_responses(): void
{
$reported = null;
$this->app->make(ExceptionHandler::class)->reportable(function (Throwable $e) use (&$reported) {
$reported = $e;
});
Http::fake([
'*/api/deployments' => Http::response(json_encode(['message' => 'Invalid environment token.']), 403),
]);

$this->artisan('nightwatch:deploy')
->expectsOutputToContain('Deployment could not be sent to Nightwatch: Invalid environment token.')
->assertExitCode(0);

$this->assertInstanceOf(NightwatchDeployException::class, $reported);
$this->assertSame('Invalid environment token.', $reported?->getMessage());
$this->assertInstanceOf(RequestException::class, $reported?->getPrevious());
}

#[WithEnv('NIGHTWATCH_TOKEN', 'test-token')]
public function test_it_handles_http_errors(): void
{
$reported = null;
$this->app->make(ExceptionHandler::class)->reportable(function (Throwable $e) use (&$reported) {
$reported = $e;
});
Http::fake([
'*/api/deployments' => Http::response('Whoops!', 500),
]);

$this->artisan('nightwatch:deploy')
->expectsOutputToContain('Deployment could not be sent to Nightwatch: [500] Whoops!')
->assertExitCode(0);

$this->assertInstanceOf(NightwatchDeployException::class, $reported);
$this->assertSame('[500] Whoops!', $reported?->getMessage());
$this->assertInstanceOf(RequestException::class, $reported?->getPrevious());
}

#[WithEnv('NIGHTWATCH_TOKEN', 'test-token')]
public function test_it_handles_connection_errors(): void
{
$reported = null;
$this->app->make(ExceptionHandler::class)->reportable(function (Throwable $e) use (&$reported) {
$reported = $e;
});
Http::fake([
'*/api/deployments' => fn () => throw new ConnectionException('Connection timeout.'),
]);

$this->artisan('nightwatch:deploy')
->expectsOutputToContain('Deployment could not be sent to Nightwatch: Connection timeout.')
->assertExitCode(0);

$this->assertInstanceOf(NightwatchDeployException::class, $reported);
$this->assertSame('Connection timeout.', $reported?->getMessage());
$this->assertInstanceOf(ConnectionException::class, $reported?->getPrevious());
}
}