diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index 9c32e4e..0913b3d 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -41,10 +41,18 @@ jobs: - uses: actions/checkout@v6 with: ref: ${{ github.head_ref }} - - name: "laravel-pint" - uses: aglipanci/laravel-pint-action@latest + - name: Setup PHP + uses: shivammathur/setup-php@master with: - configPath: './pint.json' + php-version: '8.4' + coverage: none + + - name: Install dependencies + run: composer install --prefer-dist --no-progress + + # The project's own Pint (composer.json), so CI formats as a local run does. + - name: Pint + run: vendor/bin/pint --config pint.json - name: Commit changes uses: stefanzweifel/git-auto-commit-action@v7 diff --git a/composer.json b/composer.json index ad31bfc..b02e253 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,8 @@ }, "require-dev": { "phpunit/phpunit": "^13.4.3", - "mockery/mockery": "^1.6.15" + "mockery/mockery": "^1.6.15", + "laravel/pint": "^1.32.1" }, "autoload": { "psr-4": { diff --git a/pint.json b/pint.json new file mode 100644 index 0000000..93061b6 --- /dev/null +++ b/pint.json @@ -0,0 +1,3 @@ +{ + "preset": "laravel" +} diff --git a/src/Console/Commands/InstallCommand.php b/src/Console/Commands/InstallCommand.php index d834d76..3750439 100644 --- a/src/Console/Commands/InstallCommand.php +++ b/src/Console/Commands/InstallCommand.php @@ -4,6 +4,7 @@ use Illuminate\Console\Command; use Illuminate\Console\View\TaskResult; +use Illuminate\Contracts\Process\ProcessResult; use Illuminate\Support\Facades\Process; use Illuminate\Support\Str; use Laravel\Prompts\Elements\Element; @@ -111,10 +112,22 @@ public function path(string $relative = ''): string */ public function runArtisan(array $args, int $timeout = 120): bool { - return Process::path($this->targetPath()) + return $this->remember(Process::path($this->targetPath()) ->timeout($timeout) - ->run([PHP_BINARY, $this->path('artisan'), ...$args]) - ->successful(); + ->run([PHP_BINARY, $this->path('artisan'), ...$args])); + } + + /** The last lines a failed step wrote, so its warning can say why. */ + protected ?string $lastFailure = null; + + /** The install task that failed, named in the failure box when the driver didn't name a step. */ + protected ?string $failedTask = null; + + private function remember(ProcessResult $result): bool + { + $this->lastFailure = $result->successful() ? null : trim($result->output()."\n".$result->errorOutput()); + + return $result->successful(); } public function getSelectedStack(): ?string @@ -286,10 +299,9 @@ public function installCore(): bool /** @param string[] $command */ public function runProcess(array $command, int $timeout = 300): bool { - return Process::path($this->targetPath()) + return $this->remember(Process::path($this->targetPath()) ->timeout($timeout) - ->run($command) - ->successful(); + ->run($command)); } /** A contributor checkout runs the UI from saucebase/core instead of owning a copy. */ @@ -331,12 +343,7 @@ public function install(): int $this->generateApplicationKey(); - $installed = false; - $this->task('Installing Saucebase', function () use (&$installed) { - return $installed = $this->installCore(); - }); - - if (! $installed) { + if (! $this->installSaucebase()) { return self::FAILURE; } @@ -490,7 +497,8 @@ public function nameProject(): void protected function applyIdentityToEnv(string $env, string $name, string $slug, string $host, bool $native = false): string { $replaceable = [ - 'APP_NAME' => [['Laravel', 'Saucebase'], str_contains($name, ' ') ? "\"{$name}\"" : $name], + // Quoted when dotenv would misread it bare; inside the quotes, \ and " are escaped. + 'APP_NAME' => [['Laravel', 'Saucebase'], preg_match('/[\s"\\\\$#]/', $name) ? '"'.addcslashes($name, '"\\').'"' : $name], 'APP_SLUG' => [['saucebase'], $slug], ]; @@ -502,16 +510,23 @@ protected function applyIdentityToEnv(string $env, string $name, string $slug, s } } + // Read before APP_HOST is overwritten: a URL on the host chosen last time is ours. + $previousHost = self::readEnvLine($env, 'APP_HOST'); + // Always authoritative: the certificate and nginx config are generated from the // resolved domain, so APP_HOST must agree with them. A user's own value is not // lost — it is what captureDomain() offers as the prompt default. $env = self::setEnvLine($env, 'APP_HOST', $host); - // Native serves on whatever laravel/installer already wrote for localhost - // (http://localhost:8000, which is what `composer dev` binds); only a custom - // host needs correcting here. - if ($native && $host !== 'localhost') { - $env = self::setEnvLine($env, 'APP_URL', 'http://'.$host); + // Only a URL the installer wrote follows the host, keeping its scheme and port: native's + // localhost one is laravel/installer's http://localhost:8000, what `composer dev` binds. + // Docker's localhost URL is applyDockerEnvDefaults()'s, which also sets scheme and port. + $url = self::readEnvLine($env, 'APP_URL'); + $urlHost = $url === null ? null : parse_url($url, PHP_URL_HOST); + $ours = array_filter([$native ? 'localhost' : null, $previousHost]); + + if (is_string($urlHost) && $urlHost !== $host && in_array($urlHost, $ours, true)) { + $env = self::setEnvLine($env, 'APP_URL', (string) preg_replace('#^(https?://)[^/:]+#', '${1}'.$host, $url)); } return $env; @@ -530,8 +545,9 @@ public static function setEnvLine(string $env, string $key, string $value): stri { $pattern = '/^'.preg_quote($key, '/').'=.*$/m'; + // A callback, so the value is written as given: preg_replace would read $0 or \1 in it as backreferences. return preg_match($pattern, $env) - ? preg_replace($pattern, "{$key}={$value}", $env) + ? preg_replace_callback($pattern, fn () => "{$key}={$value}", $env) : rtrim($env, "\n")."\n{$key}={$value}\n"; } @@ -567,18 +583,19 @@ protected function generateApplicationKey(): void }); } + /** Composer and core's own install; a failure says why, like every install step. */ + protected function installSaucebase(): bool + { + return $this->runInstallTask('Installing Saucebase', [], fn () => $this->installCore()); + } + protected function setupDatabase(): bool { $fresh = $this->option('fresh'); $label = $fresh ? 'Running migrate:fresh --seed' : 'Running migrations'; $command = $fresh ? 'migrate:fresh' : 'migrate'; - $ok = false; - - $this->task($label, function () use ($command, &$ok) { - return $ok = $this->runArtisan([$command, '--seed', '--force'], 300); - }); - return $ok; + return $this->runInstallTask($label, [$command, '--seed', '--force'], fn (array $args) => $this->runArtisan($args, 300)); } /** False when a selected module could not be wired into the application. */ @@ -595,12 +612,16 @@ protected function setupModules(): bool return true; } - // Fast path: skip Packagist discovery when all requested names are fully qualified + // Named modules need no discovery: a short name is one of Saucebase's, as in + // core's template-install. Private modules aren't on Packagist; Composer says + // so if a name doesn't exist. if ($opt) { - $names = array_values(array_filter(array_map(fn ($n) => strtolower(trim($n)), explode(',', $opt)))); - if ($names && ! array_filter($names, fn ($n) => ! str_contains($n, '/'))) { - return $this->doInstallModules($names); - } + return $this->doInstallModules(collect(explode(',', $opt)) + ->map(fn (string $name) => strtolower(trim($name))) + ->filter() + ->map(fn (string $name) => str_contains($name, '/') ? $name : 'saucebase/'.$name) + ->values() + ->all()); } if (! $opt && empty($this->selectedModules) && ! $this->option('all-modules')) { @@ -717,7 +738,16 @@ private function runInstallTask(string $label, array $command, \Closure $run): b }); if (! $ok) { - $this->components->warn("{$label} failed. Run it again to see why: ".implode(' ', array_diff($command, ['--no-interaction']))); + // ANSI codes and blank lines out; the end of the output is where the reason is. + $why = collect(explode("\n", (string) preg_replace('/\e\[[0-9;]*m/', '', (string) $this->lastFailure))) + ->map(fn (string $line) => trim($line))->filter() + // Composer's progress, per-package and usage lines bury the reason. + ->reject(fn (string $line) => (bool) preg_match('/^(\d+(\/\d+)? \[|- (Installing|Downloading|Locking|Excluded)|require \[|Loading composer|Updating dependencies|Lock file operations|Writing lock file|Installing dependencies|Package operations|Generating .*autoload)/', $line)) + ->take(-12)->implode("\n"); + // The reason only: the failure box's resume command reruns this step and every + // one after it (the build, HTTPS); re-running this one alone would skip them. + $this->failedTask = $label; + $this->components->warn("{$label} failed".($why !== '' ? ":\n{$why}" : '.')); } return $ok; @@ -742,22 +772,6 @@ protected function resolveModuleSelection(array $available): array return $available; } - // 2. Modules passed via --modules option - if ($modules = $this->option('modules')) { - $requested = collect(explode(',', $modules)) - ->map(fn ($m) => strtolower(trim($m))) - ->filter() - ->values(); - - return collect($available) - ->filter(function (string $package) use ($requested) { - return $requested->contains(strtolower($package)) - || $requested->contains(strtolower(Str::after($package, '/'))); - }) - ->values() - ->all(); - } - return $this->selectedModules; } @@ -829,6 +843,8 @@ public function displayFailure(?string $step = null, array $resumeOptions = []): /** @return array */ protected function failureCalloutContent(?string $step): array { + $step ??= $this->failedTask; + return array_values(array_filter([ $step ? "Failed at: {$step}" : null, 'Your application directory is intact — nothing was rolled back.', @@ -854,10 +870,20 @@ public function resumeCommand(array $resumeOptions = []): string $command .= ' '.$this->selectedStack; } + // Herd's choice is only on the command line; Docker's comes back resolved. + if (! isset($resumeOptions['--ssl']) && ($ssl = $this->optionOrNull('ssl'))) { + $resumeOptions['--ssl'] = $ssl; + } + foreach ($resumeOptions as $option => $value) { $command .= " {$option}={$value}"; } + // Free text: quoted, so a name with spaces or quotes survives the shell. + if ($name = $this->optionOrNull('app-name')) { + $command .= ' --app-name='.escapeshellarg($name); + } + if ($this->domain !== null) { $command .= ' --domain='.$this->domain; } diff --git a/src/Console/Commands/NewCommand.php b/src/Console/Commands/NewCommand.php index 846102c..4febd0d 100644 --- a/src/Console/Commands/NewCommand.php +++ b/src/Console/Commands/NewCommand.php @@ -66,7 +66,9 @@ public function handle(): int $ssl = $this->ssl($driver); - if ($ssl === true && ! $driver->hasCommand('mkcert')) { + // Docker's certificates come from mkcert: checked here, before the project exists, so a + // missing one leaves nothing half-made. Herd secures with `herd secure` instead. + if ($ssl === true && $driver->name() === 'docker' && ! $driver->hasCommand('mkcert')) { $this->error('mkcert is required for SSL. Install it with: brew install mkcert'); $this->info('Official mkcert installation instructions: https://github.com/FiloSottile/mkcert'); diff --git a/src/Console/Commands/StackCommand.php b/src/Console/Commands/StackCommand.php index 0c52d6a..60d8eff 100644 --- a/src/Console/Commands/StackCommand.php +++ b/src/Console/Commands/StackCommand.php @@ -126,9 +126,22 @@ private function runDevMode(string $framework): int $this->info("Framework set to {$framework} (dev mode)"); + // A template's own files (CSS, page shell, tsconfig) are core's to put back, not this command's. + if (is_string($this->projectJson()['template'] ?? null)) { + $this->line('Template workspace: run `'.$this->inWorkspace('php artisan saucebase:template-capture --restore').'` to put its files back for this stack.'); + } + return self::SUCCESS; } + /** A command for the workspace to run: from elsewhere (--path), it goes there first. */ + private function inWorkspace(string $command): string + { + return realpath($this->basePath) === realpath((string) getcwd()) + ? $command + : 'cd '.escapeshellarg($this->basePath)." && {$command}"; + } + private function runReset(): int { $framework = $this->getSelectedFramework(); @@ -140,14 +153,21 @@ private function runReset(): int } if ($this->cssEdited() && ! $this->option('force')) { - $this->error('resources/css has changes that are not in saucebase/core. Run `saucebase stack --sync` ' - .'to keep them, or `saucebase stack --reset --force` to discard them.'); + // A template's CSS belongs in its stubs, never in core: --sync would push it there. + $this->error(is_string($this->projectJson()['template'] ?? null) + ? 'resources/css differs from saucebase/core. Keep template changes with `'.$this->inWorkspace('php artisan saucebase:template-capture').'`, ' + .'then run `'.$this->inWorkspace('saucebase stack --reset --force').'`.' + : 'resources/css has changes that are not in saucebase/core. Run `saucebase stack --sync` ' + .'to keep them, or `saucebase stack --reset --force` to discard them.'); return self::FAILURE; } $this->info("Resetting framework '{$framework}'..."); + // What the workspace set itself (the template it builds, say) outlives the stack. + $kept = array_diff_key($this->projectJson(), array_flip(['framework', 'contributor'])); + $this->restoreTrackedFiles($framework); foreach ($this->generatedFiles($framework) as $file) { @@ -168,6 +188,13 @@ private function runReset(): int $this->files->delete($lockfile); } + if ($kept !== []) { + $this->files->put( + $this->basePath.'/saucebase.json', + json_encode([...$this->projectJson(), ...$kept], JSON_PRETTY_PRINT).PHP_EOL, + ); + } + $this->info('Reset complete. Run: npm install to restore base dependencies.'); return self::SUCCESS; diff --git a/src/Environments/DockerEnvironment.php b/src/Environments/DockerEnvironment.php index 974e204..60001bf 100644 --- a/src/Environments/DockerEnvironment.php +++ b/src/Environments/DockerEnvironment.php @@ -825,12 +825,24 @@ protected function createStorageLink(InstallCommand $command): void $this->execInContainer($command, ['php', 'artisan', 'storage:link']); } + protected function printedArtisan(): string + { + return 'docker compose exec app php artisan'; + } + /** Inside the app container: on the host, `.env` points at hostnames only Docker resolves. */ protected function artisan(InstallCommand $command, array $args): bool { return $this->execInContainer($command, ['php', 'artisan', ...$args], quiet: true); } + protected function artisanOutput(InstallCommand $command, array $args): ?string + { + $result = Process::path($command->targetPath())->timeout(120)->run(['docker', 'compose', 'exec', '-T', 'app', 'php', 'artisan', ...$args]); + + return $result->successful() ? $result->output() : null; + } + protected function clearCaches(InstallCommand $command): void { $command->info('Clearing caches...'); diff --git a/src/Environments/Environment.php b/src/Environments/Environment.php index d73afdb..46d33ff 100644 --- a/src/Environments/Environment.php +++ b/src/Environments/Environment.php @@ -3,7 +3,6 @@ namespace Saucebase\Installer\Environments; use Illuminate\Support\Facades\Process; -use Illuminate\Support\Str; use Saucebase\Installer\Console\Commands\InstallCommand; abstract class Environment @@ -89,6 +88,18 @@ protected function artisan(InstallCommand $command, array $args): bool return $command->runArtisan($args); } + /** + * An artisan command's output, or null when it fails. + * + * @param string[] $args + */ + protected function artisanOutput(InstallCommand $command, array $args): ?string + { + $result = Process::path($command->targetPath())->timeout(120)->run([PHP_BINARY, $command->path('artisan'), ...$args]); + + return $result->successful() ? $result->output() : null; + } + /** Record which step failed, then return FAILURE for boot() to propagate. */ protected function fail(string $step): int { @@ -136,26 +147,36 @@ protected function demoStep(InstallCommand $command): array { $password = ($command->optionOrNull('demo') || $command->optionOrNull('template')) ? $this->readEnvValue($command, 'DEMO_PASSWORD') : null; + // No demo accounts: with auth, the owner's own account has to become the admin. if ($password === null) { - return []; + return is_dir($command->path('modules/auth')) + ? ['Sign up, then make your account the admin: `'.$this->printedArtisan().' auth:make-admin you@example.com`'] + : []; } - // A template's demo seeds its own accounts, and may name the one to sign in with - // (`extra.saucebase.demo_account`). Without a template, auth's demo admin sees everything. - $template = $command->optionOrNull('template'); - $account = match (true) { - $template !== null => json_decode((string) @file_get_contents($command->path('modules/'.Str::afterLast($template, '/').'/composer.json')), true)['extra']['saucebase']['demo_account'] ?? null, - $command->optionOrNull('demo') && is_dir($command->path('modules/auth')) => '`chef@saucebase.dev` (admin)', - default => null, - }; - - if (is_string($account) && $account !== '' && $template !== null) { - $account = "`{$account}`"; + // The state that was seeded: a template's demo is its `default`, a module demo the + // `showcase`. Its seeders declare their accounts (#[DemoAccount]); the featured + // ones are where to start. + $state = $command->optionOrNull('state') + ?: ($command->optionOrNull('demo') ? ($command->optionOrNull('template') ? 'default' : 'showcase') : null); + $featured = $state === null ? [] : array_values(array_filter( + json_decode((string) $this->artisanOutput($command, ['modules:demo-accounts', "--state={$state}", '--json']), true) ?: [], + fn (array $account): bool => (bool) ($account['featured'] ?? false), + )); + + if ($featured === []) { + return ["Demo accounts use the password `{$password}`, saved in .env as DEMO_PASSWORD"]; } - return [is_string($account) && $account !== '' - ? "Sign in as {$account} with the password `{$password}`. Every demo account uses it; it is saved in .env as DEMO_PASSWORD" - : "Demo accounts use the password `{$password}`, saved in .env as DEMO_PASSWORD"]; + $accounts = implode(' or ', array_map(fn (array $account): string => "`{$account['email']}` ({$account['description']})", $featured)); + + return ["Sign in as {$accounts} with the password `{$password}`, saved in .env as DEMO_PASSWORD. Every demo account: `{$this->printedArtisan()} modules:demo-accounts --state={$state}`"]; + } + + /** How the user runs artisan in the new app, for the commands printed at the end. */ + protected function printedArtisan(): string + { + return 'php artisan'; } /** Hook: perform driver-specific steps before the module prompt. Return an exit code to abort, null to continue. */ diff --git a/tests/Feature/Environments/EnvironmentHelpersTest.php b/tests/Feature/Environments/EnvironmentHelpersTest.php index df1b775..4fd423e 100644 --- a/tests/Feature/Environments/EnvironmentHelpersTest.php +++ b/tests/Feature/Environments/EnvironmentHelpersTest.php @@ -3,6 +3,7 @@ namespace Saucebase\Installer\Tests\Feature\Environments; use Saucebase\Installer\Console\Commands\InstallCommand; +use Saucebase\Installer\Environments\DockerEnvironment; use Saucebase\Installer\Environments\NativeEnvironment; use Saucebase\Installer\Tests\TestCase; @@ -98,47 +99,54 @@ public function test_a_demo_install_tells_the_user_the_demo_password(): void $this->assertStringContainsString('`s3cret`', $steps[0]); } - public function test_with_auth_it_names_the_admin_account_to_sign_in_with(): void + /** The accounts come from the app: what the state's seeders declare (`modules:demo-accounts`). */ + public function test_a_demo_names_its_featured_accounts_to_sign_in_with(): void { file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); - mkdir($this->tmp.'/modules/auth', recursive: true); + $environment = $this->environment([ + ['module' => 'auth', 'email' => 'chef@saucebase.dev', 'description' => 'admin, sees everything', 'featured' => true], + ['module' => 'auth', 'email' => 'support@saucebase.dev', 'description' => 'support staff', 'featured' => false], + ['module' => 'tenancy', 'email' => 'owner@saucebase.dev', 'description' => 'owns Acme and Globex', 'featured' => true], + ]); - $steps = $this->environment()->exposedDemoStep($this->command(demo: true)); + $steps = $environment->exposedDemoStep($this->command(demo: true)); - $this->assertSame(['Sign in as `chef@saucebase.dev` (admin) with the password `s3cret`. Every demo account uses it; it is saved in .env as DEMO_PASSWORD'], $steps); + $this->assertSame(['--state=showcase'], array_values(array_filter($environment->asked, fn (string $arg) => str_starts_with($arg, '--state')))); + $this->assertSame(['Sign in as `chef@saucebase.dev` (admin, sees everything) or `owner@saucebase.dev` (owns Acme and Globex) with the password `s3cret`, saved in .env as DEMO_PASSWORD. Every demo account: `php artisan modules:demo-accounts --state=showcase`'], $steps); } - /** A template seeds its own accounts; auth's demo admin is only there with --demo. */ - public function test_a_template_without_demo_content_names_no_admin_account(): void + /** A template's demo is its default state, and names the template's own account. */ + public function test_a_template_demo_names_the_templates_own_account(): void { file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); - mkdir($this->tmp.'/modules/auth', recursive: true); + $environment = $this->environment([ + ['module' => 'uptime', 'email' => 'uptime@saucebase.dev', 'description' => 'owns the demo sites', 'featured' => true], + ]); - $steps = $this->environment()->exposedDemoStep($this->command(template: 'saucebase/uptime')); + $steps = $environment->exposedDemoStep($this->command(demo: true, template: 'saucebase/uptime')); - $this->assertSame(['Demo accounts use the password `s3cret`, saved in .env as DEMO_PASSWORD'], $steps); + $this->assertContains('--state=default', $environment->asked); + $this->assertSame(['Sign in as `uptime@saucebase.dev` (owns the demo sites) with the password `s3cret`, saved in .env as DEMO_PASSWORD. Every demo account: `php artisan modules:demo-accounts --state=default`'], $steps); } - /** A template's demo seeds its own accounts: auth's admin is not among them. */ - public function test_a_template_demo_names_the_templates_own_account(): void + public function test_a_demo_that_features_no_account_gives_the_password_only(): void { file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); - mkdir($this->tmp.'/modules/auth', recursive: true); - mkdir($this->tmp.'/modules/uptime', recursive: true); - file_put_contents($this->tmp.'/modules/uptime/composer.json', json_encode(['extra' => ['saucebase' => ['demo_account' => 'uptime@saucebase.dev']]])); - $steps = $this->environment()->exposedDemoStep($this->command(demo: true, template: 'saucebase/uptime')); + $steps = $this->environment([])->exposedDemoStep($this->command(demo: true, template: 'saucebase/uptime')); - $this->assertSame(['Sign in as `uptime@saucebase.dev` with the password `s3cret`. Every demo account uses it; it is saved in .env as DEMO_PASSWORD'], $steps); + $this->assertSame(['Demo accounts use the password `s3cret`, saved in .env as DEMO_PASSWORD'], $steps); } - public function test_a_template_demo_without_a_named_account_gives_the_password_only(): void + /** Without a demo nothing was seeded: no accounts to look up, only the password. */ + public function test_a_template_without_demo_content_names_no_account(): void { file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); - mkdir($this->tmp.'/modules/auth', recursive: true); + $environment = $this->environment([['module' => 'auth', 'email' => 'chef@saucebase.dev', 'description' => 'admin', 'featured' => true]]); - $steps = $this->environment()->exposedDemoStep($this->command(demo: true, template: 'saucebase/uptime')); + $steps = $environment->exposedDemoStep($this->command(template: 'saucebase/uptime')); + $this->assertSame([], $environment->asked); $this->assertSame(['Demo accounts use the password `s3cret`, saved in .env as DEMO_PASSWORD'], $steps); } @@ -149,6 +157,40 @@ public function test_without_demo_content_no_password_is_shown(): void $this->assertSame([], $this->environment()->exposedDemoStep($this->command())); } + /** A clean install has no accounts: the owner signs up, then makes that account the admin. */ + public function test_without_demo_content_auth_says_how_to_become_admin(): void + { + mkdir($this->tmp.'/modules/auth', recursive: true); + + $this->assertSame( + ['Sign up, then make your account the admin: `php artisan auth:make-admin you@example.com`'], + $this->environment()->exposedDemoStep($this->command()), + ); + } + + /** On Docker, `.env` names hosts only the containers resolve: the commands it prints run in the app container. */ + public function test_docker_prints_its_artisan_commands_for_the_container(): void + { + $docker = new class extends DockerEnvironment + { + protected function artisanOutput(InstallCommand $command, array $args): ?string + { + return (string) json_encode([['email' => 'chef@saucebase.dev', 'description' => 'admin', 'featured' => true]]); + } + + public function exposedDemoStep(InstallCommand $command): array + { + return $this->demoStep($command); + } + }; + mkdir($this->tmp.'/modules/auth', recursive: true); + + $this->assertStringContainsString('`docker compose exec app php artisan auth:make-admin you@example.com`', $docker->exposedDemoStep($this->command())[0]); + + file_put_contents($this->tmp.'/.env', "DEMO_PASSWORD=s3cret\n"); + $this->assertStringContainsString('`docker compose exec app php artisan modules:demo-accounts --state=showcase`', $docker->exposedDemoStep($this->command(demo: true))[0]); + } + private function command(?string $modules = null, ?string $target = null, bool $demo = false, ?string $template = null): InstallCommand { return new class($target ?? $this->tmp, $modules, $demo, $template) extends InstallCommand @@ -185,10 +227,24 @@ public function getSelectedModules(): array }; } - private function environment(): NativeEnvironment + /** @param list> $accounts What `modules:demo-accounts --json` answers. */ + private function environment(array $accounts = []): NativeEnvironment { - return new class extends NativeEnvironment + return new class($accounts) extends NativeEnvironment { + /** @var string[] The artisan arguments asked for. */ + public array $asked = []; + + /** @param list> $accounts */ + public function __construct(private array $accounts) {} + + protected function artisanOutput(InstallCommand $command, array $args): ?string + { + $this->asked = $args; + + return (string) json_encode($this->accounts); + } + public function exposedReadEnvValue(InstallCommand $command, string $key): ?string { return $this->readEnvValue($command, $key); diff --git a/tests/Feature/InstallCommandIdentityTest.php b/tests/Feature/InstallCommandIdentityTest.php index 1e0c055..be1eb59 100644 --- a/tests/Feature/InstallCommandIdentityTest.php +++ b/tests/Feature/InstallCommandIdentityTest.php @@ -29,6 +29,16 @@ public function test_names_the_app_after_its_directory(): void $this->assertStringContainsString('APP_SLUG=my-app', $result); } + /** Whatever the name holds reaches .env as written: no regex backreferences, quotes escaped for dotenv. */ + public function test_an_app_name_with_dollars_or_quotes_is_written_as_typed(): void + { + $command = new TestableInstallCommand; + + $this->assertStringContainsString('APP_NAME="Shop $0 \\\\1"', $command->exposedApplyIdentityToEnv("APP_NAME=Laravel\n", 'Shop $0 \1', 'shop', 'localhost', false)); + $this->assertStringContainsString('APP_NAME="Joe \"Big\" Shop"', $command->exposedApplyIdentityToEnv("APP_NAME=Laravel\n", 'Joe "Big" Shop', 'joe', 'localhost', false)); + $this->assertSame("KEY=a\$0b\n", InstallCommand::setEnvLine("KEY=old\n", 'KEY', 'a$0b')); + } + public function test_names_a_plain_laravel_app_after_its_directory(): void { $result = $this->apply("APP_NAME=Laravel\n"); @@ -102,8 +112,28 @@ public function test_native_sets_app_url_only_for_a_custom_host(): void $localhost = $this->apply("APP_URL=http://localhost:8000\n", native: true); $this->assertStringContainsString('APP_URL=http://localhost:8000', $localhost); + // A custom host keeps the port `composer dev` serves on. $custom = $this->apply("APP_URL=http://localhost:8000\n", host: 'my-app.test', native: true); - $this->assertStringContainsString('APP_URL=http://my-app.test', $custom); + $this->assertStringContainsString("APP_URL=http://my-app.test:8000\n", $custom); + } + + /** The URL on the host the installer chose last time is the installer's: it follows a new host. */ + public function test_a_reinstall_with_a_new_host_moves_the_installers_own_url(): void + { + $native = $this->apply("APP_HOST=old.test\nAPP_URL=http://old.test:8000\n", host: 'new.test', native: true); + $this->assertStringContainsString("APP_URL=http://new.test:8000\n", $native); + + // Docker: the host moves here; applyDockerEnvDefaults() then sets scheme and port for it. + $docker = $this->apply("APP_HOST=old.test\nAPP_URL=https://old.test:8443\n", host: 'new.test', native: false); + $this->assertStringContainsString("APP_URL=https://new.test:8443\n", $docker); + } + + public function test_a_url_the_user_set_is_left_alone(): void + { + $env = "APP_HOST=old.test\nAPP_URL=https://mine.example\n"; + + $this->assertStringContainsString("APP_URL=https://mine.example\n", $this->apply($env, host: 'new.test', native: true)); + $this->assertStringContainsString("APP_URL=https://mine.example\n", $this->apply($env, host: 'new.test', native: false)); } public function test_docker_never_writes_app_url_here(): void diff --git a/tests/Feature/InstallCommandResumeTest.php b/tests/Feature/InstallCommandResumeTest.php index 1f5d1f0..5bec06b 100644 --- a/tests/Feature/InstallCommandResumeTest.php +++ b/tests/Feature/InstallCommandResumeTest.php @@ -63,6 +63,23 @@ public function test_resume_command_carries_the_flags_through(): void $this->assertStringContainsString('--force', $resume); } + /** A name typed once is not lost on resume, whatever it holds: quoted for the shell. */ + public function test_resume_command_keeps_the_app_name_quoted(): void + { + $resume = $this->command(['path' => '/tmp/app', 'app-name' => "Joe's \$hop"])->resumeCommand(); + + $this->assertStringContainsString("--app-name='Joe'\\''s \$hop'", $resume); + } + + /** Herd's `--ssl=no` came from the command line; the driver doesn't add it, so the command must. */ + public function test_resume_command_keeps_an_ssl_choice_the_driver_does_not_carry(): void + { + $resume = $this->command(['path' => '/tmp/app', 'ssl' => 'no'])->resumeCommand(['--driver' => 'herd']); + + $this->assertStringContainsString('--ssl=no', $resume); + $this->assertSame(1, substr_count($this->command(['path' => '/tmp/app', 'ssl' => 'no'])->resumeCommand(['--driver' => 'docker', '--ssl' => 'no']), '--ssl=')); + } + public function test_resume_command_keeps_the_template_and_its_state(): void { $resume = $this->command(['path' => '/tmp/app', 'template' => 'saucebase/uptime', 'state' => 'agency'])->resumeCommand(); diff --git a/tests/Feature/InstallCommandTest.php b/tests/Feature/InstallCommandTest.php index d522476..9369663 100644 --- a/tests/Feature/InstallCommandTest.php +++ b/tests/Feature/InstallCommandTest.php @@ -437,50 +437,6 @@ public function test_all_modules_without_stack_returns_all(): void $this->assertSame(['saucebase/auth', 'saucebase/react-only'], $result); } - // ------------------------------------------------------------------------- - // resolveModuleSelection — --modules= matching - // ------------------------------------------------------------------------- - - public function test_resolve_matches_full_package_name(): void - { - $cmd = new TestableInstallCommand; - $cmd->fakeOptions = ['modules' => 'saucebase/auth']; - - $result = $cmd->exposedResolveModuleSelection(['saucebase/auth', 'saucebase/billing']); - - $this->assertSame(['saucebase/auth'], $result); - } - - public function test_resolve_matches_short_name(): void - { - $cmd = new TestableInstallCommand; - $cmd->fakeOptions = ['modules' => 'auth']; - - $result = $cmd->exposedResolveModuleSelection(['saucebase/auth', 'saucebase/billing']); - - $this->assertSame(['saucebase/auth'], $result); - } - - public function test_resolve_matches_mixed_case_short_name(): void - { - $cmd = new TestableInstallCommand; - $cmd->fakeOptions = ['modules' => 'Auth']; - - $result = $cmd->exposedResolveModuleSelection(['saucebase/auth', 'saucebase/billing']); - - $this->assertSame(['saucebase/auth'], $result); - } - - public function test_resolve_matches_multiple_full_package_names(): void - { - $cmd = new TestableInstallCommand; - $cmd->fakeOptions = ['modules' => 'saucebase/auth,saucebase/billing']; - - $result = $cmd->exposedResolveModuleSelection(['saucebase/auth', 'saucebase/billing', 'saucebase/settings']); - - $this->assertSame(['saucebase/auth', 'saucebase/billing'], $result); - } - // ------------------------------------------------------------------------- // displaySuccess — sequential step numbering // ------------------------------------------------------------------------- @@ -525,6 +481,37 @@ public function fetchAvailableModules(): array $this->assertFalse($cmd->fetchCalled, 'Packagist must not be fetched when all names are fully qualified'); } + /** A short name means one of Saucebase's: a private module isn't on Packagist, and is still installed. */ + public function test_short_names_are_saucebase_modules_even_off_packagist(): void + { + $cmd = new class extends TestableInstallCommand + { + public bool $fetchCalled = false; + + /** @var string[] */ + public array $installed = []; + + public function fetchAvailableModules(): array + { + $this->fetchCalled = true; + + return ['saucebase/auth']; + } + + public function doInstallModules(array $selected, ?\Closure $run = null): bool + { + $this->installed = $selected; + + return true; + } + }; + $cmd->fakeOptions = ['modules' => 'auth, Tenancy,acme/thing']; + $cmd->exposedSetupModules(); + + $this->assertSame(['saucebase/auth', 'saucebase/tenancy', 'acme/thing'], $cmd->installed); + $this->assertFalse($cmd->fetchCalled); + } + private function fakePackagistList(): void { Http::fake([ diff --git a/tests/Feature/InstallModulesRunnerTest.php b/tests/Feature/InstallModulesRunnerTest.php index 52e86ec..632d46a 100644 --- a/tests/Feature/InstallModulesRunnerTest.php +++ b/tests/Feature/InstallModulesRunnerTest.php @@ -2,6 +2,7 @@ namespace Saucebase\Installer\Tests\Feature; +use Illuminate\Support\Facades\Process; use Saucebase\Installer\Console\Commands\InstallCommand; use Saucebase\Installer\Tests\TestCase; @@ -104,6 +105,105 @@ public function test_a_template_installs_clean_through_template_install(): void $this->assertStringNotContainsString('DEMO_PASSWORD=', (string) @file_get_contents($this->tmp.'/.env')); } + /** Installing Saucebase and the migrations fail the same way as a module: with the reason. */ + public function test_a_failed_core_install_or_migration_shows_its_error(): void + { + Process::fake(['*' => Process::result(errorOutput: "SQLSTATE[HY000] [2002] Connection refused\n", exitCode: 1)]); + $command = new class extends TestableInstallCommand + { + /** @var string[] */ + public array $warnings = []; + + public function attempt(string $step): bool + { + $warnings = &$this->warnings; + $this->components = new class($warnings) + { + /** @param string[] $warnings */ + public function __construct(private array &$warnings) {} + + public function task(string $label, callable $task): void + { + $task(); + } + + public function warn(string $message): void + { + $this->warnings[] = $message; + } + }; + + return $step === 'core' ? $this->installSaucebase() : $this->setupDatabase(); + } + + public function newLine($count = 1): static + { + return $this; + } + }; + $command->fakeOptions = ['path' => $this->tmp]; + $command->setSelectedStack('vue'); + + foreach (['core' => 'Installing Saucebase', 'database' => 'Running migrations'] as $step => $label) { + $command->warnings = []; + + $this->assertFalse($command->attempt($step)); + $this->assertStringContainsString('Connection refused', implode("\n", $command->warnings)); + $this->assertSame("Failed at: {$label}", $command->exposedFailureCalloutContent(null)[0]); + } + } + + /** A failed step shows why, not only how to run it again. */ + public function test_a_failed_step_shows_its_error(): void + { + Process::fake([ + '*' => Process::result(output: "Installing...\n", errorOutput: "Loading composer repositories with package information\nPackage operations: 16 installs, 0 updates, 0 removals\n 0 [>---]\n - Installing saucebase/notes (dev-dev): Extracting archive\n 0/16 [>---] 0%\n saucebase/notes does not support react.\nrequire [--dev] [--dry-run] [...]\n", exitCode: 1), + ]); + $command = new class extends TestableInstallCommand + { + /** @var string[] */ + public array $warnings = []; + + public function installDefault(): bool + { + $warnings = &$this->warnings; + $this->components = new class($warnings) + { + /** @param string[] $warnings */ + public function __construct(private array &$warnings) {} + + public function task(string $label, callable $task): void + { + $task(); + } + + public function warn(string $message): void + { + $this->warnings[] = $message; + } + }; + + return InstallCommand::doInstallModules([]); + } + + public function newLine($count = 1): static + { + return $this; + } + }; + $command->fakeOptions = ['path' => $this->tmp, 'template' => 'saucebase/notes']; + + $this->assertFalse($command->installDefault()); + $this->assertStringContainsString('saucebase/notes does not support react.', implode("\n", $command->warnings)); + // One way on, the install's resume command: re-running only this step would skip + // the build and the rest. + $this->assertStringNotContainsString('saucebase:template-install', implode("\n", $command->warnings)); + $this->assertStringNotContainsString('Extracting archive', implode("\n", $command->warnings)); + $this->assertStringNotContainsString('--dry-run', implode("\n", $command->warnings)); + $this->assertStringNotContainsString('Package operations', implode("\n", $command->warnings)); + $this->assertSame('Failed at: Installing the template', $command->exposedFailureCalloutContent(null)[0]); + } + /** A template requires its own modules: nothing to look up or ask. */ public function test_a_template_install_does_not_ask_for_modules(): void { diff --git a/tests/Feature/NewCommandTest.php b/tests/Feature/NewCommandTest.php index d3c9794..6bc671b 100644 --- a/tests/Feature/NewCommandTest.php +++ b/tests/Feature/NewCommandTest.php @@ -5,6 +5,7 @@ use Laravel\Prompts\Key; use Laravel\Prompts\Prompt; use Saucebase\Installer\Console\Commands\NewCommand; +use Saucebase\Installer\Environments\DockerEnvironment; use Saucebase\Installer\Environments\Environment; use Saucebase\Installer\Environments\HerdEnvironment; use Saucebase\Installer\Environments\NativeEnvironment; @@ -61,6 +62,83 @@ public function test_herd_is_secured_unless_ssl_is_turned_off(): void $this->assertNull($this->command([])->exposedSsl(new NativeEnvironment)); } + /** Herd secures with `herd secure`: a machine without mkcert still gets its HTTPS app. */ + public function test_herd_does_not_need_mkcert(): void + { + $herd = new class extends HerdEnvironment + { + public function missingPrerequisites(): array + { + return []; + } + + public function hasCommand(string $name): bool + { + return $name !== 'mkcert'; + } + }; + $this->bindCommand(new class($herd) extends NewCommand + { + public function __construct(private Environment $herd) + { + parent::__construct(); + } + + protected function resolveDriver(string $name): Environment + { + return $this->herd; + } + + // The step after the SSL check: reaching it is the point. + protected function resolveDomain(string $name, Environment $driver): string + { + throw new \RuntimeException('past the SSL check'); + } + }); + + $this->expectExceptionMessage('past the SSL check'); + + $this->artisan('new acme --driver=herd --stack=vue --modules=none -n'); + } + + /** Docker's certificates come from mkcert: without it, stop before the project is created, not after. */ + public function test_docker_with_ssl_needs_mkcert_before_the_project_is_created(): void + { + $docker = new class extends DockerEnvironment + { + public function missingPrerequisites(): array + { + return []; + } + + public function hasCommand(string $name): bool + { + return $name !== 'mkcert'; + } + }; + $this->bindCommand(new class($docker) extends NewCommand + { + public function __construct(private Environment $docker) + { + parent::__construct(); + } + + protected function resolveDriver(string $name): Environment + { + return $this->docker; + } + + protected function resolveDomain(string $name, Environment $driver): string + { + throw new \RuntimeException('past the SSL check'); + } + }); + + $this->artisan('new acme --driver=docker --ssl=yes --stack=vue --modules=none -n') + ->expectsOutputToContain('mkcert is required for SSL') + ->assertFailed(); + } + public function test_the_folder_defaults_to_the_app_name_as_a_slug(): void { // The app's name, then Enter to take the folder it suggests. diff --git a/tests/Feature/StackCommandTest.php b/tests/Feature/StackCommandTest.php index c4a9ff8..681776b 100644 --- a/tests/Feature/StackCommandTest.php +++ b/tests/Feature/StackCommandTest.php @@ -539,10 +539,88 @@ public function test_sync_needs_a_contributor_checkout(): void ->expectsOutputToContain('contributor'); } + // ------------------------------------------------------------------------- + // Template workspace ("template" in saucebase.json) + // ------------------------------------------------------------------------- + + /** The workspace builds a template: switching stacks must not forget which. */ + public function test_reset_keeps_the_template_the_workspace_builds(): void + { + $this->seedFakeStubs('vue'); + $this->seedFakeTemplate(); + $this->artisan('stack vue --dev')->assertSuccessful(); + + $this->artisan('stack --reset')->assertSuccessful(); + + $data = json_decode(file_get_contents($this->tmpDir.'/saucebase.json'), true); + $this->assertNull($data['framework']); + $this->assertSame('uptime', $data['template']); + } + + /** + * The template's own files (CSS, page shell, tsconfig) are core's business: the stack + * command only points at the core command that puts them back for the stack chosen. + */ + public function test_a_template_workspace_is_told_to_restore_its_stubs(): void + { + $this->seedFakeStubs('react'); + $this->seedFakeTemplate(); + + $this->artisan('stack react --dev') + ->assertSuccessful() + ->expectsOutputToContain('php artisan saucebase:template-capture --restore'); + } + + /** A template's CSS belongs in its stubs, never in core: --sync is the wrong way out. */ + public function test_a_template_workspace_with_css_changes_is_sent_to_capture_not_sync(): void + { + $this->seedFakeStubs('vue'); + $this->seedFakeTemplate(); + $this->artisan('stack vue --dev')->assertSuccessful(); + file_put_contents($this->tmpDir.'/resources/css/app.css', '/* the template\'s */'); + + $this->artisan('stack --reset') + ->assertFailed() + ->expectsOutputToContain('php artisan saucebase:template-capture') + ->doesntExpectOutputToContain('--sync'); + } + + /** Run from elsewhere with --path: the commands it names run in that workspace, not here. */ + public function test_a_template_workspace_named_by_path_is_told_to_go_there_first(): void + { + $this->seedFakeStubs('vue'); + $this->seedFakeTemplate(); + + $this->artisan('stack vue --dev --path='.$this->tmpDir) + ->assertSuccessful() + ->expectsOutputToContain("cd '{$this->tmpDir}' && php artisan saucebase:template-capture --restore"); + + file_put_contents($this->tmpDir.'/resources/css/app.css', '/* the template\'s */'); + + $this->artisan('stack --reset --path='.$this->tmpDir) + ->assertFailed() + ->expectsOutputToContain("cd '{$this->tmpDir}' && php artisan saucebase:template-capture") + ->expectsOutputToContain("cd '{$this->tmpDir}' && saucebase stack --reset --force"); + } + + public function test_a_plain_checkout_is_not_told_to_restore_stubs(): void + { + $this->seedFakeStubs('react'); + + $this->artisan('stack react --dev') + ->assertSuccessful() + ->doesntExpectOutputToContain('template-capture'); + } + // ------------------------------------------------------------------------- // Helpers // ------------------------------------------------------------------------- + private function seedFakeTemplate(): void + { + file_put_contents($this->tmpDir.'/saucebase.json', json_encode(['framework' => null, 'template' => 'uptime']).PHP_EOL); + } + private function seedFakeViewStub(string $framework, string $entry): void { $viewDir = $this->tmpDir."/vendor/saucebase/core/stubs/stack/{$framework}/views"; @@ -556,7 +634,7 @@ private function seedFakeStubs(string $framework): void $this->files->ensureDirectoryExists($stubDir); file_put_contents($stubDir.'/vite.config.js', "import { saucebase } from './vendor/saucebase/core/resources/js/{$framework}/vite.ts';"); - file_put_contents($stubDir.'/tsconfig.json', "{\"paths\": {\"@/*\": [\"./vendor/saucebase/core/stubs/stack/{$framework}/js/*\"]}}"); + file_put_contents($stubDir.'/tsconfig.json', "{\"compilerOptions\": {\"paths\": {\"@/*\": [\"./vendor/saucebase/core/stubs/stack/{$framework}/js/*\"]}}, \"include\": [\"resources/js/*.ts\"]}"); file_put_contents($stubDir.'/package.json', '{}'); file_put_contents($stubDir.'/package-lock.json', '{}'); file_put_contents($stubDir.'/eslint.config.js', '// eslint');