Skip to content
Merged
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
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,46 @@ The runner stops when an operation throws an exception. The command fails, the o

The filename without `.php` is the operation's identity. Keep completed filenames unchanged and create another operation when you need a correction. Operations do not support rollbacks.

To run a single pending operation, pass its exact filename without `.php`:

```bash
php artisan operations:run 2026_10_03_120000_backfill_company_names
```

The name must contain only letters, numbers, underscores, and hyphens. Paths, the `.php` extension, and partial names are not accepted. Invalid or unknown names fail without running any operations.

Only the selected operation runs. It uses the same transaction support and completion ledger as a full run, and is skipped if already completed. Its file must still exist, even if it has a completion record.

### Testing Operations

Call the command from a Laravel/Pest feature test to exercise a specific operation:

```php
use App\Models\Company;
use Illuminate\Foundation\Testing\RefreshDatabase;

use function Pest\Laravel\artisan;

uses(RefreshDatabase::class);

test('company names are backfilled', function () {
$company = Company::factory()->create([
'name' => 'Acme',
'display_name' => null,
]);

artisan('operations:run', [
'operation' => '2026_10_03_120000_backfill_company_names',
])->assertSuccessful();

expect($company->fresh()->display_name)->toBe('Acme');
});
```

Use your application's Laravel test case and a dedicated test database with the published operations migration. `RefreshDatabase` resets the completion ledger between tests; invoking the same operation twice within a test skips it on the second call. If you configure a separate `operations.connection`, point it to a test database and include it in your database reset setup.

To test whether an operation can safely resume after partial work, create that partial state without a completion record, run the operation, and assert the expected result. Running a completed operation again only verifies that it is skipped.

### Checking Status

```bash
Expand Down
7 changes: 5 additions & 2 deletions src/Commands/RunCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@ class RunCommand extends Command implements Isolatable
*
* @var string
*/
protected $signature = 'operations:run {--force : Run operations in production without confirmation}';
protected $signature = 'operations:run
{operation? : The exact operation filename without the .php extension}
{--force : Run operations in production without confirmation}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Run all pending deployment operations';
protected $description = 'Run pending deployment operations';

/**
* Execute the console command.
Expand All @@ -47,6 +49,7 @@ public function handle(Runner $runner): int
$this->components->twoColumnDetail($name, "<fg=gray>{$duration}s</> <fg=green;options=bold>DONE</>");
$this->newLine();
},
operation: $this->argument('operation'),
);

$this->components->info($count ? "Completed {$count} operation(s)." : 'No pending operations.');
Expand Down
26 changes: 24 additions & 2 deletions src/Runner.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Closure;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use InvalidArgumentException;
use UnexpectedValueException;

class Runner
Expand Down Expand Up @@ -41,12 +42,13 @@ public function files(): array
* @param (Closure(string): void)|null $before
* @param (Closure(string, float): void)|null $after
*/
public function run(Command $command, ?Closure $before = null, ?Closure $after = null): int
public function run(Command $command, ?Closure $before = null, ?Closure $after = null, ?string $operation = null): int
{
$files = $operation === null ? $this->files() : $this->find($operation);
$completed = $this->repository->completed();
$count = 0;

foreach ($this->files() as $name => $path) {
foreach ($files as $name => $path) {
if ($completed->has($name)) {
continue;
}
Expand All @@ -70,4 +72,24 @@ public function run(Command $command, ?Closure $before = null, ?Closure $after =

return $count;
}

/**
* Find an operation by its exact filename without the extension.
*
* @return array<string, string>
*/
protected function find(string $name): array
{
if (! preg_match('/\A[a-zA-Z0-9_-]+\z/', $name)) {
throw new InvalidArgumentException('Use an exact operation filename without .php, containing only letters, numbers, underscores, and hyphens.');
}

$files = $this->files();

if (! isset($files[$name])) {
throw new InvalidArgumentException("Operation [{$name}] not found. Use its exact filename without .php.");
}

return [$name => $files[$name]];
}
}
82 changes: 82 additions & 0 deletions tests/Feature/RunSelectedTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

use function Pest\Laravel\artisan;
use function Pest\Laravel\freezeTime;
use function Pest\Laravel\travel;

test('only the selected operation runs and is skipped after completion', function () {
freezeTime();

File::ensureDirectoryExists(config('operations.path'));

foreach (['2026_10_03_110000_unrelated', '2026_10_03_130000_unrelated'] as $name) {
File::put(config('operations.path')."/{$name}.php", '<?php throw new \RuntimeException("Unrelated operation loaded.");');
}

File::put(config('operations.path').'/2026_10_03_120000_selected.php', <<<'PHP'
<?php

return new class extends \DirectoryTree\Operations\Operation {
public function handle(\Illuminate\Console\Command $command): void
{
$command->info('Selected operation executed.');
}
};
PHP);

artisan('operations:run', ['operation' => '2026_10_03_120000_selected'])
->expectsOutputToContain('Selected operation executed.')
->expectsOutputToContain('Completed 1 operation(s).')
->assertSuccessful();

$completedAt = DB::table('operations')->value('completed_at');

travel(1)->minute();

artisan('operations:run', ['operation' => '2026_10_03_120000_selected'])
->expectsOutputToContain('No pending operations.')
->assertSuccessful();

expect(DB::table('operations')->pluck('name')->all())->toBe(['2026_10_03_120000_selected'])
->and($completedAt)->not->toBeNull()
->and(DB::table('operations')->value('completed_at'))->toBe($completedAt);
});

test('invalid selections fail clearly without loading any operations', function (string $operation, string $message) {
File::ensureDirectoryExists(config('operations.path'));

foreach (['2026_10_03_120000_backfill', '2026_10_03_130000_backfill'] as $name) {
File::put(config('operations.path')."/{$name}.php", '<?php throw new \RuntimeException("Unrelated operation loaded.");');
}

expect(fn () => artisan('operations:run', [
'operation' => $operation,
])->run())->toThrow(InvalidArgumentException::class, $message);

expect(DB::table('operations')->count())->toBe(0);
})->with([
'missing filename' => ['2026_10_03_140000_missing', 'not found'],
'ambiguous suffix' => ['backfill', 'not found'],
'ambiguous prefix' => ['2026_10_03', 'not found'],
'empty argument' => ['', 'Use an exact operation filename'],
'whitespace' => [' ', 'Use an exact operation filename'],
'extension' => ['2026_10_03_120000_backfill.php', 'Use an exact operation filename'],
'relative path' => ['./2026_10_03_120000_backfill', 'Use an exact operation filename'],
'absolute path' => ['/2026_10_03_120000_backfill', 'Use an exact operation filename'],
'traversal' => ['../2026_10_03_120000_backfill', 'Use an exact operation filename'],
'windows traversal' => ['..\\2026_10_03_120000_backfill', 'Use an exact operation filename'],
'wildcard' => ['2026_10_03_*', 'Use an exact operation filename'],
]);

test('a selected filename must exist even when already completed', function () {
DB::table('operations')->insert([
'name' => '2026_10_03_120000_missing',
'completed_at' => now(),
]);

expect(fn () => artisan('operations:run', ['operation' => '2026_10_03_120000_missing'])->run())
->toThrow(InvalidArgumentException::class, 'Operation [2026_10_03_120000_missing] not found.');
});
45 changes: 9 additions & 36 deletions tests/Feature/RunTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@
use DirectoryTree\Operations\Tests\Fixtures\ExampleJob;
use Illuminate\Database\QueryException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;

use function Pest\Laravel\artisan;

Expand Down Expand Up @@ -84,7 +81,7 @@ public function handle(\Illuminate\Console\Command $command): void
])->and(DB::table('operations')->count())->toBe(3);
});

test('a transaction rolls back database changes when an operation fails', function () {
test('a transaction rolls back database changes when an operation fails', function (?string $operation) {
Schema::create('examples', function (Blueprint $table) {
$table->id();
});
Expand All @@ -103,13 +100,13 @@ public function handle(\Illuminate\Console\Command $command): void
};
PHP);

expect(fn () => app(Runner::class)->run(app(RunCommand::class)))->toThrow(RuntimeException::class, 'Backfill failed.');
expect(fn () => Artisan::call('operations:run', ['operation' => $operation]))->toThrow(RuntimeException::class, 'Backfill failed.');

expect(DB::table('examples')->count())->toBe(0)
->and(DB::table('operations')->count())->toBe(0);
});
})->with([null, '2026_10_02_120000_backfill']);

test('a transaction rolls back the operation if recording completion fails', function () {
test('a transaction rolls back the operation if recording completion fails', function (?string $operation) {
Schema::create('examples', function (Blueprint $table) {
$table->id();
});
Expand All @@ -130,11 +127,11 @@ public function handle(\Illuminate\Console\Command $command): void
};
PHP);

expect(fn () => app(Runner::class)->run(app(RunCommand::class)))->toThrow(QueryException::class);
expect(fn () => Artisan::call('operations:run', ['operation' => $operation]))->toThrow(QueryException::class);

expect(DB::table('examples')->count())->toBe(0)
->and(DB::table('operations')->count())->toBe(0);
});
})->with([null, '2026_10_02_120000_backfill']);

test('operations can dispatch jobs without becoming queued operations themselves', function () {
Bus::fake();
Expand All @@ -159,14 +156,14 @@ public function handle(\Illuminate\Console\Command $command): void
expect(DB::table('operations')->count())->toBe(1);
});

test('completed operation files are not loaded on subsequent runs', function () {
test('completed operation files are not loaded on subsequent runs', function (?string $operation) {
File::ensureDirectoryExists(config('operations.path'));
File::put(config('operations.path').'/2026_10_02_120000_old.php', '<?php throw new \RuntimeException("Obsolete dependency.");');

DB::table('operations')->insert(['name' => '2026_10_02_120000_old', 'completed_at' => now()]);

artisan('operations:run')->expectsOutputToContain('No pending operations.')->assertSuccessful();
});
artisan('operations:run', ['operation' => $operation])->expectsOutputToContain('No pending operations.')->assertSuccessful();
})->with([null, '2026_10_02_120000_old']);

test('invalid operation files fail without being recorded', function () {
File::ensureDirectoryExists(config('operations.path'));
Expand Down Expand Up @@ -197,27 +194,3 @@ public function handle(\Illuminate\Console\Command $command): void
test('a missing operations directory has no pending work', function () {
artisan('operations:run')->expectsOutputToContain('No pending operations.')->assertSuccessful();
});

test('operation exceptions produce a failing console exit code', function () {
File::ensureDirectoryExists(config('operations.path'));
File::put(config('operations.path').'/2026_10_02_120000_failure.php', <<<'PHP'
<?php

return new class extends \DirectoryTree\Operations\Operation {
public function handle(\Illuminate\Console\Command $command): void
{
throw new \RuntimeException('Backfill failed.');
}
};
PHP);

$output = new BufferedOutput;
// Testbench rethrows console exceptions; use Laravel's kernel to verify the exit code.
$kernel = new Kernel(app(), app('events'));
$kernel->registerCommand(app(RunCommand::class));
$exitCode = $kernel->handle(new ArrayInput(['command' => 'operations:run']), $output);

expect($exitCode)->toBe(1)
->and($output->fetch())->toContain('Backfill failed.')
->and(DB::table('operations')->count())->toBe(0);
});
Loading