diff --git a/README.md b/README.md index 7a6923b..9eaffa3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/Commands/RunCommand.php b/src/Commands/RunCommand.php index 21f6df9..9117bc5 100644 --- a/src/Commands/RunCommand.php +++ b/src/Commands/RunCommand.php @@ -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. @@ -47,6 +49,7 @@ public function handle(Runner $runner): int $this->components->twoColumnDetail($name, "{$duration}s DONE"); $this->newLine(); }, + operation: $this->argument('operation'), ); $this->components->info($count ? "Completed {$count} operation(s)." : 'No pending operations.'); diff --git a/src/Runner.php b/src/Runner.php index 9209d98..8414d60 100644 --- a/src/Runner.php +++ b/src/Runner.php @@ -5,6 +5,7 @@ use Closure; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; +use InvalidArgumentException; use UnexpectedValueException; class Runner @@ -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; } @@ -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 + */ + 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]]; + } } diff --git a/tests/Feature/RunSelectedTest.php b/tests/Feature/RunSelectedTest.php new file mode 100644 index 0000000..c33aff1 --- /dev/null +++ b/tests/Feature/RunSelectedTest.php @@ -0,0 +1,82 @@ +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", ' 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.'); +}); diff --git a/tests/Feature/RunTest.php b/tests/Feature/RunTest.php index c71a74a..1350f23 100644 --- a/tests/Feature/RunTest.php +++ b/tests/Feature/RunTest.php @@ -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; @@ -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(); }); @@ -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(); }); @@ -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(); @@ -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', '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')); @@ -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' - 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); -});