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
80 changes: 80 additions & 0 deletions src/Console/DeployCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?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 SensitiveParameter;
use Symfony\Component\Console\Attribute\AsCommand;
use Throwable;

use function config;

/**
* @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
{
$start = CarbonImmutable::now();

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

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' => $start->toDateTimeString('microsecond'),
'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

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

return 0;
}
}
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
107 changes: 107 additions & 0 deletions tests/Feature/Console/DeployCommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

namespace Tests\Feature\Console;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Laravel\Nightwatch\Console\DeployCommand;
use Orchestra\Testbench\Attributes\WithEnv;
use Tests\TestCase;

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()->toDateTimeString('microsecond'),
'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()->toDateTimeString('microsecond'),
'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
{
$this->app->singleton(DeployCommand::class, fn () => new DeployCommand(token: null));

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

#[WithEnv('NIGHTWATCH_TOKEN', 'test-token')]
public function test_it_handles_error_responses(): void
{
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);
}

#[WithEnv('NIGHTWATCH_TOKEN', 'test-token')]
public function test_it_handles_http_errors(): void
{
Http::fake([
'*/api/deployments' => Http::response('Whoops!', 500),
]);

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

#[WithEnv('NIGHTWATCH_TOKEN', 'test-token')]
public function test_it_handles_connection_errors(): void
{
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);
}
}