diff --git a/composer.json b/composer.json index f058946..78263fd 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,23 @@ { "$schema": "https://getcomposer.org/schema.json", "name": "saucebase/installer", - "description": "The Saucebase application installer.", + "description": "The saucebase CLI: creates a Laravel SaaS app from the Saucebase starter kit and sets it up on Docker, native PHP, Laravel Herd or Lerd, with Vue or React and the modules you pick.", + "keywords": [ + "saucebase", + "laravel", + "laravel-installer", + "cli", + "installer", + "scaffolding", + "laravel-starter-kit", + "saas-starter-kit", + "composer", + "docker", + "laravel-herd", + "lerd", + "php-cli" + ], + "homepage": "https://saucebase-dev.github.io/docs/", "type": "library", "license": "MIT", "require": { diff --git a/src/Console/Commands/InstallCommand.php b/src/Console/Commands/InstallCommand.php index 61ccc74..5593ff2 100644 --- a/src/Console/Commands/InstallCommand.php +++ b/src/Console/Commands/InstallCommand.php @@ -6,6 +6,7 @@ use Illuminate\Console\View\TaskResult; use Illuminate\Contracts\Process\ProcessResult; use Illuminate\Support\Facades\Process; +use Illuminate\Support\ProcessUtils; use Illuminate\Support\Str; use Laravel\Prompts\Elements\Element; use Laravel\Prompts\Elements\ElementContract; @@ -125,7 +126,8 @@ public function runArtisan(array $args, int $timeout = 120): bool /** 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 + /** Keeps a failed step's output for warnFailed(); drivers that run their own processes call it too. */ + public function remember(ProcessResult $result): bool { $this->lastFailure = $result->successful() ? null : trim($result->output()."\n".$result->errorOutput()); @@ -743,21 +745,29 @@ private function runInstallTask(string $label, array $command, \Closure $run): b }); if (! $ok) { - // 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}" : '.')); + $this->warnFailed($label); } return $ok; } + /** + * Says why the last command failed, above the failure box that names `$label`. The + * reason only: the box's resume command reruns this step and every one after it (the + * build, HTTPS); re-running this one alone would skip them. + */ + public function warnFailed(string $label): void + { + // 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"); + $this->components->warn("{$label} failed".($why !== '' ? ":\n{$why}" : '.')); + } + /** * @return string[] */ @@ -881,32 +891,32 @@ public function resumeCommand(array $resumeOptions = []): string } foreach ($resumeOptions as $option => $value) { - $command .= " {$option}={$value}"; + $command .= " {$option}=".$this->quotePath((string) $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); + $command .= ' --app-name='.ProcessUtils::escapeArgument($name); } if ($this->domain !== null) { - $command .= ' --domain='.$this->domain; + $command .= ' --domain='.$this->quotePath($this->domain); } if ($modules = $this->resumeModules()) { - $command .= ' --modules='.$modules; + $command .= ' --modules='.$this->quotePath($modules); } if ($template = $this->optionOrNull('template')) { - $command .= ' --template='.$template; + $command .= ' --template='.$this->quotePath((string) $template); } if ($state = $this->optionOrNull('state')) { - $command .= ' --state='.$state; + $command .= ' --state='.$this->quotePath((string) $state); } if ($make = $this->optionOrNull('make-template')) { - $command .= ' --make-template='.$make; + $command .= ' --make-template='.$this->quotePath((string) $make); } foreach (['all-modules', 'dev', 'fresh', 'force', 'demo'] as $flag) { @@ -936,9 +946,9 @@ protected function resumeModules(): ?string return $this->selectedModules ? implode(',', $this->selectedModules) : null; } - /** Quote only when needed, but quote safely: paths can contain $, backticks or quotes. */ + /** Quote only when needed, but quote safely: paths and typed values can contain $, backticks or quotes. */ protected function quotePath(string $path): string { - return preg_match('#^[A-Za-z0-9._/@:+-]+$#', $path) === 1 ? $path : escapeshellarg($path); + return preg_match('#^[A-Za-z0-9._/@:,+-]+$#', $path) === 1 ? $path : ProcessUtils::escapeArgument($path); } } diff --git a/src/Console/Commands/StackCommand.php b/src/Console/Commands/StackCommand.php index 736d821..b47ffe5 100644 --- a/src/Console/Commands/StackCommand.php +++ b/src/Console/Commands/StackCommand.php @@ -5,6 +5,7 @@ use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Facades\Process; +use Illuminate\Support\ProcessUtils; use function Laravel\Prompts\select; @@ -140,7 +141,7 @@ private function inWorkspace(string $command): string { return realpath($this->basePath) === realpath((string) getcwd()) ? $command - : 'cd '.escapeshellarg($this->basePath)." && {$command}"; + : 'cd '.ProcessUtils::escapeArgument($this->basePath)." && {$command}"; } private function runReset(): int diff --git a/src/Environments/DockerEnvironment.php b/src/Environments/DockerEnvironment.php index 60001bf..9d0579f 100644 --- a/src/Environments/DockerEnvironment.php +++ b/src/Environments/DockerEnvironment.php @@ -705,7 +705,7 @@ protected function execInContainer(InstallCommand $command, array $args, int $ti $command->line(trim($result->output().$result->errorOutput())); } - return $result->successful(); + return $command->remember($result); } protected function generateAppKey(InstallCommand $command): bool diff --git a/src/Environments/Environment.php b/src/Environments/Environment.php index 5f367ba..8f468f5 100644 --- a/src/Environments/Environment.php +++ b/src/Environments/Environment.php @@ -3,6 +3,7 @@ namespace Saucebase\Installer\Environments; use Illuminate\Support\Facades\Process; +use Illuminate\Support\ProcessUtils; use Saucebase\Installer\Console\Commands\InstallCommand; abstract class Environment @@ -47,7 +48,7 @@ public function run(InstallCommand $command): int // A module that doesn't fit the installed core installs fine and then breaks // every request, so "complete" waits until the app has actually booted. if (! $this->artisan($command, ['about', '--only=environment'])) { - $result = $this->fail('Checking the app boots'); + $result = $this->failWithReason($command, 'Checking the app boots'); } } @@ -101,6 +102,14 @@ protected function artisanOutput(InstallCommand $command, array $args): ?string return $result->successful() ? $result->output() : null; } + /** fail() after a command: its output says why, the failure box only names the step. */ + protected function failWithReason(InstallCommand $command, string $step): int + { + $command->warnFailed($step); + + return $this->fail($step); + } + /** Record which step failed, then return FAILURE for boot() to propagate. */ protected function fail(string $step): int { @@ -133,7 +142,7 @@ protected function cdStep(InstallCommand $command): array // Relative under the current directory, and quoted only where the shell would split it. $path = str_starts_with($target, $cwd.'/') ? substr($target, strlen($cwd) + 1) : $target; - return ['cd '.(preg_match('#^[\w./-]+$#', $path) === 1 ? $path : escapeshellarg($path))]; + return ['cd '.(preg_match('#^[\w./-]+$#', $path) === 1 ? $path : ProcessUtils::escapeArgument($path))]; } private function normalizePath(string $path): string diff --git a/src/Environments/LinkedSiteEnvironment.php b/src/Environments/LinkedSiteEnvironment.php index a4b7331..d6082a1 100644 --- a/src/Environments/LinkedSiteEnvironment.php +++ b/src/Environments/LinkedSiteEnvironment.php @@ -32,11 +32,11 @@ protected function boot(InstallCommand $command): int $site = $this->site($command); if (! $command->runProcess([$this->name(), 'link', $site])) { - return $this->fail("Linking the site to {$this->tool()}"); + return $this->failWithReason($command, "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()}"); + return $this->failWithReason($command, "Securing the site with {$this->tool()}"); } $env = (string) file_get_contents($command->path('.env')); diff --git a/tests/Feature/Environments/DockerQuietExecTest.php b/tests/Feature/Environments/DockerQuietExecTest.php index 2eb663d..c847901 100644 --- a/tests/Feature/Environments/DockerQuietExecTest.php +++ b/tests/Feature/Environments/DockerQuietExecTest.php @@ -21,6 +21,11 @@ private function execQuietly(string $output, string $errorOutput = '', int $exit /** @var string[] */ public array $printed = []; + public function reason(): ?string + { + return $this->lastFailure; + } + public function line($string, $style = null, $verbosity = null): void { $this->printed[] = $string; @@ -36,9 +41,13 @@ public function quietly(InstallCommand $command): bool } }; + $this->command = $command; + return [$docker->quietly($command), $command->printed]; } + private TestableInstallCommand $command; + public function test_a_quiet_command_prints_nothing_when_it_succeeds(): void { [$ok, $printed] = $this->execQuietly('Seeding database.'); @@ -62,4 +71,12 @@ public function test_the_command_runs_in_the_app_container_from_the_app_folder() Process::assertRan(fn ($process) => $process->command === ['docker', 'compose', 'exec', '-T', 'app', 'php', 'artisan', 'migrate'] && $process->path === sys_get_temp_dir()); } + + /** The boot check's warning names this command's error, not an earlier step's (the build's). */ + public function test_a_failed_command_is_the_reason_the_next_warning_gives(): void + { + $this->execQuietly('', 'Class "App\\Providers\\ModuleServiceProvider" not found', 1); + + $this->assertSame('Class "App\\Providers\\ModuleServiceProvider" not found', $this->command->reason()); + } } diff --git a/tests/Feature/Environments/FinishingStepsTest.php b/tests/Feature/Environments/FinishingStepsTest.php index ca30490..f466608 100644 --- a/tests/Feature/Environments/FinishingStepsTest.php +++ b/tests/Feature/Environments/FinishingStepsTest.php @@ -70,6 +70,7 @@ public function test_an_app_that_does_not_boot_is_not_reported_as_installed(): v $this->assertNull($command->steps, 'no success callout'); $this->assertSame('Checking the app boots', $command->failedStep); + $this->assertSame(['Checking the app boots: Class "App\Providers\ModuleServiceProvider" not found'], $command->warnings); } private function environment(): NativeEnvironment @@ -114,6 +115,11 @@ public function displayFailure(?string $step = null, array $resumeOptions = []): $this->failedStep = $step; } + public function warnFailed(string $label): void + { + $this->warnings[] = "{$label}: {$this->lastFailure}"; + } + public function warn($string, $verbosity = null): void { $this->warnings[] = $string; diff --git a/tests/Feature/Environments/LinkedSiteEnvironmentTest.php b/tests/Feature/Environments/LinkedSiteEnvironmentTest.php index f629451..33b4de1 100644 --- a/tests/Feature/Environments/LinkedSiteEnvironmentTest.php +++ b/tests/Feature/Environments/LinkedSiteEnvironmentTest.php @@ -88,6 +88,20 @@ public function test_without_ssl_it_only_links_and_serves_over_http(string $name $this->assertStringContainsString("APP_URL=http://{$site}.test", (string) file_get_contents($this->app.'/.env')); } + /** The failure box names the step; the tool's own output above it says why. */ + #[DataProvider('drivers')] + public function test_a_failed_link_or_secure_says_why(string $name): void + { + $tool = ucfirst($name); + + foreach (["{$name} link shop" => "Linking the site to {$tool}", "{$name} secure shop" => "Securing the site with {$tool}"] as $failing => $step) { + $command = $this->command(installs: true, domain: 'shop.test', failing: [$failing]); + + $this->assertSame(Command::FAILURE, Environment::make($name)->run($command)); + $this->assertSame([$step], $command->warned); + } + } + #[DataProvider('drivers')] public function test_a_failed_install_is_not_linked(string $name): void { @@ -225,6 +239,9 @@ private function command(bool $installs, string $domain = 'localhost', array $op /** @var list */ public array $ran = []; + /** @var list */ + public array $warned = []; + /** * @param array $options * @param list $failing @@ -260,6 +277,11 @@ public function runProcess(array $command, int $timeout = 300): bool return ! in_array($line, $this->failing, true); } + public function warnFailed(string $label): void + { + $this->warned[] = $label; + } + public function promptForModules(): void {} public function displaySuccess(array $steps = []): void {} diff --git a/tests/Feature/InstallCommandResumeTest.php b/tests/Feature/InstallCommandResumeTest.php index 5bec06b..49e770b 100644 --- a/tests/Feature/InstallCommandResumeTest.php +++ b/tests/Feature/InstallCommandResumeTest.php @@ -71,6 +71,14 @@ public function test_resume_command_keeps_the_app_name_quoted(): void $this->assertStringContainsString("--app-name='Joe'\\''s \$hop'", $resume); } + /** Quoted byte for byte: escapeshellarg drops what a C locale can't read (Linux), so `Café` became `Caf`. */ + public function test_resume_command_keeps_a_non_ascii_name_whole(): void + { + $resume = $this->command(['path' => '/tmp/app', 'app-name' => 'Café São'])->resumeCommand(); + + $this->assertStringContainsString("--app-name='Café São'", $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 { @@ -87,6 +95,15 @@ public function test_resume_command_keeps_the_template_and_its_state(): void $this->assertStringContainsString('--template=saucebase/uptime --state=agency', $resume); } + /** Every typed value survives the shell, not only the app name; plain ones stay unquoted. */ + public function test_resume_command_quotes_any_value_the_shell_would_split(): void + { + $resume = $this->command(['path' => '/tmp/app', 'template' => 'saucebase/uptime', 'state' => "a b's"])->resumeCommand(); + + $this->assertStringContainsString("--state='a b'\\''s'", $resume); + $this->assertStringContainsString('--template=saucebase/uptime', $resume); + } + public function test_resume_command_drops_the_cd_when_the_target_is_the_current_directory(): void { $resume = $this->command(['path' => getcwd()])->resumeCommand(['--driver' => 'native']); diff --git a/tests/Feature/InstallModulesRunnerTest.php b/tests/Feature/InstallModulesRunnerTest.php index 632d46a..f1efc47 100644 --- a/tests/Feature/InstallModulesRunnerTest.php +++ b/tests/Feature/InstallModulesRunnerTest.php @@ -153,6 +153,43 @@ public function newLine($count = 1): static } } + /** A driver's step (Lerd's or Herd's `secure`) fails with its tool's reason too. */ + public function test_a_failed_driver_step_shows_its_tools_error(): void + { + Process::fake(['*' => Process::result(errorOutput: "nginx: [emerg] open() \"/etc/nginx/conf.d/shop.test.conf\" failed\nnginx: configuration file /etc/nginx/nginx.conf test failed\n", exitCode: 1)]); + $command = new class extends TestableInstallCommand + { + /** @var string[] */ + public array $warnings = []; + + public function secure(): bool + { + $warnings = &$this->warnings; + $this->components = new class($warnings) + { + /** @param string[] $warnings */ + public function __construct(private array &$warnings) {} + + public function warn(string $message): void + { + $this->warnings[] = $message; + } + }; + + if ($this->runProcess(['lerd', 'secure', 'shop'])) { + return true; + } + $this->warnFailed('Securing the site with Lerd'); + + return false; + } + }; + $command->fakeOptions = ['path' => $this->tmp]; + + $this->assertFalse($command->secure()); + $this->assertSame(["Securing the site with Lerd failed:\nnginx: [emerg] open() \"/etc/nginx/conf.d/shop.test.conf\" failed\nnginx: configuration file /etc/nginx/nginx.conf test failed"], $command->warnings); + } + /** A failed step shows why, not only how to run it again. */ public function test_a_failed_step_shows_its_error(): void {