From ad57d0d0e853f9e8222cbfa36eccfa42cf3090a8 Mon Sep 17 00:00:00 2001 From: roble Date: Sun, 29 Nov 2026 20:43:09 +0000 Subject: [PATCH 1/2] feat: lerd driver, with its queue worker and scheduler `--driver=lerd` installs natively, then `lerd link` and `lerd secure`, like Herd. Offered when `lerd` is on PATH. Herd's flow moves into a shared LinkedSiteEnvironment; Herd and Lerd only name the tool. - `--workers=yes|no` (asked, default yes; non-interactive takes yes): `lerd queue:start` and `lerd schedule:start` after linking. A worker that doesn't start becomes a next step. Resume carries the answer. - Lerd's DNS mode and TLD come from ~/.config/lerd/config.yaml: DNS off serves http://.localhost without `lerd secure`. - The saved driver preference restores herd and lerd too, while offered. - Tests point HOME at a temp dir, so they never read or write ~/.config. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- README.md | 8 +- src/Console/Commands/InstallCommand.php | 11 +- src/Console/Commands/NewCommand.php | 74 ++++-- src/Environments/Environment.php | 1 + src/Environments/HerdEnvironment.php | 67 +---- src/Environments/LerdEnvironment.php | 112 ++++++++ src/Environments/LinkedSiteEnvironment.php | 99 +++++++ .../Environments/HerdEnvironmentTest.php | 138 ---------- .../LinkedSiteEnvironmentTest.php | 247 ++++++++++++++++++ tests/Feature/NewCommandTest.php | 86 +++++- tests/TestCase.php | 20 +- tests/Unit/ProcessGuardTest.php | 2 +- 13 files changed, 639 insertions(+), 228 deletions(-) create mode 100644 src/Environments/LerdEnvironment.php create mode 100644 src/Environments/LinkedSiteEnvironment.php delete mode 100644 tests/Feature/Environments/HerdEnvironmentTest.php create mode 100644 tests/Feature/Environments/LinkedSiteEnvironmentTest.php diff --git a/CLAUDE.md b/CLAUDE.md index ab003ef..8a19dde 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -75,7 +75,7 @@ composer install **`StackCommand`** — Vue/React selection. Takes `--path`; `basePath`/`jsRoot` resolve from `--path` (or an injected constructor path in tests) at `handle()` time. Supports `--dev` (contributor mode — config only, keeps both dirs, uses git skip-worktree) and `--reset`. ### Drivers -`src/Environments/`: `Environment` (abstract base + `make()` factory), `DockerEnvironment`, `NativeEnvironment`. Add a driver (Valet, Herd, Sail) by extending `Environment` and adding a `match` arm to `Environment::make()`. +`src/Environments/`: `Environment` (abstract base + `make()` factory), `DockerEnvironment`, `NativeEnvironment`, and `LinkedSiteEnvironment` (native install, then ` link` / ` secure` at `.test`) with its two drivers `HerdEnvironment` and `LerdEnvironment`, which only name the tool. Add a driver by extending `Environment` (or `LinkedSiteEnvironment` for another tool with `link`/`secure`) and adding a `match` arm to `Environment::make()`. ## Testing diff --git a/README.md b/README.md index 79942fc..9dd352c 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ saucebase new my-app - **Docker driver:** [Docker Desktop](https://www.docker.com/products/docker-desktop/) or Docker Engine with the Compose plugin; [mkcert](https://github.com/FiloSottile/mkcert) only if you enable SSL - **Native driver:** a local PHP capable of running the app; the CLI points you to [php.new](https://php.new) if anything is missing - **Herd driver:** [Laravel Herd](https://herd.laravel.com); offered in the prompt only when the `herd` command is found +- **Lerd driver:** [Lerd](https://github.com/lerd-env/lerd); offered in the prompt only when the `lerd` command is found The CLI **checks and instructs** for prerequisites — it never installs them for you. @@ -48,9 +49,10 @@ Runs a self-update check, then collects every choice upfront (driver → SSL if | Option | Description | |--------|-------------| -| `--driver=docker\|native\|herd` | Environment driver (skips the prompt) | +| `--driver=docker\|native\|herd\|lerd` | Environment driver (skips the prompt) | | `--stack=vue\|react` | Frontend stack (skips the prompt) | | `--ssl=yes\|no` | Enable HTTPS via mkcert, Docker only (skips the prompt) | +| `--workers=yes\|no` | Lerd only: let Lerd run the queue worker and scheduler (skips the prompt; default yes, also when non-interactive) | | `--modules=auth,billing` | Install specific modules by name, or `none` to skip modules | | `--all-modules` | Install every module compatible with the stack | | `--using=vendor/skeleton` | Use a different starter kit instead of `saucebase/saucebase` | @@ -90,6 +92,8 @@ Takes an optional `stack` argument (`vue`/`react`) and the same `--driver`, `--s **Herd driver** — the native install, then `herd link` and (unless `--ssl=no`) `herd secure`, so the app is served at `https://.test`. The name comes from a `.test` `--domain`, otherwise the directory. With `npm run dev` running, Vite renders pages on the server. With built assets only, Herd doesn't start the renderer, so pages render in the browser until you run `php artisan inertia:start-ssr`. +**Lerd driver** — the same as Herd, with `lerd link` and `lerd secure`. It doesn't run `lerd env`, so the app keeps the SQLite database the native install set up. To move it to Lerd's MySQL or Postgres, run `lerd env` in the app. Unless `--workers=no`, it then runs `lerd queue:start` and `lerd schedule:start`, so jobs and scheduled tasks run in the background. The queue worker keeps the code it started with: after you edit a job, run `php artisan queue:restart`. A worker that doesn't start is listed as a next step; the install still completes. The domain follows Lerd's own config (`~/.config/lerd/config.yaml`): its `dns.tld`, or `http://.localhost` without HTTPS when Lerd's DNS is off (`lerd dns:disable`). + Every driver ends by building the frontend (`npm install && npm run build`) when npm is available, then checks the app boots before reporting the install complete. --- @@ -125,7 +129,7 @@ Copies the framework's config (`package.json`, `vite.config.js`, `tsconfig.json` ### SQLite: "database is locked" -The native and Herd drivers use SQLite. By default it doesn't wait when another request or a queue worker is writing, and the second write fails. In `config/database.php`, under `sqlite`, set: +The native, Herd and Lerd drivers use SQLite. By default it doesn't wait when another request or a queue worker is writing, and the second write fails. In `config/database.php`, under `sqlite`, set: ```php 'busy_timeout' => 5000, diff --git a/src/Console/Commands/InstallCommand.php b/src/Console/Commands/InstallCommand.php index 3750439..61ccc74 100644 --- a/src/Console/Commands/InstallCommand.php +++ b/src/Console/Commands/InstallCommand.php @@ -12,6 +12,7 @@ use Saucebase\Installer\Console\Commands\Concerns\DisplaysBanner; use Saucebase\Installer\Environments\Environment; use Saucebase\Installer\Environments\HerdEnvironment; +use Saucebase\Installer\Environments\LerdEnvironment; use Saucebase\Installer\ModuleRegistry; use function Laravel\Prompts\callout; @@ -25,9 +26,10 @@ class InstallCommand extends Command protected $signature = 'install {stack? : The frontend stack to install (vue or react)} {--path= : The Saucebase application directory (defaults to the current directory)} - {--driver= : Environment driver (docker, native, herd) — prompted if omitted} + {--driver= : Environment driver (docker, native, herd, lerd) — prompted if omitted} {--ssl= : Enable HTTPS with mkcert for docker (yes/no) — prompted if omitted} {--domain= : Hostname the app is served on (e.g. myapp.test) — prompted if omitted} + {--workers= : Let Lerd run the queue worker and scheduler (yes/no), prompted if omitted} {--app-name= : What the app is called (defaults to its directory name)} {--demo : Load demo content and demo users} {--template= : A Saucebase template (vendor/name): installs it, the modules it requires, and its starting data} @@ -152,6 +154,9 @@ protected function resolveDriver(): Environment ...((new HerdEnvironment)->hasCommand('herd') ? ['herd' => 'Laravel Herd - served at https://.test'] : []), + ...((new LerdEnvironment)->hasCommand('lerd') + ? ['lerd' => 'Lerd - served at '.(new LerdEnvironment)->siteUrl('')] + : []), ], default: 'docker', ); @@ -227,7 +232,7 @@ public static function normalizeDomain(string $value): ?string } /** - * A custom domain resolves only via /etc/hosts, Herd, Valet or dnsmasq. Say so + * A custom domain resolves only via /etc/hosts, Herd, Lerd, Valet or dnsmasq. Say so * rather than letting the browser fail after a successful install. */ protected function warnWhenDomainDoesNotResolve(string $domain): void @@ -870,7 +875,7 @@ public function resumeCommand(array $resumeOptions = []): string $command .= ' '.$this->selectedStack; } - // Herd's choice is only on the command line; Docker's comes back resolved. + // Herd's and Lerd's choice is only on the command line; Docker's comes back resolved. if (! isset($resumeOptions['--ssl']) && ($ssl = $this->optionOrNull('ssl'))) { $resumeOptions['--ssl'] = $ssl; } diff --git a/src/Console/Commands/NewCommand.php b/src/Console/Commands/NewCommand.php index 4febd0d..d1c149d 100644 --- a/src/Console/Commands/NewCommand.php +++ b/src/Console/Commands/NewCommand.php @@ -10,6 +10,8 @@ use Saucebase\Installer\Console\Commands\Concerns\DisplaysBanner; use Saucebase\Installer\Environments\Environment; use Saucebase\Installer\Environments\HerdEnvironment; +use Saucebase\Installer\Environments\LerdEnvironment; +use Saucebase\Installer\Environments\LinkedSiteEnvironment; use Saucebase\Installer\ModuleRegistry; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Process\Process as SymfonyProcess; @@ -24,12 +26,13 @@ class NewCommand extends Command protected $signature = 'new {name? : The name of the new Saucebase application} - {--driver= : Environment driver (docker, native, herd) — prompted if omitted} + {--driver= : Environment driver (docker, native, herd, lerd) — prompted if omitted} {--stack= : Frontend stack (vue or react) — prompted if omitted} {--modules= : Comma-separated list of modules to enable, or "none"} {--all-modules : Enable and migrate all available modules without prompting} {--ssl= : Enable HTTPS with mkcert for docker (yes/no) — prompted if omitted} {--domain= : Hostname the app is served on (e.g. myapp.test) — prompted if omitted} + {--workers= : Let Lerd run the queue worker and scheduler (yes/no), prompted if omitted} {--app-name= : What the app is called (defaults to its directory name), prompted if omitted} {--using= : A starter kit to start from, instead of a plain Laravel application} {--template= : A Saucebase template (vendor/name): installs it, the modules it requires, and its starting data} @@ -67,7 +70,7 @@ public function handle(): int $ssl = $this->ssl($driver); // 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. + // missing one leaves nothing half-made. Herd and Lerd secure with their own `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'); @@ -76,6 +79,7 @@ public function handle(): int } $domain = $this->resolveDomain($name, $driver); + $workers = $this->workers($driver); // A template brings its own framework, which the install reads once the files are there. $stack = $this->option('stack') ?: ($this->option('using') ? null : select( @@ -96,7 +100,7 @@ public function handle(): int // Laravel's installer has just printed its own next steps; ours come at the end. $this->line(' Laravel is ready. Now setting up Saucebase…'); - $arguments = $this->installArguments($name, $driver, $stack, $ssl, $modules, $domain, $appName, $demo); + $arguments = $this->installArguments($name, $driver, $stack, $ssl, $modules, $domain, $appName, $demo, $workers); $result = $this->call('install', $arguments); if ($result === self::SUCCESS) { @@ -137,36 +141,71 @@ protected function names(?string $folder): array protected function resolveDriver(string $name): Environment { + // Offered only where it can run. + $options = $this->driverOptions($name, herd: (new HerdEnvironment)->hasCommand('herd'), lerd: (new LerdEnvironment)->hasCommand('lerd')); + $driver = $this->option('driver') ?? select( label: 'How would you like to run Saucebase?', - // Offered only where it can run. - options: $this->driverOptions($name, herd: (new HerdEnvironment)->hasCommand('herd')), - default: $this->savedDriverPreference() ?? 'docker', + options: $options, + default: $this->defaultDriver($options), ); return Environment::make($driver); } + /** + * The last install's driver, while it is still on offer: Herd or Lerd may be gone since. + * + * @param array $options + */ + protected function defaultDriver(array $options): string + { + $saved = $this->savedDriverPreference(); + + return $saved !== null && isset($options[$saved]) ? $saved : 'docker'; + } + /** @return array */ - protected function driverOptions(string $name, bool $herd): array + protected function driverOptions(string $name, bool $herd, bool $lerd): array { return [ 'docker' => 'Docker - recommended for real projects: MySQL, Redis, Mailpit, HTTPS', 'native' => 'Native PHP - minimal setup, ideal for exploring', - ...($herd ? ['herd' => 'Laravel Herd - served at https://'.Str::slug($name).'.test'] : []), + ...($herd ? ['herd' => 'Laravel Herd - served at '.(new HerdEnvironment)->siteUrl(Str::slug($name))] : []), + ...($lerd ? ['lerd' => 'Lerd - served at '.(new LerdEnvironment)->siteUrl(Str::slug($name))] : []), ]; } - /** Docker asks; Herd secures unless told not to; native serves plain HTTP. */ + /** Docker asks; Herd and Lerd secure unless told not to; native serves plain HTTP. */ protected function ssl(Environment $driver): ?bool { - return match ($driver->name()) { - 'docker' => $this->resolveSsl($driver), - 'herd' => $this->option('ssl') !== 'no', + return match (true) { + $driver->name() === 'docker' => $this->resolveSsl($driver), + $driver instanceof LinkedSiteEnvironment => $driver->canSecure() && $this->option('ssl') !== 'no', default => null, }; } + /** Lerd runs the queue and scheduler unless told not to; other drivers aren't asked. */ + protected function workers(Environment $driver): ?bool + { + if (! $driver instanceof LerdEnvironment) { + return null; + } + + $option = $this->option('workers'); + + return match (true) { + is_string($option) && $option !== '' => filter_var($option, FILTER_VALIDATE_BOOLEAN), + (bool) $this->option('force') => true, + default => confirm( + label: 'Let Lerd run the queue and scheduler?', + default: true, + hint: 'Jobs and scheduled tasks run in the background while you work.', + ), + }; + } + protected function resolveSsl(Environment $driver): bool { $option = $this->option('ssl'); @@ -192,8 +231,8 @@ protected function resolveDomain(string $name, Environment $driver): string $answer = match (true) { is_string($option) && $option !== '' => $option, - // Herd serves every site at its own .test name. - $driver->name() === 'herd' => Str::slug($name).'.test', + // Herd and Lerd serve every site at its own name under their TLD. + $driver instanceof LinkedSiteEnvironment => Str::slug($name).'.'.$driver->tld(), (bool) $this->option('force') => 'localhost', default => text( label: 'Which hostname will you use for this app?', @@ -324,6 +363,7 @@ protected function installArguments( string $domain = 'localhost', ?string $appName = null, bool $demo = false, + ?bool $workers = null, ): array { $arguments = array_filter(['stack' => $stack]) + [ '--path' => getcwd().'/'.$name, @@ -336,6 +376,10 @@ protected function installArguments( $arguments['--ssl'] = $ssl ? 'yes' : 'no'; } + if ($workers !== null) { + $arguments['--workers'] = $workers ? 'yes' : 'no'; + } + if ($appName !== null) { $arguments['--app-name'] = $appName; } @@ -501,7 +545,7 @@ protected function savedDriverPreference(): ?string $driver = $config['driver'] ?? null; - return in_array($driver, ['docker', 'native'], true) ? $driver : null; + return is_string($driver) ? $driver : null; } protected function saveDriverPreference(string $driver): void diff --git a/src/Environments/Environment.php b/src/Environments/Environment.php index 46d33ff..5f367ba 100644 --- a/src/Environments/Environment.php +++ b/src/Environments/Environment.php @@ -19,6 +19,7 @@ public static function make(string $name): Environment 'docker' => new DockerEnvironment, 'native' => new NativeEnvironment, 'herd' => new HerdEnvironment, + 'lerd' => new LerdEnvironment, default => throw new \InvalidArgumentException("Unknown driver: {$name}"), }; } diff --git a/src/Environments/HerdEnvironment.php b/src/Environments/HerdEnvironment.php index 6b39a09..4e7ceac 100644 --- a/src/Environments/HerdEnvironment.php +++ b/src/Environments/HerdEnvironment.php @@ -2,11 +2,7 @@ namespace Saucebase\Installer\Environments; -use Illuminate\Support\Str; -use Saucebase\Installer\Console\Commands\InstallCommand; - -/** The native install, served by Laravel Herd at `.test` instead of `composer dev`. */ -class HerdEnvironment extends NativeEnvironment +class HerdEnvironment extends LinkedSiteEnvironment { public function name(): string { @@ -17,65 +13,4 @@ public function label(): string { return 'Laravel Herd'; } - - public function missingPrerequisites(): array - { - $missing = parent::missingPrerequisites(); - - if (! $this->commandExists('herd')) { - $missing[] = 'herd is not installed or not in PATH.'; - } - - return $missing; - } - - protected function boot(InstallCommand $command): int - { - if (($result = parent::boot($command)) !== InstallCommand::SUCCESS) { - return $result; - } - - $site = $this->site($command); - - if (! $command->runProcess(['herd', 'link', $site])) { - return $this->fail('Linking the site to Herd'); - } - - if ($this->secure($command) && ! $command->runProcess(['herd', 'secure', $site])) { - return $this->fail('Securing the site with Herd'); - } - - $env = (string) file_get_contents($command->path('.env')); - $env = InstallCommand::setEnvLine($env, 'APP_HOST', "{$site}.test"); - $scheme = $this->secure($command) ? 'https' : 'http'; - $env = InstallCommand::setEnvLine($env, 'APP_URL', "{$scheme}://{$site}.test"); - file_put_contents($command->path('.env'), $env); - - return InstallCommand::SUCCESS; - } - - protected function nextSteps(InstallCommand $command): array - { - return [ - ...($this->frontendBuilt ? [] : ['Install frontend dependencies: `npm install`']), - $this->frontendBuilt ? 'For live reload while you edit: `npm run dev`' : 'Start Vite: `npm run dev`', - 'Herd already serves your app: `'.($this->readEnvValue($command, 'APP_URL') ?? '').'`', - ]; - } - - /** HTTPS unless `--ssl=no`: Herd trusts its own certificates, so there is nothing to install. */ - private function secure(InstallCommand $command): bool - { - return $command->optionOrNull('ssl') !== 'no'; - } - - /** `shop.test` from `--domain`, otherwise the directory name. */ - private function site(InstallCommand $command): string - { - $domain = $command->getDomain(); - - return str_ends_with($domain, '.test') - ? substr($domain, 0, -5) - : Str::slug(basename($command->targetPath())); - } } diff --git a/src/Environments/LerdEnvironment.php b/src/Environments/LerdEnvironment.php new file mode 100644 index 0000000..c8236d5 --- /dev/null +++ b/src/Environments/LerdEnvironment.php @@ -0,0 +1,112 @@ + 'queue', 'schedule' => 'scheduler']; + + private bool $workers = true; + + /** @var list Workers that didn't start. */ + private array $notStarted = []; + + public function name(): string + { + return 'lerd'; + } + + public function label(): string + { + return 'Lerd'; + } + + /** `.localhost` while Lerd's DNS is off, otherwise its configured TLD. */ + public function tld(): string + { + return $this->dns()['enabled'] ? $this->dns()['tld'] : 'localhost'; + } + + /** Lerd issues certificates only while it manages DNS. */ + public function canSecure(): bool + { + return $this->dns()['enabled']; + } + + /** + * The `dns:` block of Lerd's config: `enabled` and `tld`. Lerd has no command that + * prints them, so the file is read. Missing, Lerd's defaults: on, `test`. + * + * @return array{enabled: bool, tld: string} + */ + private function dns(): array + { + $home = $_SERVER['HOME'] ?? (getenv('HOME') ?: sys_get_temp_dir()); + $config = (string) @file_get_contents($home.'/.config/lerd/config.yaml'); + $block = preg_match('/^dns:[^\n]*\n((?:[ \t]+[^\n]*\n?)*)/m', $config, $m) === 1 ? $m[1] : ''; + + return [ + 'enabled' => preg_match('/^\s+enabled:\s*false\b/m', $block) !== 1, + 'tld' => preg_match('/^\s+tld:\s*["\']?([a-z0-9-]+)/m', $block, $tld) === 1 ? $tld[1] : 'test', + ]; + } + + /** Yes unless `--workers=no`; non-interactive runs take the default without asking. */ + protected function beforePrompts(InstallCommand $command): ?int + { + $option = $command->optionOrNull('workers'); + + $this->workers = match (true) { + is_string($option) && $option !== '' => filter_var($option, FILTER_VALIDATE_BOOLEAN), + (bool) $command->optionOrNull('force') => true, + default => confirm( + label: 'Let Lerd run the queue and scheduler?', + default: true, + hint: 'Jobs and scheduled tasks run in the background while you work.', + ), + }; + + return null; + } + + protected function boot(InstallCommand $command): int + { + if (($result = parent::boot($command)) !== InstallCommand::SUCCESS || ! $this->workers) { + return $result; + } + + foreach (array_keys(self::WORKERS) as $worker) { + if (! $command->runProcess(['lerd', "{$worker}:start"])) { + $this->notStarted[] = $worker; + } + } + + return InstallCommand::SUCCESS; + } + + protected function nextSteps(InstallCommand $command): array + { + $site = basename((string) $this->readEnvValue($command, 'APP_HOST'), '.localhost'); + $dnsOff = $this->canSecure() ? [] : [ + "Lerd's DNS is off, so there is no HTTPS. For `https://{$site}.{$this->dns()['tld']}`: `lerd dns:enable && lerd secure`", + ]; + + return [...parent::nextSteps($command), ...$dnsOff, match (true) { + ! $this->workers => 'Run the queue and scheduler: `lerd queue:start && lerd schedule:start`', + $this->notStarted === [] => 'Lerd runs the queue and scheduler. After you edit a job: `php artisan queue:restart`', + default => 'Run the '.implode(' and ', array_map(fn (string $w): string => self::WORKERS[$w], $this->notStarted)).': `' + .implode(' && ', array_map(fn (string $w): string => "lerd {$w}:start", $this->notStarted)).'`', + }]; + } + + protected function resumeOptions(): array + { + return [...parent::resumeOptions(), '--workers' => $this->workers ? 'yes' : 'no']; + } +} diff --git a/src/Environments/LinkedSiteEnvironment.php b/src/Environments/LinkedSiteEnvironment.php new file mode 100644 index 0000000..a4b7331 --- /dev/null +++ b/src/Environments/LinkedSiteEnvironment.php @@ -0,0 +1,99 @@ +.` by a local site server (Herd, Lerd) + * instead of `composer dev`. The driver's name is the tool's command: both take + * `link ` and `secure `. + */ +abstract class LinkedSiteEnvironment extends NativeEnvironment +{ + public function missingPrerequisites(): array + { + $missing = parent::missingPrerequisites(); + + if (! $this->commandExists($this->name())) { + $missing[] = "{$this->name()} is not installed or not in PATH."; + } + + return $missing; + } + + protected function boot(InstallCommand $command): int + { + if (($result = parent::boot($command)) !== InstallCommand::SUCCESS) { + return $result; + } + + $site = $this->site($command); + + if (! $command->runProcess([$this->name(), 'link', $site])) { + return $this->fail("Linking the site to {$this->tool()}"); + } + + if ($this->secure($command) && ! $command->runProcess([$this->name(), 'secure', $site])) { + return $this->fail("Securing the site with {$this->tool()}"); + } + + $env = (string) file_get_contents($command->path('.env')); + $env = InstallCommand::setEnvLine($env, 'APP_HOST', "{$site}.{$this->tld()}"); + $env = InstallCommand::setEnvLine($env, 'APP_URL', $this->siteUrl($site, $this->secure($command))); + file_put_contents($command->path('.env'), $env); + + return InstallCommand::SUCCESS; + } + + protected function nextSteps(InstallCommand $command): array + { + return [ + ...($this->frontendBuilt ? [] : ['Install frontend dependencies: `npm install`']), + $this->frontendBuilt ? 'For live reload while you edit: `npm run dev`' : 'Start Vite: `npm run dev`', + $this->tool().' already serves your app: `'.($this->readEnvValue($command, 'APP_URL') ?? '').'`', + ]; + } + + /** The suffix the tool serves sites under. */ + public function tld(): string + { + return 'test'; + } + + /** Whether the tool can issue certificates for its sites. */ + public function canSecure(): bool + { + return true; + } + + /** Where the tool serves `$site`: over HTTPS when asked and it can. */ + public function siteUrl(string $site, bool $ssl = true): string + { + return ($ssl && $this->canSecure() ? 'https' : 'http')."://{$site}.{$this->tld()}"; + } + + /** `Herd`, `Lerd`: the tool's name in messages. */ + private function tool(): string + { + return ucfirst($this->name()); + } + + /** HTTPS unless `--ssl=no`: the tool trusts its own certificates, so there is nothing to install. */ + private function secure(InstallCommand $command): bool + { + return $this->canSecure() && $command->optionOrNull('ssl') !== 'no'; + } + + /** `shop` from a `shop.` `--domain`, otherwise the directory name. */ + private function site(InstallCommand $command): string + { + $domain = $command->getDomain(); + $suffix = '.'.$this->tld(); + + return str_ends_with($domain, $suffix) + ? substr($domain, 0, -strlen($suffix)) + : Str::slug(basename($command->targetPath())); + } +} diff --git a/tests/Feature/Environments/HerdEnvironmentTest.php b/tests/Feature/Environments/HerdEnvironmentTest.php deleted file mode 100644 index f049cd1..0000000 --- a/tests/Feature/Environments/HerdEnvironmentTest.php +++ /dev/null @@ -1,138 +0,0 @@ -fakeFinishingSteps(); - $this->app = sys_get_temp_dir().'/acme-shop-'.uniqid(); - mkdir($this->app); - } - - protected function tearDown(): void - { - @unlink($this->app.'/.env'); - @rmdir($this->app); - parent::tearDown(); - } - - public function test_it_is_the_herd_driver(): void - { - $this->assertInstanceOf(HerdEnvironment::class, Environment::make('herd')); - } - - public function test_it_needs_herd(): void - { - $env = new class extends HerdEnvironment - { - protected function commandExists(string $name): bool - { - return $name !== 'herd'; - } - }; - - $this->assertSame(['herd is not installed or not in PATH.'], $env->missingPrerequisites()); - } - - public function test_it_links_and_secures_the_app_after_installing_it(): void - { - $command = $this->command(installs: true, domain: 'shop.test'); - - $this->assertSame(Command::SUCCESS, (new HerdEnvironment)->run($command)); - $this->assertSame(['herd link shop', 'herd secure shop'], $command->ran); - $this->assertStringContainsString('APP_URL=https://shop.test', (string) file_get_contents($this->app.'/.env')); - $this->assertStringContainsString('APP_HOST=shop.test', (string) file_get_contents($this->app.'/.env')); - } - - public function test_the_summary_says_herd_already_serves_the_app(): void - { - $command = $this->command(installs: true, domain: 'shop.test'); - $env = new class extends HerdEnvironment - { - /** @return string[] */ - public function steps(InstallCommand $command): array - { - return $this->nextSteps($command); - } - }; - $env->run($command); - - $this->assertContains('Herd already serves your app: `https://shop.test`', $env->steps($command)); - } - - public function test_without_ssl_it_only_links_and_serves_over_http(): void - { - $command = $this->command(installs: true, ssl: 'no'); - - (new HerdEnvironment)->run($command); - - $site = basename($this->app); - $this->assertSame(["herd link {$site}"], $command->ran); - $this->assertStringContainsString("APP_URL=http://{$site}.test", (string) file_get_contents($this->app.'/.env')); - } - - public function test_a_failed_install_is_not_linked(): void - { - $command = $this->command(installs: false); - - $this->assertSame(Command::FAILURE, (new HerdEnvironment)->run($command)); - $this->assertSame([], $command->ran); - } - - private function command(bool $installs, string $domain = 'localhost', ?string $ssl = null): InstallCommand - { - return new class($this->app, $installs, $domain, $ssl) extends InstallCommand - { - /** @var list */ - public array $ran = []; - - public function __construct(private string $app, private bool $installs, private string $site, private ?string $ssl) {} - - public function targetPath(): string - { - return $this->app; - } - - public function getDomain(): string - { - return $this->site; - } - - public function optionOrNull(string $key): string|array|bool|null - { - return $key === 'ssl' ? $this->ssl : null; - } - - public function install(): int - { - file_put_contents($this->app.'/.env', "APP_URL=http://localhost:8000\nAPP_HOST=localhost\n"); - - return $this->installs ? Command::SUCCESS : Command::FAILURE; - } - - public function runProcess(array $command, int $timeout = 300): bool - { - $this->ran[] = implode(' ', $command); - - return true; - } - - public function promptForModules(): void {} - - public function displaySuccess(array $steps = []): void {} - - public function displayFailure(?string $step = null, array $resumeOptions = []): void {} - }; - } -} diff --git a/tests/Feature/Environments/LinkedSiteEnvironmentTest.php b/tests/Feature/Environments/LinkedSiteEnvironmentTest.php new file mode 100644 index 0000000..d587f60 --- /dev/null +++ b/tests/Feature/Environments/LinkedSiteEnvironmentTest.php @@ -0,0 +1,247 @@ +.test`. */ +class LinkedSiteEnvironmentTest extends TestCase +{ + private string $app; + + protected function setUp(): void + { + parent::setUp(); + $this->fakeFinishingSteps(); + $this->app = sys_get_temp_dir().'/acme-shop-'.uniqid(); + mkdir($this->app); + } + + protected function tearDown(): void + { + @unlink($this->app.'/.env'); + @rmdir($this->app); + parent::tearDown(); + } + + /** @return array */ + public static function drivers(): array + { + return ['herd' => ['herd'], 'lerd' => ['lerd']]; + } + + public function test_herd_and_lerd_are_their_own_drivers(): void + { + $this->assertInstanceOf(HerdEnvironment::class, Environment::make('herd')); + $this->assertInstanceOf(LerdEnvironment::class, Environment::make('lerd')); + } + + #[DataProvider('drivers')] + public function test_it_needs_its_tool(string $name): void + { + Process::fake(["'which' '{$name}'" => Process::result(''), "'which' *" => Process::result('/usr/local/bin/tool')]); + + $this->assertSame(["{$name} is not installed or not in PATH."], Environment::make($name)->missingPrerequisites()); + } + + #[DataProvider('drivers')] + public function test_it_links_and_secures_the_app_after_installing_it(string $name): void + { + $command = $this->command(installs: true, domain: 'shop.test'); + + $this->assertSame(Command::SUCCESS, Environment::make($name)->run($command)); + $this->assertSame(["{$name} link shop", "{$name} secure shop"], $command->ran); + $this->assertStringContainsString('APP_URL=https://shop.test', (string) file_get_contents($this->app.'/.env')); + $this->assertStringContainsString('APP_HOST=shop.test', (string) file_get_contents($this->app.'/.env')); + } + + #[DataProvider('drivers')] + public function test_the_summary_says_the_tool_already_serves_the_app(string $name): void + { + $command = $this->command(installs: true, domain: 'shop.test'); + $env = Environment::make($name); + $env->run($command); + + $steps = (fn (): array => $this->nextSteps($command))->call($env); + + $tool = ['herd' => 'Herd', 'lerd' => 'Lerd'][$name]; + $this->assertContains("{$tool} already serves your app: `https://shop.test`", $steps); + } + + #[DataProvider('drivers')] + public function test_without_ssl_it_only_links_and_serves_over_http(string $name): void + { + $command = $this->command(installs: true, options: ['ssl' => 'no']); + + Environment::make($name)->run($command); + + $site = basename($this->app); + $this->assertSame(["{$name} link {$site}"], $command->ran); + $this->assertStringContainsString("APP_URL=http://{$site}.test", (string) file_get_contents($this->app.'/.env')); + } + + #[DataProvider('drivers')] + public function test_a_failed_install_is_not_linked(string $name): void + { + $command = $this->command(installs: false); + + $this->assertSame(Command::FAILURE, Environment::make($name)->run($command)); + $this->assertSame([], $command->ran); + } + + public function test_lerd_runs_the_queue_and_scheduler_when_asked_to(): void + { + $command = $this->command(installs: true, domain: 'shop.test', options: ['workers' => 'yes']); + + (new LerdEnvironment)->run($command); + + $this->assertSame(['lerd link shop', 'lerd secure shop', 'lerd queue:start', 'lerd schedule:start'], $command->ran); + $this->assertContains('Lerd runs the queue and scheduler. After you edit a job: `php artisan queue:restart`', $this->steps(new LerdEnvironment, $command)); + } + + /** `-n`, CI and night runs never see the question: the default, yes, is taken. */ + public function test_lerd_runs_them_without_asking_when_not_interactive(): void + { + Prompt::interactive(false); + $command = $this->command(installs: true, domain: 'shop.test', options: ['workers' => null]); + + (new LerdEnvironment)->run($command); + + $this->assertSame(['lerd link shop', 'lerd secure shop', 'lerd queue:start', 'lerd schedule:start'], $command->ran); + } + + public function test_declined_the_workers_become_a_next_step(): void + { + $command = $this->command(installs: true, domain: 'shop.test', options: ['workers' => 'no']); + $env = new LerdEnvironment; + + $env->run($command); + + $this->assertSame(['lerd link shop', 'lerd secure shop'], $command->ran); + $this->assertContains('Run the queue and scheduler: `lerd queue:start && lerd schedule:start`', $this->steps($env, $command)); + } + + /** The app already works without them: a worker that won't start is a next step, not a failed install. */ + public function test_a_worker_that_does_not_start_leaves_the_install_complete(): void + { + $command = $this->command(installs: true, domain: 'shop.test', options: ['workers' => 'yes'], failing: ['lerd schedule:start']); + $env = new LerdEnvironment; + + $this->assertSame(Command::SUCCESS, $env->run($command)); + $this->assertContains('Run the scheduler: `lerd schedule:start`', $this->steps($env, $command)); + } + + public function test_a_resumed_lerd_install_keeps_the_workers_answer(): void + { + $command = $this->command(installs: false, options: ['workers' => 'no']); + $env = new LerdEnvironment; + $env->run($command); + + $this->assertSame(['--driver' => 'lerd', '--workers' => 'no'], (fn (): array => $this->resumeOptions())->call($env)); + } + + /** With its DNS off, Lerd serves `.localhost` and can't issue certificates. */ + public function test_lerd_with_its_dns_off_serves_over_http_at_localhost(): void + { + $this->fakeLerdConfig("dns:\n enabled: false\n tld: test\nui:\n enabled: true\n"); + $command = $this->command(installs: true, domain: 'shop.localhost'); + $env = new LerdEnvironment; + + $this->assertSame(Command::SUCCESS, $env->run($command)); + $this->assertSame(['lerd link shop'], $command->ran); + $this->assertStringContainsString('APP_URL=http://shop.localhost', (string) file_get_contents($this->app.'/.env')); + $this->assertStringContainsString('APP_HOST=shop.localhost', (string) file_get_contents($this->app.'/.env')); + $this->assertContains("Lerd's DNS is off, so there is no HTTPS. For `https://shop.test`: `lerd dns:enable && lerd secure`", $this->steps($env, $command)); + } + + public function test_lerd_serves_the_app_at_its_configured_tld(): void + { + $this->fakeLerdConfig("dns:\n enabled: true\n tld: dev\n"); + $command = $this->command(installs: true, domain: 'shop.dev'); + + (new LerdEnvironment)->run($command); + + $this->assertSame(['lerd link shop', 'lerd secure shop'], $command->ran); + $this->assertStringContainsString('APP_URL=https://shop.dev', (string) file_get_contents($this->app.'/.env')); + } + + public function test_herd_starts_no_workers(): void + { + $command = $this->command(installs: true, domain: 'shop.test', options: ['workers' => 'yes']); + + (new HerdEnvironment)->run($command); + + $this->assertSame(['herd link shop', 'herd secure shop'], $command->ran); + } + + /** @return string[] */ + private function steps(Environment $env, InstallCommand $command): array + { + return (fn (): array => $this->nextSteps($command))->call($env); + } + + /** + * @param array $options + * @param list $failing Commands that fail. + */ + private function command(bool $installs, string $domain = 'localhost', array $options = [], array $failing = []): InstallCommand + { + // Other tests aren't about the workers: declined, so only link and secure run. + $options += ['workers' => 'no']; + + return new class($this->app, $installs, $domain, $options, $failing) extends InstallCommand + { + /** @var list */ + public array $ran = []; + + /** + * @param array $options + * @param list $failing + */ + public function __construct(private string $app, private bool $installs, private string $site, private array $options, private array $failing) {} + + public function targetPath(): string + { + return $this->app; + } + + public function getDomain(): string + { + return $this->site; + } + + public function optionOrNull(string $key): string|array|bool|null + { + return $this->options[$key] ?? null; + } + + public function install(): int + { + file_put_contents($this->app.'/.env', "APP_URL=http://localhost:8000\nAPP_HOST=localhost\n"); + + return $this->installs ? Command::SUCCESS : Command::FAILURE; + } + + public function runProcess(array $command, int $timeout = 300): bool + { + $this->ran[] = $line = implode(' ', $command); + + return ! in_array($line, $this->failing, true); + } + + public function promptForModules(): void {} + + public function displaySuccess(array $steps = []): void {} + + public function displayFailure(?string $step = null, array $resumeOptions = []): void {} + }; + } +} diff --git a/tests/Feature/NewCommandTest.php b/tests/Feature/NewCommandTest.php index 6bc671b..2c26297 100644 --- a/tests/Feature/NewCommandTest.php +++ b/tests/Feature/NewCommandTest.php @@ -8,6 +8,7 @@ use Saucebase\Installer\Environments\DockerEnvironment; use Saucebase\Installer\Environments\Environment; use Saucebase\Installer\Environments\HerdEnvironment; +use Saucebase\Installer\Environments\LerdEnvironment; use Saucebase\Installer\Environments\NativeEnvironment; use Saucebase\Installer\Tests\TestCase; @@ -62,6 +63,12 @@ public function test_herd_is_secured_unless_ssl_is_turned_off(): void $this->assertNull($this->command([])->exposedSsl(new NativeEnvironment)); } + public function test_lerd_is_secured_unless_ssl_is_turned_off(): void + { + $this->assertTrue($this->command([])->exposedSsl(new LerdEnvironment)); + $this->assertFalse($this->command(['ssl' => 'no'])->exposedSsl(new LerdEnvironment)); + } + /** Herd secures with `herd secure`: a machine without mkcert still gets its HTTPS app. */ public function test_herd_does_not_need_mkcert(): void { @@ -152,6 +159,66 @@ public function test_herd_is_offered_at_the_apps_own_address(): void $this->assertSame('Laravel Herd - served at https://acme-shop.test', $this->command([])->exposedDriverOptions('acme-shop')['herd']); } + public function test_lerd_runs_the_workers_unless_told_not_to(): void + { + Prompt::interactive(false); + + $this->assertTrue($this->command([])->exposedWorkers(new LerdEnvironment)); + $this->assertFalse($this->command(['workers' => 'no'])->exposedWorkers(new LerdEnvironment)); + $this->assertNull($this->command([])->exposedWorkers(new HerdEnvironment)); + } + + /** Asked upfront with the other questions, then handed to the install so it runs unattended. */ + public function test_the_workers_answer_reaches_the_install(): void + { + $command = $this->command(['force' => true]); + + $this->assertSame('yes', $command->exposedLerdInstallArguments(workers: true)['--workers']); + $this->assertSame('no', $command->exposedLerdInstallArguments(workers: false)['--workers']); + $this->assertArrayNotHasKey('--workers', $command->exposedInstallArguments('acme', 'vue')); + } + + public function test_lerd_with_its_dns_off_is_offered_over_http_at_localhost(): void + { + $this->fakeLerdConfig("dns:\n enabled: false\n"); + + $this->assertSame('Lerd - served at http://acme-shop.localhost', $this->command([])->exposedDriverOptions('acme-shop')['lerd']); + $this->assertSame('acme-shop.localhost', $this->command([])->exposedResolveDomain('acme-shop', new LerdEnvironment)); + $this->assertFalse($this->command([])->exposedSsl(new LerdEnvironment)); + } + + public function test_lerd_serves_the_app_at_its_configured_tld(): void + { + $this->fakeLerdConfig("dns:\n enabled: true\n tld: dev\n"); + + $this->assertSame('acme-shop.dev', $this->command([])->exposedResolveDomain('acme-shop', new LerdEnvironment)); + } + + /** The last install's driver is the default again, while it is still on offer. */ + public function test_the_saved_driver_is_the_default_while_it_is_offered(): void + { + @mkdir($_SERVER['HOME'].'/.config/saucebase', 0755, true); + $save = fn (string $driver) => file_put_contents($_SERVER['HOME'].'/.config/saucebase/config.json', json_encode(['driver' => $driver])); + $offered = ['docker' => '', 'native' => '', 'herd' => '', 'lerd' => '']; + + $save('lerd'); + $this->assertSame('lerd', $this->command([])->exposedDefaultDriver($offered)); + $this->assertSame('docker', $this->command([])->exposedDefaultDriver(['docker' => '', 'native' => ''])); + + $save('herd'); + $this->assertSame('herd', $this->command([])->exposedDefaultDriver($offered)); + } + + public function test_lerd_is_offered_at_the_apps_own_address(): void + { + $this->assertSame('Lerd - served at https://acme-shop.test', $this->command([])->exposedDriverOptions('acme-shop')['lerd']); + } + + public function test_lerd_serves_the_app_at_its_folder_name_without_asking(): void + { + $this->assertSame('acme-shop.test', $this->command([])->exposedResolveDomain('acme-shop', new LerdEnvironment)); + } + public function test_herd_serves_the_app_at_its_folder_name_without_asking(): void { $this->assertSame('acme-shop.test', $this->command([])->exposedResolveDomain('acme-shop', new HerdEnvironment)); @@ -301,7 +368,7 @@ public function exposedNames(?string $name): array /** @return array */ public function exposedDriverOptions(string $name): array { - return $this->driverOptions($name, herd: true); + return $this->driverOptions($name, herd: true, lerd: true); } public function exposedResolveDomain(string $name, Environment $driver): string @@ -309,6 +376,23 @@ public function exposedResolveDomain(string $name, Environment $driver): string return $this->resolveDomain($name, $driver); } + /** @param array $options */ + public function exposedDefaultDriver(array $options): string + { + return $this->defaultDriver($options); + } + + public function exposedWorkers(Environment $driver): ?bool + { + return $this->workers($driver); + } + + /** @return array */ + public function exposedLerdInstallArguments(bool $workers): array + { + return $this->installArguments('acme', new LerdEnvironment, 'vue', true, null, 'acme.test', workers: $workers); + } + public function exposedSsl(Environment $driver): ?bool { return $this->ssl($driver); diff --git a/tests/TestCase.php b/tests/TestCase.php index 170802e..ba89bfc 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -4,6 +4,7 @@ use Illuminate\Console\Application as ConsoleApplication; use Illuminate\Console\Command; +use Illuminate\Filesystem\Filesystem; use Illuminate\Process\PendingProcess; use Illuminate\Process\ProcessResult; use Illuminate\Support\Facades\Facade; @@ -18,6 +19,8 @@ abstract class TestCase extends BaseTestCase { protected ConsoleApplication $console; + private ?string $realHome = null; + protected function setUp(): void { parent::setUp(); @@ -26,19 +29,34 @@ protected function setUp(): void $this->console = Application::make(); // A process a test did not fake fails the test instead of reaching the real - // docker, herd, mkcert, npm, composer or git on the developer's machine. + // docker, herd, lerd, mkcert, npm, composer or git on the developer's machine. // Laravel only refuses strays while faking, hence the empty fake. Process::preventStrayProcesses(); Process::fake([]); + + // Nor the developer's config files: ~/.config/saucebase, ~/.config/lerd. + $this->realHome = $_SERVER['HOME'] ?? null; + $_SERVER['HOME'] = sys_get_temp_dir().'/saucebase-home-'.uniqid(); + mkdir($_SERVER['HOME']); } protected function tearDown(): void { Facade::clearResolvedInstances(); + (new Filesystem)->deleteDirectory($_SERVER['HOME']); + $_SERVER['HOME'] = $this->realHome; + parent::tearDown(); } + /** Lerd's own config, as `~/.config/lerd/config.yaml` holds it. */ + protected function fakeLerdConfig(string $yaml): void + { + @mkdir($_SERVER['HOME'].'/.config/lerd', 0755, true); + file_put_contents($_SERVER['HOME'].'/.config/lerd/config.yaml', $yaml); + } + /** Every tool the installer looks up with `which` is installed. */ protected function fakeToolsInstalled(): void { diff --git a/tests/Unit/ProcessGuardTest.php b/tests/Unit/ProcessGuardTest.php index cdb3628..fd08339 100644 --- a/tests/Unit/ProcessGuardTest.php +++ b/tests/Unit/ProcessGuardTest.php @@ -7,7 +7,7 @@ use Saucebase\Installer\Tests\TestCase; /** - * The installer drives docker, herd, mkcert, npm, composer and git. Under test, + * The installer drives docker, herd, lerd, mkcert, npm, composer and git. Under test, * a process nobody faked fails the test instead of reaching the real tool. */ class ProcessGuardTest extends TestCase From 0487dce07961ff88adebea5ec77bd1422a535610 Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 30 Nov 2026 17:35:53 +0000 Subject: [PATCH 2/2] fix: read Lerd's config as YAML, like Lerd does A blank line after `dns:` hid `enabled: false`, so the installer ran `lerd secure` with Lerd's DNS off, and a dotted suffix such as internal.example.com was cut to its first label. symfony/yaml parses the file; missing or unreadable values keep Lerd's defaults. Also: every test starts with Laravel Prompts non-interactive, instead of the mode the terminal or the previous test left (Prompt::fake() turns it on); and the five new lines over 120 characters are split. Co-Authored-By: Claude Opus 5.5 --- composer.json | 3 +- src/Console/Commands/NewCommand.php | 10 +++++-- src/Environments/LerdEnvironment.php | 30 +++++++++++++------ .../LinkedSiteEnvironmentTest.php | 23 ++++++++++++++ tests/TestCase.php | 6 ++++ 5 files changed, 60 insertions(+), 12 deletions(-) diff --git a/composer.json b/composer.json index b02e253..f058946 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,8 @@ "laravel/installer": "^5.32", "laravel/prompts": "^0.3.26", "symfony/process": "^8.1.9", - "illuminate/process": "^13.38" + "illuminate/process": "^13.38", + "symfony/yaml": "^8.0" }, "require-dev": { "phpunit/phpunit": "^13.4.3", diff --git a/src/Console/Commands/NewCommand.php b/src/Console/Commands/NewCommand.php index d1c149d..3a5270c 100644 --- a/src/Console/Commands/NewCommand.php +++ b/src/Console/Commands/NewCommand.php @@ -100,7 +100,9 @@ public function handle(): int // Laravel's installer has just printed its own next steps; ours come at the end. $this->line(' Laravel is ready. Now setting up Saucebase…'); - $arguments = $this->installArguments($name, $driver, $stack, $ssl, $modules, $domain, $appName, $demo, $workers); + $arguments = $this->installArguments( + $name, $driver, $stack, $ssl, $modules, $domain, $appName, $demo, $workers, + ); $result = $this->call('install', $arguments); if ($result === self::SUCCESS) { @@ -142,7 +144,11 @@ protected function names(?string $folder): array protected function resolveDriver(string $name): Environment { // Offered only where it can run. - $options = $this->driverOptions($name, herd: (new HerdEnvironment)->hasCommand('herd'), lerd: (new LerdEnvironment)->hasCommand('lerd')); + $options = $this->driverOptions( + $name, + herd: (new HerdEnvironment)->hasCommand('herd'), + lerd: (new LerdEnvironment)->hasCommand('lerd'), + ); $driver = $this->option('driver') ?? select( label: 'How would you like to run Saucebase?', diff --git a/src/Environments/LerdEnvironment.php b/src/Environments/LerdEnvironment.php index c8236d5..ac2c435 100644 --- a/src/Environments/LerdEnvironment.php +++ b/src/Environments/LerdEnvironment.php @@ -3,6 +3,8 @@ namespace Saucebase\Installer\Environments; use Saucebase\Installer\Console\Commands\InstallCommand; +use Symfony\Component\Yaml\Exception\ParseException; +use Symfony\Component\Yaml\Yaml; use function Laravel\Prompts\confirm; @@ -41,19 +43,26 @@ public function canSecure(): bool /** * The `dns:` block of Lerd's config: `enabled` and `tld`. Lerd has no command that - * prints them, so the file is read. Missing, Lerd's defaults: on, `test`. + * prints them, so the file is read, as YAML like Lerd reads it. Missing or unreadable, Lerd's defaults: on, `test`. * * @return array{enabled: bool, tld: string} */ private function dns(): array { $home = $_SERVER['HOME'] ?? (getenv('HOME') ?: sys_get_temp_dir()); - $config = (string) @file_get_contents($home.'/.config/lerd/config.yaml'); - $block = preg_match('/^dns:[^\n]*\n((?:[ \t]+[^\n]*\n?)*)/m', $config, $m) === 1 ? $m[1] : ''; + + try { + $config = Yaml::parse((string) @file_get_contents($home.'/.config/lerd/config.yaml')); + } catch (ParseException) { + $config = null; + } + + $dns = is_array($config) && is_array($config['dns'] ?? null) ? $config['dns'] : []; + $tld = is_string($dns['tld'] ?? null) ? trim($dns['tld'], " \t.") : ''; return [ - 'enabled' => preg_match('/^\s+enabled:\s*false\b/m', $block) !== 1, - 'tld' => preg_match('/^\s+tld:\s*["\']?([a-z0-9-]+)/m', $block, $tld) === 1 ? $tld[1] : 'test', + 'enabled' => ($dns['enabled'] ?? true) !== false, + 'tld' => $tld !== '' ? $tld : 'test', ]; } @@ -93,15 +102,18 @@ protected function boot(InstallCommand $command): int protected function nextSteps(InstallCommand $command): array { $site = basename((string) $this->readEnvValue($command, 'APP_HOST'), '.localhost'); + $https = "https://{$site}.{$this->dns()['tld']}"; $dnsOff = $this->canSecure() ? [] : [ - "Lerd's DNS is off, so there is no HTTPS. For `https://{$site}.{$this->dns()['tld']}`: `lerd dns:enable && lerd secure`", + "Lerd's DNS is off, so there is no HTTPS. For `{$https}`: `lerd dns:enable && lerd secure`", ]; + $names = array_map(fn (string $w): string => self::WORKERS[$w], $this->notStarted); + $starts = array_map(fn (string $w): string => "lerd {$w}:start", $this->notStarted); return [...parent::nextSteps($command), ...$dnsOff, match (true) { ! $this->workers => 'Run the queue and scheduler: `lerd queue:start && lerd schedule:start`', - $this->notStarted === [] => 'Lerd runs the queue and scheduler. After you edit a job: `php artisan queue:restart`', - default => 'Run the '.implode(' and ', array_map(fn (string $w): string => self::WORKERS[$w], $this->notStarted)).': `' - .implode(' && ', array_map(fn (string $w): string => "lerd {$w}:start", $this->notStarted)).'`', + $this->notStarted === [] => 'Lerd runs the queue and scheduler. ' + .'After you edit a job: `php artisan queue:restart`', + default => 'Run the '.implode(' and ', $names).': `'.implode(' && ', $starts).'`', }]; } diff --git a/tests/Feature/Environments/LinkedSiteEnvironmentTest.php b/tests/Feature/Environments/LinkedSiteEnvironmentTest.php index d587f60..f629451 100644 --- a/tests/Feature/Environments/LinkedSiteEnvironmentTest.php +++ b/tests/Feature/Environments/LinkedSiteEnvironmentTest.php @@ -162,6 +162,29 @@ public function test_lerd_with_its_dns_off_serves_over_http_at_localhost(): void $this->assertContains("Lerd's DNS is off, so there is no HTTPS. For `https://shop.test`: `lerd dns:enable && lerd secure`", $this->steps($env, $command)); } + /** Lerd reads its config as YAML: a blank line inside `dns:` keeps the block's settings. */ + public function test_a_blank_line_in_lerds_dns_block_keeps_it_off(): void + { + $this->fakeLerdConfig("dns:\n\n enabled: false\n tld: test\n"); + $command = $this->command(installs: true, domain: 'shop.localhost'); + + (new LerdEnvironment)->run($command); + + $this->assertSame(['lerd link shop'], $command->ran); + $this->assertStringContainsString('APP_URL=http://shop.localhost', (string) file_get_contents($this->app.'/.env')); + } + + /** Lerd allows a dotted suffix: the site is served under all of it. */ + public function test_lerd_serves_the_app_under_a_dotted_tld(): void + { + $this->fakeLerdConfig("dns:\n enabled: true\n tld: internal.example.com\n"); + $command = $this->command(installs: true, domain: 'shop.internal.example.com'); + + (new LerdEnvironment)->run($command); + + $this->assertStringContainsString('APP_URL=https://shop.internal.example.com', (string) file_get_contents($this->app.'/.env')); + } + public function test_lerd_serves_the_app_at_its_configured_tld(): void { $this->fakeLerdConfig("dns:\n enabled: true\n tld: dev\n"); diff --git a/tests/TestCase.php b/tests/TestCase.php index ba89bfc..42a2bd5 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -9,6 +9,7 @@ use Illuminate\Process\ProcessResult; use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Process; +use Laravel\Prompts\Prompt; use PHPUnit\Framework\TestCase as BaseTestCase; use Saucebase\Installer\Console\Application; use Symfony\Component\Console\Input\StringInput; @@ -34,6 +35,11 @@ protected function setUp(): void Process::preventStrayProcesses(); Process::fake([]); + // Nor the terminal: Prompts keeps its interactive mode in a static, set from the + // TTY or by whichever test ran last (`Prompt::fake()` turns it on). Each test + // starts without one; a test that types into a prompt calls `Prompt::fake()`. + Prompt::interactive(false); + // Nor the developer's config files: ~/.config/saucebase, ~/.config/lerd. $this->realHome = $_SERVER['HOME'] ?? null; $_SERVER['HOME'] = sys_get_temp_dir().'/saucebase-home-'.uniqid();