From a0e1e02a47c9de22c8d167d6e807b6c971f8a881 Mon Sep 17 00:00:00 2001 From: Dries Vints Date: Fri, 2 Dec 2022 09:32:28 +0100 Subject: [PATCH] Test Valet commands (#1256) * First attempt at testing CLI commands * Apply fixes from StyleCI * Protect from running locally * Fix test * wip * wip * wip * wip * wip * Update app.php * Create config folder and files for CLI tests * Apply fixes from StyleCI * Fix some formatting * Fix imports * Update all output() calls to use the writer passed in by the command Ugly capture of all $outputs from commands, by passing them into `writer()` to be bound into the container, where they can then be pulled out from calls to `output()` and its buddies `info()`, `table()`, and `warning()`. * Apply fixes from StyleCI * Flesh out park command test * Apply fixes from StyleCI * Drop php 7.0 and 7.1 Co-authored-by: StyleCI Bot Co-authored-by: Matt Stauffer --- .github/workflows/tests.yml | 2 +- .gitignore | 1 + cli/Valet/Filesystem.php | 20 + cli/app.php | 804 ++++++++++++++++++++++++++++++ cli/includes/helpers.php | 45 +- cli/valet.php | 728 +-------------------------- composer.json | 5 +- tests/BaseApplicationTestCase.php | 35 ++ tests/BrewTest.php | 3 + tests/CliTest.php | 26 + tests/ConfigurationTest.php | 3 + tests/DnsMasqTest.php | 3 + tests/FilesystemTest.php | 7 + tests/NginxTest.php | 3 + tests/NgrokTest.php | 3 + tests/PhpFpmTest.php | 3 + tests/SiteTest.php | 3 + tests/UsesNullWriter.php | 17 + 18 files changed, 975 insertions(+), 736 deletions(-) create mode 100755 cli/app.php create mode 100644 tests/BaseApplicationTestCase.php create mode 100644 tests/CliTest.php create mode 100644 tests/UsesNullWriter.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 256b431..2bfbdd0 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -16,7 +16,7 @@ jobs: strategy: fail-fast: true matrix: - php: ['7.0', 7.1, 7.2, 7.3, 7.4, '8.0', 8.1, 8.2] + php: [7.2, 7.3, 7.4, '8.0', 8.1, 8.2] name: PHP ${{ matrix.php }} diff --git a/.gitignore b/.gitignore index 8277f6c..9b527bf 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ error.log .idea .phpunit.result.cache tests/conf.d +tests/config/ diff --git a/cli/Valet/Filesystem.php b/cli/Valet/Filesystem.php index cbff03e..fcfc9a0 100644 --- a/cli/Valet/Filesystem.php +++ b/cli/Valet/Filesystem.php @@ -3,6 +3,8 @@ namespace Valet; use CommandLine as CommandLineFacade; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; class Filesystem { @@ -243,6 +245,24 @@ public function unlink($path) } } + /** + * Recursively delete a directory and its contents. + * + * @param string $path + * @return void + */ + public function rmDirAndContents($path) + { + $dir = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS); + $files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST); + + foreach ($files as $file) { + $file->isDir() ? rmdir($file->getRealPath()) : unlink($file->getRealPath()); + } + + rmdir($path); + } + /** * Change the owner of the given path. * diff --git a/cli/app.php b/cli/app.php new file mode 100755 index 0000000..3bf613e --- /dev/null +++ b/cli/app.php @@ -0,0 +1,804 @@ +command('install', function (OutputInterface $output) { + writer($output); + + Nginx::stop(); + + Configuration::install(); + Nginx::install(); + PhpFpm::install(); + DnsMasq::install(Configuration::read()['tld']); + Nginx::restart(); + Valet::symlinkToUsersBin(); + + output(PHP_EOL.'Valet installed successfully!'); +})->descriptions('Install the Valet services'); + +/** + * Most commands are available only if valet is installed. + */ +if (is_dir(VALET_HOME_PATH)) { + /** + * Upgrade helper: ensure the tld config exists or the loopback config exists. + */ + if (empty(Configuration::read()['tld']) || empty(Configuration::read()['loopback'])) { + Configuration::writeBaseConfiguration(); + } + + /** + * Get or set the TLD currently being used by Valet. + */ + $app->command('tld [tld]', function (InputInterface $input, OutputInterface $output, $tld = null) { + writer($output); + + if ($tld === null) { + return output(Configuration::read()['tld']); + } + + $helper = $this->getHelperSet()->get('question'); + $question = new ConfirmationQuestion( + 'Using a custom TLD is no longer officially supported and may lead to unexpected behavior. Do you wish to proceed? [y/N]', + false + ); + + if (false === $helper->ask($input, $output, $question)) { + return warning('No new Valet tld was set.'); + } + + DnsMasq::updateTld( + $oldTld = Configuration::read()['tld'], + $tld = trim($tld, '.') + ); + + Configuration::updateKey('tld', $tld); + + Site::resecureForNewConfiguration(['tld' => $oldTld], ['tld' => $tld]); + PhpFpm::restart(); + Nginx::restart(); + + info('Your Valet TLD has been updated to ['.$tld.'].'); + }, ['domain'])->descriptions('Get or set the TLD used for Valet sites.'); + + /** + * Get or set the loopback address currently being used by Valet. + */ + $app->command('loopback [loopback]', function (InputInterface $input, OutputInterface $output, $loopback = null) { + writer($output); + + if ($loopback === null) { + return output(Configuration::read()['loopback']); + } + + if (filter_var($loopback, FILTER_VALIDATE_IP) === false) { + return warning('['.$loopback.'] is not a valid IP address'); + } + + $oldLoopback = Configuration::read()['loopback']; + + Configuration::updateKey('loopback', $loopback); + + DnsMasq::refreshConfiguration(); + Site::aliasLoopback($oldLoopback, $loopback); + Site::resecureForNewConfiguration(['loopback' => $oldLoopback], ['loopback' => $loopback]); + PhpFpm::restart(); + Nginx::installServer(); + Nginx::restart(); + + info('Your valet loopback address has been updated to ['.$loopback.']'); + })->descriptions('Get or set the loopback address used for Valet sites'); + + /** + * Add the current working directory to the paths configuration. + */ + $app->command('park [path]', function (OutputInterface $output, $path = null) { + writer($output); + + Configuration::addPath($path ?: getcwd()); + + info(($path === null ? 'This' : "The [{$path}]")." directory has been added to Valet's paths.", $output); + })->descriptions('Register the current working (or specified) directory with Valet'); + + /** + * Get all the current sites within paths parked with 'park {path}'. + */ + $app->command('parked', function (OutputInterface $output) { + writer($output); + + $parked = Site::parked(); + + table(['Site', 'SSL', 'URL', 'Path'], $parked->all()); + })->descriptions('Display all the current sites within parked paths'); + + /** + * Remove the current working directory from the paths configuration. + */ + $app->command('forget [path]', function (OutputInterface $output, $path = null) { + writer($output); + + Configuration::removePath($path ?: getcwd()); + + info(($path === null ? 'This' : "The [{$path}]")." directory has been removed from Valet's paths."); + }, ['unpark'])->descriptions('Remove the current working (or specified) directory from Valet\'s list of paths'); + + /** + * Register a symbolic link with Valet. + */ + $app->command('link [name] [--secure]', function (OutputInterface $output, $name, $secure) { + writer($output); + + $linkPath = Site::link(getcwd(), $name = $name ?: basename(getcwd())); + + info('A ['.$name.'] symbolic link has been created in ['.$linkPath.'].'); + + if ($secure) { + $this->runCommand('secure '.$name); + } + })->descriptions('Link the current working directory to Valet'); + + /** + * Display all of the registered symbolic links. + */ + $app->command('links', function (OutputInterface $output) { + writer($output); + + $links = Site::links(); + + table(['Site', 'SSL', 'URL', 'Path', 'PHP Version'], $links->all()); + })->descriptions('Display all of the registered Valet links'); + + /** + * Unlink a link from the Valet links directory. + */ + $app->command('unlink [name]', function (OutputInterface $output, $name) { + writer($output); + + info('The ['.Site::unlink($name).'] symbolic link has been removed.'); + })->descriptions('Remove the specified Valet link'); + + /** + * Secure the given domain with a trusted TLS certificate. + */ + $app->command('secure [domain] [--expireIn=]', function (OutputInterface $output, $domain = null, $expireIn = 368) { + writer($output); + + $url = Site::domain($domain); + + Site::secure($url, null, $expireIn); + + Nginx::restart(); + + info('The ['.$url.'] site has been secured with a fresh TLS certificate.'); + })->descriptions('Secure the given domain with a trusted TLS certificate', [ + '--expireIn' => 'The amount of days the self signed certificate is valid for. Default is set to "368"', + ]); + + /** + * Stop serving the given domain over HTTPS and remove the trusted TLS certificate. + */ + $app->command('unsecure [domain] [--all]', function (OutputInterface $output, $domain = null, $all = null) { + writer($output); + + if ($all) { + Site::unsecureAll(); + + return; + } + + $url = Site::domain($domain); + + Site::unsecure($url); + + Nginx::restart(); + + info('The ['.$url.'] site will now serve traffic over HTTP.'); + })->descriptions('Stop serving the given domain over HTTPS and remove the trusted TLS certificate'); + + /** + * Display all of the currently secured sites. + */ + $app->command('secured', function (OutputInterface $output) { + writer($output); + + $sites = collect(Site::secured())->map(function ($url) { + return ['Site' => $url]; + }); + + table(['Site'], $sites->all()); + })->descriptions('Display all of the currently secured sites'); + + /** + * Create an Nginx proxy config for the specified domain. + */ + $app->command('proxy domain host [--secure]', function (OutputInterface $output, $domain, $host, $secure) { + writer($output); + + Site::proxyCreate($domain, $host, $secure); + Nginx::restart(); + })->descriptions('Create an Nginx proxy site for the specified host. Useful for docker, mailhog etc.', [ + '--secure' => 'Create a proxy with a trusted TLS certificate', + ]); + + /** + * Delete an Nginx proxy config. + */ + $app->command('unproxy domain', function (OutputInterface $output, $domain) { + writer($output); + + Site::proxyDelete($domain); + Nginx::restart(); + })->descriptions('Delete an Nginx proxy config.'); + + /** + * Display all of the sites that are proxies. + */ + $app->command('proxies', function (OutputInterface $output) { + writer($output); + + $proxies = Site::proxies(); + + table(['Site', 'SSL', 'URL', 'Host'], $proxies->all()); + })->descriptions('Display all of the proxy sites'); + + /** + * Determine which Valet driver the current directory is using. + */ + $app->command('which', function (OutputInterface $output) { + writer($output); + + require __DIR__.'/drivers/require.php'; + + $driver = ValetDriver::assign(getcwd(), basename(getcwd()), '/'); + + if ($driver) { + info('This site is served by ['.get_class($driver).'].'); + } else { + warning('Valet could not determine which driver to use for this site.'); + } + })->descriptions('Determine which Valet driver serves the current working directory'); + + /** + * Display all of the registered paths. + */ + $app->command('paths', function (OutputInterface $output) { + writer($output); + + $paths = Configuration::read()['paths']; + + if (count($paths) > 0) { + output(json_encode($paths, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + } else { + info('No paths have been registered.'); + } + })->descriptions('Get all of the paths registered with Valet'); + + /** + * Open the current or given directory in the browser. + */ + $app->command('open [domain]', function (OutputInterface $output, $domain = null) { + writer($output); + + $url = 'http://'.Site::domain($domain); + CommandLine::runAsUser('open '.escapeshellarg($url)); + })->descriptions('Open the site for the current (or specified) directory in your browser'); + + /** + * Generate a publicly accessible URL for your project. + */ + $app->command('share', function (OutputInterface $output) { + writer($output); + + warning('It looks like you are running `cli/valet.php` directly; please use the `valet` script in the project root instead.'); + })->descriptions('Generate a publicly accessible URL for your project'); + + /** + * Echo the currently tunneled URL. + */ + $app->command('fetch-share-url [domain]', function (OutputInterface $output, $domain = null) { + writer($output); + + output(Ngrok::currentTunnelUrl(Site::domain($domain))); + })->descriptions('Get the URL to the current Ngrok tunnel'); + + /** + * Start the daemon services. + */ + $app->command('start [service]', function (OutputInterface $output, $service) { + writer($output); + + switch ($service) { + case '': + DnsMasq::restart(); + PhpFpm::restart(); + Nginx::restart(); + + return info('Valet services have been started.'); + case 'dnsmasq': + DnsMasq::restart(); + + return info('dnsmasq has been started.'); + case 'nginx': + Nginx::restart(); + + return info('Nginx has been started.'); + case 'php': + PhpFpm::restart(); + + return info('PHP has been started.'); + } + + return warning(sprintf('Invalid valet service name [%s]', $service)); + })->descriptions('Start the Valet services'); + + /** + * Restart the daemon services. + */ + $app->command('restart [service]', function (OutputInterface $output, $service) { + writer($output); + + switch ($service) { + case '': + DnsMasq::restart(); + PhpFpm::restart(); + Nginx::restart(); + + return info('Valet services have been restarted.'); + case 'dnsmasq': + DnsMasq::restart(); + + return info('dnsmasq has been restarted.'); + case 'nginx': + Nginx::restart(); + + return info('Nginx has been restarted.'); + case 'php': + PhpFpm::restart(); + + return info('PHP has been restarted.'); + } + + return warning(sprintf('Invalid valet service name [%s]', $service)); + })->descriptions('Restart the Valet services'); + + /** + * Stop the daemon services. + */ + $app->command('stop [service]', function (OutputInterface $output, $service) { + writer($output); + + switch ($service) { + case '': + PhpFpm::stopRunning(); + Nginx::stop(); + + return info('Valet services have been stopped.'); + case 'nginx': + Nginx::stop(); + + return info('Nginx has been stopped.'); + case 'php': + PhpFpm::stopRunning(); + + return info('PHP has been stopped.'); + } + + return warning(sprintf('Invalid valet service name [%s]', $service)); + })->descriptions('Stop the Valet services'); + + /** + * Uninstall Valet entirely. Requires --force to actually remove; otherwise manual instructions are displayed. + */ + $app->command('uninstall [--force]', function (InputInterface $input, OutputInterface $output, $force) { + writer($output); + + if ($force) { + warning('YOU ARE ABOUT TO UNINSTALL Nginx, PHP, Dnsmasq and all Valet configs and logs.'); + $helper = $this->getHelperSet()->get('question'); + $question = new ConfirmationQuestion('Are you sure you want to proceed? ', false); + if (false === $helper->ask($input, $output, $question)) { + return warning('Uninstall aborted.'); + } + info('Removing certificates for all Secured sites...'); + Site::unsecureAll(); + info('Removing Nginx and configs...'); + Nginx::uninstall(); + info('Removing Dnsmasq and configs...'); + DnsMasq::uninstall(); + info('Removing loopback customization...'); + Site::uninstallLoopback(); + info('Removing Valet configs and customizations...'); + Configuration::uninstall(); + info('Removing PHP versions and configs...'); + PhpFpm::uninstall(); + info('Attempting to unlink Valet from bin path...'); + Valet::unlinkFromUsersBin(); + info('Removing sudoers entries...'); + Brew::removeSudoersEntry(); + Valet::removeSudoersEntry(); + + return output('NOTE: +Valet has attempted to uninstall itself, but there are some steps you need to do manually: +Run php -v to see what PHP version you are now really using. +Run composer global update to update your globally-installed Composer packages to work with your default PHP. +NOTE: Composer may have other dependencies for other global apps you have installed, and those may not be compatible with your default PHP. +Thus, you may need to delete things from your ~/.composer/composer.json file before running composer global update successfully. +Then to finish removing any Composer fragments of Valet: +Run composer global remove laravel/valet +and then rm '.BREW_PREFIX.'/bin/valet to remove the Valet bin link if it still exists. +Optional: +- brew list --formula will show any other Homebrew services installed, in case you want to make changes to those as well. +- brew doctor can indicate if there might be any broken things left behind. +- brew cleanup can purge old cached Homebrew downloads. +If you had customized your Mac DNS settings in System Preferences->Network, you will need to remove 127.0.0.1 from that list. +Additionally you might also want to open Keychain Access and search for valet to remove any leftover trust certificates. +'); + } + + output('WAIT! Before you uninstall things, consider cleaning things up in the following order. (Or skip to the bottom for troubleshooting suggestions.): +You did not pass the --force parameter so we are NOT ACTUALLY uninstalling anything. +A --force removal WILL delete your custom configuration information, so you will want to make backups first. + +IF YOU WANT TO UNINSTALL VALET MANUALLY, DO THE FOLLOWING... + +1. Valet Keychain Certificates +Before removing Valet configuration files, we recommend that you run valet unsecure --all to clean up the certificates that Valet inserted into your Keychain. +Alternatively you can do a search for @laravel.valet in Keychain Access and delete those certificates there manually. +You may also run valet parked to see a list of all sites Valet could serve. + +2. Valet Configuration Files +You may remove your user-specific Valet config files by running: rm -rf ~/.config/valet + +3. Remove Valet package +You can run composer global remove laravel/valet to uninstall the Valet package. + +4. Homebrew Services +You may remove the core services (php, nginx, dnsmasq) by running: brew uninstall --force php nginx dnsmasq +You can then remove selected leftover configurations for these services manually in both '.BREW_PREFIX.'/etc/ and '.BREW_PREFIX.'/logs/. +(If you have other PHP versions installed, run brew list --formula | grep php to see which versions you should also uninstall manually.) + +BEWARE: Uninstalling PHP via Homebrew will leave your Mac with its original PHP version, which may not be compatible with other Composer dependencies you have installed. Thus you may get unexpected errors. + +Some additional services which you may have installed (but which Valet does not directly configure or manage) include: mariadb mysql mailhog. +If you wish to also remove them, you may manually run brew uninstall SERVICENAME and clean up their configurations in '.BREW_PREFIX.'/etc if necessary. + +You can discover more Homebrew services by running: brew services list and brew list --formula + +If you have customized your Mac DNS settings in System Preferences->Network, you may need to add or remove 127.0.0.1 from the top of that list. + +5. GENERAL TROUBLESHOOTING +If your reasons for considering an uninstall are more for troubleshooting purposes, consider running brew doctor and/or brew cleanup to see if any problems exist there. +Also consider running sudo nginx -t to test your nginx configs in case there are failures/errors there preventing nginx from running. +Most of the nginx configs used by Valet are in your ~/.config/valet/Nginx directory. + +You might also want to investigate your global Composer configs. Helpful commands include: +composer global update to apply updates to packages +composer global outdated to identify outdated packages +composer global diagnose to run diagnostics +'); + // Stopping PHP so the ~/.config/valet/valet.sock file is released so the directory can be deleted if desired + PhpFpm::stopRunning(); + Nginx::stop(); + })->descriptions('Uninstall the Valet services', ['--force' => 'Do a forceful uninstall of Valet and related Homebrew pkgs']); + + /** + * Determine if this is the latest release of Valet. + */ + $app->command('on-latest-version', function (OutputInterface $output) use ($version) { + writer($output); + + if (Valet::onLatestVersion($version)) { + output('Yes'); + } else { + output(sprintf('Your version of Valet (%s) is not the latest version available.', $version)); + output('Upgrade instructions can be found in the docs: https://laravel.com/docs/valet#upgrading-valet'); + } + }, ['latest'])->descriptions('Determine if this is the latest version of Valet'); + + /** + * Install the sudoers.d entries so password is no longer required. + */ + $app->command('trust [--off]', function (OutputInterface $output, $off) { + writer($output); + + if ($off) { + Brew::removeSudoersEntry(); + Valet::removeSudoersEntry(); + + return info('Sudoers entries have been removed for Brew and Valet.'); + } + + Brew::createSudoersEntry(); + Valet::createSudoersEntry(); + + info('Sudoers entries have been added for Brew and Valet.'); + })->descriptions('Add sudoers files for Brew and Valet to make Valet commands run without passwords', [ + '--off' => 'Remove the sudoers files so normal sudo password prompts are required.', + ]); + + /** + * Allow the user to change the version of php Valet uses. + */ + $app->command('use [phpVersion] [--force]', function (OutputInterface $output, $phpVersion, $force) { + writer($output); + + if (! $phpVersion) { + $site = basename(getcwd()); + $linkedVersion = Brew::linkedPhp(); + + if ($phpVersion = Site::phpRcVersion($site)) { + info("Found '{$site}/.valetphprc' specifying version: {$phpVersion}"); + } else { + $domain = $site.'.'.data_get(Configuration::read(), 'tld'); + if ($phpVersion = PhpFpm::normalizePhpVersion(Site::customPhpVersion($domain))) { + info("Found isolated site '{$domain}' specifying version: {$phpVersion}"); + } + } + + if (! $phpVersion) { + return info("Valet is using {$linkedVersion}."); + } + + if ($linkedVersion == $phpVersion && ! $force) { + return info("Valet is already using {$linkedVersion}."); + } + } + + PhpFpm::useVersion($phpVersion, $force); + })->descriptions('Change the version of PHP used by Valet', [ + 'phpVersion' => 'The PHP version you want to use, e.g php@7.3', + ]); + + /** + * Allow the user to change the version of PHP Valet uses to serve the current site. + */ + $app->command('isolate [phpVersion] [--site=]', function (OutputInterface $output, $phpVersion, $site = null) { + writer($output); + + if (! $site) { + $site = basename(getcwd()); + } + + if (is_null($phpVersion) && $phpVersion = Site::phpRcVersion($site)) { + info("Found '{$site}/.valetphprc' specifying version: {$phpVersion}"); + } + + PhpFpm::isolateDirectory($site, $phpVersion); + })->descriptions('Change the version of PHP used by Valet to serve the current working directory', [ + 'phpVersion' => 'The PHP version you want to use; e.g php@8.1', + '--site' => 'Specify the site to isolate (e.g. if the site isn\'t linked as its directory name)', + ]); + + /** + * Allow the user to un-do specifying the version of PHP Valet uses to serve the current site. + */ + $app->command('unisolate [--site=]', function (OutputInterface $output, $site = null) { + writer($output); + + if (! $site) { + $site = basename(getcwd()); + } + + PhpFpm::unIsolateDirectory($site); + })->descriptions('Stop customizing the version of PHP used by Valet to serve the current working directory', [ + '--site' => 'Specify the site to un-isolate (e.g. if the site isn\'t linked as its directory name)', + ]); + + /** + * List isolated sites. + */ + $app->command('isolated', function (OutputInterface $output) { + writer($output); + + $sites = PhpFpm::isolatedDirectories(); + + table(['Path', 'PHP Version'], $sites->all()); + })->descriptions('List all sites using isolated versions of PHP.'); + + /** + * Get the PHP executable path for a site. + */ + $app->command('which-php [site]', function (OutputInterface $output, $site) { + writer($output); + + $phpVersion = Site::customPhpVersion( + Site::host($site ?: getcwd()).'.'.Configuration::read()['tld'] + ); + + if (! $phpVersion) { + $phpVersion = Site::phpRcVersion($site ?: basename(getcwd())); + } + + return output(Brew::getPhpExecutablePath($phpVersion)); + })->descriptions('Get the PHP executable path for a given site', [ + 'site' => 'The site to get the PHP executable path for', + ]); + + /** + * Proxy commands through to an isolated site's version of PHP. + */ + $app->command('php [command]', function (OutputInterface $output, $command) { + writer($output); + + warning('It looks like you are running `cli/valet.php` directly; please use the `valet` script in the project root instead.'); + })->descriptions("Proxy PHP commands with isolated site's PHP executable", [ + 'command' => "Command to run with isolated site's PHP executable", + ]); + + /** + * Proxy commands through to an isolated site's version of Composer. + */ + $app->command('composer [command]', function (OutputInterface $output, $command) { + writer($output); + + warning('It looks like you are running `cli/valet.php` directly; please use the `valet` script in the project root instead.'); + })->descriptions("Proxy Composer commands with isolated site's PHP executable", [ + 'command' => "Composer command to run with isolated site's PHP executable", + ]); + + /** + * Tail log file. + */ + $app->command('log [-f|--follow] [-l|--lines=] [key]', function (OutputInterface $output, $follow, $lines, $key = null) { + writer($output); + + $defaultLogs = [ + 'php-fpm' => BREW_PREFIX.'/var/log/php-fpm.log', + 'nginx' => VALET_HOME_PATH.'/Log/nginx-error.log', + 'mailhog' => BREW_PREFIX.'/var/log/mailhog.log', + 'redis' => BREW_PREFIX.'/var/log/redis.log', + ]; + + $configLogs = data_get(Configuration::read(), 'logs'); + if (! is_array($configLogs)) { + $configLogs = []; + } + + $logs = array_merge($defaultLogs, $configLogs); + ksort($logs); + + if (! $key) { + info(implode(PHP_EOL, [ + 'In order to tail a log, pass the relevant log key (e.g. "nginx")', + 'along with any optional tail parameters (e.g. "-f" for follow).', + null, + 'For example: "valet log nginx -f --lines=3"', + null, + 'Here are the logs you might be interested in.', + null, + ])); + + table( + ['Keys', 'Files'], + collect($logs)->map(function ($file, $key) { + return [$key, $file]; + })->toArray() + ); + + info(implode(PHP_EOL, [ + null, + 'Tip: Set custom logs by adding a "logs" key/file object', + 'to your "'.Configuration::path().'" file.', + ])); + + exit; + } + + if (! isset($logs[$key])) { + return warning('No logs found for ['.$key.'].'); + } + + $file = $logs[$key]; + if (! file_exists($file)) { + return warning('Log path ['.$file.'] does not (yet) exist.'); + } + + $options = []; + if ($follow) { + $options[] = '-f'; + } + if ((int) $lines) { + $options[] = '-n '.(int) $lines; + } + + $command = implode(' ', array_merge(['tail'], $options, [$file])); + + passthru($command); + })->descriptions('Tail log file'); + + /** + * Configure or display the directory-listing setting. + */ + $app->command('directory-listing [status]', function (OutputInterface $output, $status = null) { + writer($output); + + $key = 'directory-listing'; + $config = Configuration::read(); + + if (in_array($status, ['on', 'off'])) { + $config[$key] = $status; + Configuration::write($config); + + return output('Directory listing setting is now: '.$status); + } + + $current = isset($config[$key]) ? $config[$key] : 'off'; + output('Directory listing is '.$current); + })->descriptions('Determine directory-listing behavior. Default is off, which means a 404 will display.', [ + 'status' => 'on or off. (default=off) will show a 404 page; [on] will display a listing if project folder exists but requested URI not found', + ]); + + /** + * Output diagnostics to aid in debugging Valet. + */ + $app->command('diagnose [-p|--print] [--plain]', function (OutputInterface $output, $print, $plain) { + writer($output); + + info('Running diagnostics... (this may take a while)'); + + Diagnose::run($print, $plain); + + info('Diagnostics output has been copied to your clipboard.'); + })->descriptions('Output diagnostics to aid in debugging Valet.', [ + '--print' => 'print diagnostics output while running', + '--plain' => 'format clipboard output as plain text', + ]); +} + +/** + * Load all of the Valet extensions. + */ +foreach (Valet::extensions() as $extension) { + include $extension; +} + +return $app; diff --git a/cli/includes/helpers.php b/cli/includes/helpers.php index 352d867..f04db5d 100644 --- a/cli/includes/helpers.php +++ b/cli/includes/helpers.php @@ -11,7 +11,11 @@ * Define constants. */ if (! defined('VALET_HOME_PATH')) { - define('VALET_HOME_PATH', $_SERVER['HOME'].'/.config/valet'); + if (testing()) { + define('VALET_HOME_PATH', __DIR__.'/../../tests/config/valet'); + } else { + define('VALET_HOME_PATH', $_SERVER['HOME'].'/.config/valet'); + } } if (! defined('VALET_STATIC_PREFIX')) { define('VALET_STATIC_PREFIX', '41c270e4-5535-4daa-b23e-c269744c2f45'); @@ -25,6 +29,27 @@ define('ISOLATED_PHP_VERSION', 'ISOLATED_PHP_VERSION'); +/** + * Set or get a global console writer. + * + * @param null|Symfony\Component\Console\Output\ConsoleOutputInterface $writer + * @return void|Symfony\Component\Console\Output\ConsoleOutputInterface + */ +function writer($writer = null) +{ + $container = Container::getInstance(); + + if (! $writer) { + if (! $container->bound('writer')) { + $container->instance('writer', new ConsoleOutput()); + } + + return $container->make('writer'); + } + + Container::getInstance()->instance('writer', $writer); +} + /** * Output the given text to the console. * @@ -56,13 +81,23 @@ function warning($output) */ function table(array $headers = [], array $rows = []) { - $table = new Table(new ConsoleOutput); + $table = new Table(writer()); $table->setHeaders($headers)->setRows($rows); $table->render(); } +/** + * Return whether the app is in the testing environment. + * + * @return bool + */ +function testing() +{ + return strpos($_SERVER['SCRIPT_NAME'], 'phpunit') !== false; +} + /** * Output the given text to the console. * @@ -71,11 +106,7 @@ function table(array $headers = [], array $rows = []) */ function output($output) { - if (isset($_ENV['APP_ENV']) && $_ENV['APP_ENV'] === 'testing') { - return; - } - - (new ConsoleOutput())->writeln($output); + writer()->writeln($output); } if (! function_exists('resolve')) { diff --git a/cli/valet.php b/cli/valet.php index c4a4a39..45c0159 100755 --- a/cli/valet.php +++ b/cli/valet.php @@ -1,733 +1,7 @@ #!/usr/bin/env php command('install', function () { - Nginx::stop(); - - Configuration::install(); - Nginx::install(); - PhpFpm::install(); - DnsMasq::install(Configuration::read()['tld']); - Nginx::restart(); - Valet::symlinkToUsersBin(); - - output(PHP_EOL.'Valet installed successfully!'); -})->descriptions('Install the Valet services'); - -/** - * Most commands are available only if valet is installed. - */ -if (is_dir(VALET_HOME_PATH)) { - /** - * Upgrade helper: ensure the tld config exists or the loopback config exists. - */ - if (empty(Configuration::read()['tld']) || empty(Configuration::read()['loopback'])) { - Configuration::writeBaseConfiguration(); - } - - /** - * Get or set the TLD currently being used by Valet. - */ - $app->command('tld [tld]', function (InputInterface $input, OutputInterface $output, $tld = null) { - if ($tld === null) { - return output(Configuration::read()['tld']); - } - - $helper = $this->getHelperSet()->get('question'); - $question = new ConfirmationQuestion( - 'Using a custom TLD is no longer officially supported and may lead to unexpected behavior. Do you wish to proceed? [y/N]', - false - ); - - if (false === $helper->ask($input, $output, $question)) { - return warning('No new Valet tld was set.'); - } - - DnsMasq::updateTld( - $oldTld = Configuration::read()['tld'], - $tld = trim($tld, '.') - ); - - Configuration::updateKey('tld', $tld); - - Site::resecureForNewConfiguration(['tld' => $oldTld], ['tld' => $tld]); - PhpFpm::restart(); - Nginx::restart(); - - info('Your Valet TLD has been updated to ['.$tld.'].'); - }, ['domain'])->descriptions('Get or set the TLD used for Valet sites.'); - - /** - * Get or set the loopback address currently being used by Valet. - */ - $app->command('loopback [loopback]', function ($loopback = null) { - if ($loopback === null) { - return output(Configuration::read()['loopback']); - } - - if (filter_var($loopback, FILTER_VALIDATE_IP) === false) { - return warning('['.$loopback.'] is not a valid IP address'); - } - - $oldLoopback = Configuration::read()['loopback']; - - Configuration::updateKey('loopback', $loopback); - - DnsMasq::refreshConfiguration(); - Site::aliasLoopback($oldLoopback, $loopback); - Site::resecureForNewConfiguration(['loopback' => $oldLoopback], ['loopback' => $loopback]); - PhpFpm::restart(); - Nginx::installServer(); - Nginx::restart(); - - info('Your valet loopback address has been updated to ['.$loopback.']'); - })->descriptions('Get or set the loopback address used for Valet sites'); - - /** - * Add the current working directory to the paths configuration. - */ - $app->command('park [path]', function ($path = null) { - Configuration::addPath($path ?: getcwd()); - - info(($path === null ? 'This' : "The [{$path}]")." directory has been added to Valet's paths."); - })->descriptions('Register the current working (or specified) directory with Valet'); - - /** - * Get all the current sites within paths parked with 'park {path}'. - */ - $app->command('parked', function () { - $parked = Site::parked(); - - table(['Site', 'SSL', 'URL', 'Path'], $parked->all()); - })->descriptions('Display all the current sites within parked paths'); - - /** - * Remove the current working directory from the paths configuration. - */ - $app->command('forget [path]', function ($path = null) { - Configuration::removePath($path ?: getcwd()); - - info(($path === null ? 'This' : "The [{$path}]")." directory has been removed from Valet's paths."); - }, ['unpark'])->descriptions('Remove the current working (or specified) directory from Valet\'s list of paths'); - - /** - * Register a symbolic link with Valet. - */ - $app->command('link [name] [--secure]', function ($name, $secure) { - $linkPath = Site::link(getcwd(), $name = $name ?: basename(getcwd())); - - info('A ['.$name.'] symbolic link has been created in ['.$linkPath.'].'); - - if ($secure) { - $this->runCommand('secure '.$name); - } - })->descriptions('Link the current working directory to Valet'); - - /** - * Display all of the registered symbolic links. - */ - $app->command('links', function () { - $links = Site::links(); - - table(['Site', 'SSL', 'URL', 'Path', 'PHP Version'], $links->all()); - })->descriptions('Display all of the registered Valet links'); - - /** - * Unlink a link from the Valet links directory. - */ - $app->command('unlink [name]', function ($name) { - info('The ['.Site::unlink($name).'] symbolic link has been removed.'); - })->descriptions('Remove the specified Valet link'); - - /** - * Secure the given domain with a trusted TLS certificate. - */ - $app->command('secure [domain] [--expireIn=]', function ($domain = null, $expireIn = 368) { - $url = Site::domain($domain); - - Site::secure($url, null, $expireIn); - - Nginx::restart(); - - info('The ['.$url.'] site has been secured with a fresh TLS certificate.'); - })->descriptions('Secure the given domain with a trusted TLS certificate', [ - '--expireIn' => 'The amount of days the self signed certificate is valid for. Default is set to "368"', - ]); - - /** - * Stop serving the given domain over HTTPS and remove the trusted TLS certificate. - */ - $app->command('unsecure [domain] [--all]', function ($domain = null, $all = null) { - if ($all) { - Site::unsecureAll(); - - return; - } - - $url = Site::domain($domain); - - Site::unsecure($url); - - Nginx::restart(); - - info('The ['.$url.'] site will now serve traffic over HTTP.'); - })->descriptions('Stop serving the given domain over HTTPS and remove the trusted TLS certificate'); - - /** - * Display all of the currently secured sites. - */ - $app->command('secured', function () { - $sites = collect(Site::secured())->map(function ($url) { - return ['Site' => $url]; - }); - - table(['Site'], $sites->all()); - })->descriptions('Display all of the currently secured sites'); - - /** - * Create an Nginx proxy config for the specified domain. - */ - $app->command('proxy domain host [--secure]', function ($domain, $host, $secure) { - Site::proxyCreate($domain, $host, $secure); - Nginx::restart(); - })->descriptions('Create an Nginx proxy site for the specified host. Useful for docker, mailhog etc.', [ - '--secure' => 'Create a proxy with a trusted TLS certificate', - ]); - - /** - * Delete an Nginx proxy config. - */ - $app->command('unproxy domain', function ($domain) { - Site::proxyDelete($domain); - Nginx::restart(); - })->descriptions('Delete an Nginx proxy config.'); - - /** - * Display all of the sites that are proxies. - */ - $app->command('proxies', function () { - $proxies = Site::proxies(); - - table(['Site', 'SSL', 'URL', 'Host'], $proxies->all()); - })->descriptions('Display all of the proxy sites'); - - /** - * Determine which Valet driver the current directory is using. - */ - $app->command('which', function () { - require __DIR__.'/drivers/require.php'; - - $driver = ValetDriver::assign(getcwd(), basename(getcwd()), '/'); - - if ($driver) { - info('This site is served by ['.get_class($driver).'].'); - } else { - warning('Valet could not determine which driver to use for this site.'); - } - })->descriptions('Determine which Valet driver serves the current working directory'); - - /** - * Display all of the registered paths. - */ - $app->command('paths', function () { - $paths = Configuration::read()['paths']; - - if (count($paths) > 0) { - output(json_encode($paths, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); - } else { - info('No paths have been registered.'); - } - })->descriptions('Get all of the paths registered with Valet'); - - /** - * Open the current or given directory in the browser. - */ - $app->command('open [domain]', function ($domain = null) { - $url = 'http://'.Site::domain($domain); - CommandLine::runAsUser('open '.escapeshellarg($url)); - })->descriptions('Open the site for the current (or specified) directory in your browser'); - - /** - * Generate a publicly accessible URL for your project. - */ - $app->command('share', function () { - warning('It looks like you are running `cli/valet.php` directly; please use the `valet` script in the project root instead.'); - })->descriptions('Generate a publicly accessible URL for your project'); - - /** - * Echo the currently tunneled URL. - */ - $app->command('fetch-share-url [domain]', function ($domain = null) { - output(Ngrok::currentTunnelUrl(Site::domain($domain))); - })->descriptions('Get the URL to the current Ngrok tunnel'); - - /** - * Start the daemon services. - */ - $app->command('start [service]', function ($service) { - switch ($service) { - case '': - DnsMasq::restart(); - PhpFpm::restart(); - Nginx::restart(); - - return info('Valet services have been started.'); - case 'dnsmasq': - DnsMasq::restart(); - - return info('dnsmasq has been started.'); - case 'nginx': - Nginx::restart(); - - return info('Nginx has been started.'); - case 'php': - PhpFpm::restart(); - - return info('PHP has been started.'); - } - - return warning(sprintf('Invalid valet service name [%s]', $service)); - })->descriptions('Start the Valet services'); - - /** - * Restart the daemon services. - */ - $app->command('restart [service]', function ($service) { - switch ($service) { - case '': - DnsMasq::restart(); - PhpFpm::restart(); - Nginx::restart(); - - return info('Valet services have been restarted.'); - case 'dnsmasq': - DnsMasq::restart(); - - return info('dnsmasq has been restarted.'); - case 'nginx': - Nginx::restart(); - - return info('Nginx has been restarted.'); - case 'php': - PhpFpm::restart(); - - return info('PHP has been restarted.'); - } - - return warning(sprintf('Invalid valet service name [%s]', $service)); - })->descriptions('Restart the Valet services'); - - /** - * Stop the daemon services. - */ - $app->command('stop [service]', function ($service) { - switch ($service) { - case '': - PhpFpm::stopRunning(); - Nginx::stop(); - - return info('Valet services have been stopped.'); - case 'nginx': - Nginx::stop(); - - return info('Nginx has been stopped.'); - case 'php': - PhpFpm::stopRunning(); - - return info('PHP has been stopped.'); - } - - return warning(sprintf('Invalid valet service name [%s]', $service)); - })->descriptions('Stop the Valet services'); - - /** - * Uninstall Valet entirely. Requires --force to actually remove; otherwise manual instructions are displayed. - */ - $app->command('uninstall [--force]', function ($input, $output, $force) { - if ($force) { - warning('YOU ARE ABOUT TO UNINSTALL Nginx, PHP, Dnsmasq and all Valet configs and logs.'); - $helper = $this->getHelperSet()->get('question'); - $question = new ConfirmationQuestion('Are you sure you want to proceed? ', false); - if (false === $helper->ask($input, $output, $question)) { - return warning('Uninstall aborted.'); - } - info('Removing certificates for all Secured sites...'); - Site::unsecureAll(); - info('Removing Nginx and configs...'); - Nginx::uninstall(); - info('Removing Dnsmasq and configs...'); - DnsMasq::uninstall(); - info('Removing loopback customization...'); - Site::uninstallLoopback(); - info('Removing Valet configs and customizations...'); - Configuration::uninstall(); - info('Removing PHP versions and configs...'); - PhpFpm::uninstall(); - info('Attempting to unlink Valet from bin path...'); - Valet::unlinkFromUsersBin(); - info('Removing sudoers entries...'); - Brew::removeSudoersEntry(); - Valet::removeSudoersEntry(); - - return output('NOTE: -Valet has attempted to uninstall itself, but there are some steps you need to do manually: -Run php -v to see what PHP version you are now really using. -Run composer global update to update your globally-installed Composer packages to work with your default PHP. -NOTE: Composer may have other dependencies for other global apps you have installed, and those may not be compatible with your default PHP. -Thus, you may need to delete things from your ~/.composer/composer.json file before running composer global update successfully. -Then to finish removing any Composer fragments of Valet: -Run composer global remove laravel/valet -and then rm '.BREW_PREFIX.'/bin/valet to remove the Valet bin link if it still exists. -Optional: -- brew list --formula will show any other Homebrew services installed, in case you want to make changes to those as well. -- brew doctor can indicate if there might be any broken things left behind. -- brew cleanup can purge old cached Homebrew downloads. -If you had customized your Mac DNS settings in System Preferences->Network, you will need to remove 127.0.0.1 from that list. -Additionally you might also want to open Keychain Access and search for valet to remove any leftover trust certificates. -'); - } - - output('WAIT! Before you uninstall things, consider cleaning things up in the following order. (Or skip to the bottom for troubleshooting suggestions.): -You did not pass the --force parameter so we are NOT ACTUALLY uninstalling anything. -A --force removal WILL delete your custom configuration information, so you will want to make backups first. - -IF YOU WANT TO UNINSTALL VALET MANUALLY, DO THE FOLLOWING... - -1. Valet Keychain Certificates -Before removing Valet configuration files, we recommend that you run valet unsecure --all to clean up the certificates that Valet inserted into your Keychain. -Alternatively you can do a search for @laravel.valet in Keychain Access and delete those certificates there manually. -You may also run valet parked to see a list of all sites Valet could serve. - -2. Valet Configuration Files -You may remove your user-specific Valet config files by running: rm -rf ~/.config/valet - -3. Remove Valet package -You can run composer global remove laravel/valet to uninstall the Valet package. - -4. Homebrew Services -You may remove the core services (php, nginx, dnsmasq) by running: brew uninstall --force php nginx dnsmasq -You can then remove selected leftover configurations for these services manually in both '.BREW_PREFIX.'/etc/ and '.BREW_PREFIX.'/logs/. -(If you have other PHP versions installed, run brew list --formula | grep php to see which versions you should also uninstall manually.) - -BEWARE: Uninstalling PHP via Homebrew will leave your Mac with its original PHP version, which may not be compatible with other Composer dependencies you have installed. Thus you may get unexpected errors. - -Some additional services which you may have installed (but which Valet does not directly configure or manage) include: mariadb mysql mailhog. -If you wish to also remove them, you may manually run brew uninstall SERVICENAME and clean up their configurations in '.BREW_PREFIX.'/etc if necessary. - -You can discover more Homebrew services by running: brew services list and brew list --formula - -If you have customized your Mac DNS settings in System Preferences->Network, you may need to add or remove 127.0.0.1 from the top of that list. - -5. GENERAL TROUBLESHOOTING -If your reasons for considering an uninstall are more for troubleshooting purposes, consider running brew doctor and/or brew cleanup to see if any problems exist there. -Also consider running sudo nginx -t to test your nginx configs in case there are failures/errors there preventing nginx from running. -Most of the nginx configs used by Valet are in your ~/.config/valet/Nginx directory. - -You might also want to investigate your global Composer configs. Helpful commands include: -composer global update to apply updates to packages -composer global outdated to identify outdated packages -composer global diagnose to run diagnostics -'); - // Stopping PHP so the ~/.config/valet/valet.sock file is released so the directory can be deleted if desired - PhpFpm::stopRunning(); - Nginx::stop(); - })->descriptions('Uninstall the Valet services', ['--force' => 'Do a forceful uninstall of Valet and related Homebrew pkgs']); - - /** - * Determine if this is the latest release of Valet. - */ - $app->command('on-latest-version', function () use ($version) { - if (Valet::onLatestVersion($version)) { - output('Yes'); - } else { - output(sprintf('Your version of Valet (%s) is not the latest version available.', $version)); - output('Upgrade instructions can be found in the docs: https://laravel.com/docs/valet#upgrading-valet'); - } - }, ['latest'])->descriptions('Determine if this is the latest version of Valet'); - - /** - * Install the sudoers.d entries so password is no longer required. - */ - $app->command('trust [--off]', function ($off) { - if ($off) { - Brew::removeSudoersEntry(); - Valet::removeSudoersEntry(); - - return info('Sudoers entries have been removed for Brew and Valet.'); - } - - Brew::createSudoersEntry(); - Valet::createSudoersEntry(); - - info('Sudoers entries have been added for Brew and Valet.'); - })->descriptions('Add sudoers files for Brew and Valet to make Valet commands run without passwords', [ - '--off' => 'Remove the sudoers files so normal sudo password prompts are required.', - ]); - - /** - * Allow the user to change the version of php Valet uses. - */ - $app->command('use [phpVersion] [--force]', function ($phpVersion, $force) { - if (! $phpVersion) { - $site = basename(getcwd()); - $linkedVersion = Brew::linkedPhp(); - - if ($phpVersion = Site::phpRcVersion($site)) { - info("Found '{$site}/.valetphprc' specifying version: {$phpVersion}"); - } else { - $domain = $site.'.'.data_get(Configuration::read(), 'tld'); - if ($phpVersion = PhpFpm::normalizePhpVersion(Site::customPhpVersion($domain))) { - info("Found isolated site '{$domain}' specifying version: {$phpVersion}"); - } - } - - if (! $phpVersion) { - return info("Valet is using {$linkedVersion}."); - } - - if ($linkedVersion == $phpVersion && ! $force) { - return info("Valet is already using {$linkedVersion}."); - } - } - - PhpFpm::useVersion($phpVersion, $force); - })->descriptions('Change the version of PHP used by Valet', [ - 'phpVersion' => 'The PHP version you want to use, e.g php@7.3', - ]); - - /** - * Allow the user to change the version of PHP Valet uses to serve the current site. - */ - $app->command('isolate [phpVersion] [--site=]', function ($phpVersion, $site = null) { - if (! $site) { - $site = basename(getcwd()); - } - - if (is_null($phpVersion) && $phpVersion = Site::phpRcVersion($site)) { - info("Found '{$site}/.valetphprc' specifying version: {$phpVersion}"); - } - - PhpFpm::isolateDirectory($site, $phpVersion); - })->descriptions('Change the version of PHP used by Valet to serve the current working directory', [ - 'phpVersion' => 'The PHP version you want to use; e.g php@8.1', - '--site' => 'Specify the site to isolate (e.g. if the site isn\'t linked as its directory name)', - ]); - - /** - * Allow the user to un-do specifying the version of PHP Valet uses to serve the current site. - */ - $app->command('unisolate [--site=]', function ($site = null) { - if (! $site) { - $site = basename(getcwd()); - } - - PhpFpm::unIsolateDirectory($site); - })->descriptions('Stop customizing the version of PHP used by Valet to serve the current working directory', [ - '--site' => 'Specify the site to un-isolate (e.g. if the site isn\'t linked as its directory name)', - ]); - - /** - * List isolated sites. - */ - $app->command('isolated', function () { - $sites = PhpFpm::isolatedDirectories(); - - table(['Path', 'PHP Version'], $sites->all()); - })->descriptions('List all sites using isolated versions of PHP.'); - - /** - * Get the PHP executable path for a site. - */ - $app->command('which-php [site]', function ($site) { - $phpVersion = Site::customPhpVersion( - Site::host($site ?: getcwd()).'.'.Configuration::read()['tld'] - ); - - if (! $phpVersion) { - $phpVersion = Site::phpRcVersion($site ?: basename(getcwd())); - } - - return output(Brew::getPhpExecutablePath($phpVersion)); - })->descriptions('Get the PHP executable path for a given site', [ - 'site' => 'The site to get the PHP executable path for', - ]); - - /** - * Proxy commands through to an isolated site's version of PHP. - */ - $app->command('php [command]', function ($command) { - warning('It looks like you are running `cli/valet.php` directly; please use the `valet` script in the project root instead.'); - })->descriptions("Proxy PHP commands with isolated site's PHP executable", [ - 'command' => "Command to run with isolated site's PHP executable", - ]); - - /** - * Proxy commands through to an isolated site's version of Composer. - */ - $app->command('composer [command]', function ($command) { - warning('It looks like you are running `cli/valet.php` directly; please use the `valet` script in the project root instead.'); - })->descriptions("Proxy Composer commands with isolated site's PHP executable", [ - 'command' => "Composer command to run with isolated site's PHP executable", - ]); - - /** - * Tail log file. - */ - $app->command('log [-f|--follow] [-l|--lines=] [key]', function ($follow, $lines, $key = null) { - $defaultLogs = [ - 'php-fpm' => BREW_PREFIX.'/var/log/php-fpm.log', - 'nginx' => VALET_HOME_PATH.'/Log/nginx-error.log', - 'mailhog' => BREW_PREFIX.'/var/log/mailhog.log', - 'redis' => BREW_PREFIX.'/var/log/redis.log', - ]; - - $configLogs = data_get(Configuration::read(), 'logs'); - if (! is_array($configLogs)) { - $configLogs = []; - } - - $logs = array_merge($defaultLogs, $configLogs); - ksort($logs); - - if (! $key) { - info(implode(PHP_EOL, [ - 'In order to tail a log, pass the relevant log key (e.g. "nginx")', - 'along with any optional tail parameters (e.g. "-f" for follow).', - null, - 'For example: "valet log nginx -f --lines=3"', - null, - 'Here are the logs you might be interested in.', - null, - ])); - - table( - ['Keys', 'Files'], - collect($logs)->map(function ($file, $key) { - return [$key, $file]; - })->toArray() - ); - - info(implode(PHP_EOL, [ - null, - 'Tip: Set custom logs by adding a "logs" key/file object', - 'to your "'.Configuration::path().'" file.', - ])); - - exit; - } - - if (! isset($logs[$key])) { - return warning('No logs found for ['.$key.'].'); - } - - $file = $logs[$key]; - if (! file_exists($file)) { - return warning('Log path ['.$file.'] does not (yet) exist.'); - } - - $options = []; - if ($follow) { - $options[] = '-f'; - } - if ((int) $lines) { - $options[] = '-n '.(int) $lines; - } - - $command = implode(' ', array_merge(['tail'], $options, [$file])); - - passthru($command); - })->descriptions('Tail log file'); - - /** - * Configure or display the directory-listing setting. - */ - $app->command('directory-listing [status]', function ($status = null) { - $key = 'directory-listing'; - $config = Configuration::read(); - - if (in_array($status, ['on', 'off'])) { - $config[$key] = $status; - Configuration::write($config); - - return output('Directory listing setting is now: '.$status); - } - - $current = isset($config[$key]) ? $config[$key] : 'off'; - output('Directory listing is '.$current); - })->descriptions('Determine directory-listing behavior. Default is off, which means a 404 will display.', [ - 'status' => 'on or off. (default=off) will show a 404 page; [on] will display a listing if project folder exists but requested URI not found', - ]); - - /** - * Output diagnostics to aid in debugging Valet. - */ - $app->command('diagnose [-p|--print] [--plain]', function ($print, $plain) { - info('Running diagnostics... (this may take a while)'); - - Diagnose::run($print, $plain); - - info('Diagnostics output has been copied to your clipboard.'); - })->descriptions('Output diagnostics to aid in debugging Valet.', [ - '--print' => 'print diagnostics output while running', - '--plain' => 'format clipboard output as plain text', - ]); -} - -/** - * Load all of the Valet extensions. - */ -foreach (Valet::extensions() as $extension) { - include $extension; -} +require_once __DIR__.'/app.php'; /** * Run the application. diff --git a/composer.json b/composer.json index 2cdc7a1..7081349 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,9 @@ "files": [ "cli/includes/compatibility.php", "cli/includes/facades.php", - "cli/includes/helpers.php" + "cli/includes/helpers.php", + "tests/UsesNullWriter.php", + "tests/BaseApplicationTestCase.php" ], "psr-4": { "Valet\\": "cli/Valet/" @@ -27,6 +29,7 @@ "php": "^7.0|^8.0", "illuminate/container": "~5.1|^6.0|^7.0|^8.0|^9.0", "mnapoli/silly": "^1.0", + "symfony/console": "^3.0|^4.0|^5.0|^6.0", "symfony/process": "^3.0|^4.0|^5.0|^6.0", "tightenco/collect": "^5.3|^6.0|^7.0|^8.0", "guzzlehttp/guzzle": "^6.0|^7.4" diff --git a/tests/BaseApplicationTestCase.php b/tests/BaseApplicationTestCase.php new file mode 100644 index 0000000..827475d --- /dev/null +++ b/tests/BaseApplicationTestCase.php @@ -0,0 +1,35 @@ +prepTestConfig(); + $this->setNullWriter(); + } + + public function prepTestConfig() + { + require_once __DIR__.'/../cli/includes/helpers.php'; + + if (Filesystem::isDir(VALET_HOME_PATH)) { + Filesystem::rmDirAndContents(VALET_HOME_PATH); + } + + Configuration::createConfigurationDirectory(); + Configuration::writeBaseConfiguration(); + } + + public function appAndTester() + { + $app = require __DIR__.'/../cli/app.php'; + $app->setAutoExit(false); + $tester = new ApplicationTester($app); + + return [$app, $tester]; + } +} diff --git a/tests/BrewTest.php b/tests/BrewTest.php index b47d961..b7f08d4 100644 --- a/tests/BrewTest.php +++ b/tests/BrewTest.php @@ -11,11 +11,14 @@ class BrewTest extends Yoast\PHPUnitPolyfills\TestCases\TestCase { + use UsesNullWriter; + public function set_up() { $_SERVER['SUDO_USER'] = user(); Container::setInstance(new Container); + $this->setNullWriter(); } public function tear_down() diff --git a/tests/CliTest.php b/tests/CliTest.php new file mode 100644 index 0000000..f3bf714 --- /dev/null +++ b/tests/CliTest.php @@ -0,0 +1,26 @@ += 8.0 + */ +class CliTest extends BaseApplicationTestCase +{ + public function test_park_command() + { + [$app, $tester] = $this->appAndTester(); + + $tester->run(['command' => 'park', 'path' => './tests/output']); + + $tester->assertCommandIsSuccessful(); + + $this->assertStringContainsString( + "The [./tests/output] directory has been added to Valet's paths.", + $tester->getDisplay() + ); + + $paths = data_get(Configuration::read(), 'paths'); + + $this->assertEquals(1, count($paths)); + $this->assertEquals('./tests/output', reset($paths)); + } +} diff --git a/tests/ConfigurationTest.php b/tests/ConfigurationTest.php index 8b16083..bde7e62 100644 --- a/tests/ConfigurationTest.php +++ b/tests/ConfigurationTest.php @@ -11,11 +11,14 @@ class ConfigurationTest extends Yoast\PHPUnitPolyfills\TestCases\TestCase { + use UsesNullWriter; + public function set_up() { $_SERVER['SUDO_USER'] = user(); Container::setInstance(new Container); + $this->setNullWriter(); } public function tear_down() diff --git a/tests/DnsMasqTest.php b/tests/DnsMasqTest.php index 0b2a782..1c45b68 100644 --- a/tests/DnsMasqTest.php +++ b/tests/DnsMasqTest.php @@ -12,11 +12,14 @@ class DnsMasqTest extends Yoast\PHPUnitPolyfills\TestCases\TestCase { + use UsesNullWriter; + public function set_up() { $_SERVER['SUDO_USER'] = user(); Container::setInstance(new Container); + $this->setNullWriter(); } public function tear_down() diff --git a/tests/FilesystemTest.php b/tests/FilesystemTest.php index 1562c01..818a894 100644 --- a/tests/FilesystemTest.php +++ b/tests/FilesystemTest.php @@ -4,6 +4,13 @@ class FilesystemTest extends Yoast\PHPUnitPolyfills\TestCases\TestCase { + use UsesNullWriter; + + public function set_up() + { + $this->setNullWriter(); + } + public function tear_down() { exec('rm -rf '.__DIR__.'/output'); diff --git a/tests/NginxTest.php b/tests/NginxTest.php index f05c395..6b0141b 100644 --- a/tests/NginxTest.php +++ b/tests/NginxTest.php @@ -11,11 +11,14 @@ class NginxTest extends Yoast\PHPUnitPolyfills\TestCases\TestCase { + use UsesNullWriter; + public function set_up() { $_SERVER['SUDO_USER'] = user(); Container::setInstance(new Container); + $this->setNullWriter(); } public function tear_down() diff --git a/tests/NgrokTest.php b/tests/NgrokTest.php index 42aed42..97319aa 100644 --- a/tests/NgrokTest.php +++ b/tests/NgrokTest.php @@ -6,11 +6,14 @@ class NgrokTest extends Yoast\PHPUnitPolyfills\TestCases\TestCase { + use UsesNullWriter; + public function set_up() { $_SERVER['SUDO_USER'] = user(); Container::setInstance(new Container); + $this->setNullWriter(); } public function tear_down() diff --git a/tests/PhpFpmTest.php b/tests/PhpFpmTest.php index b9bfc4f..7b5cc4d 100644 --- a/tests/PhpFpmTest.php +++ b/tests/PhpFpmTest.php @@ -14,11 +14,14 @@ class PhpFpmTest extends Yoast\PHPUnitPolyfills\TestCases\TestCase { + use UsesNullWriter; + public function set_up() { $_SERVER['SUDO_USER'] = user(); Container::setInstance(new Container); + $this->setNullWriter(); } public function tear_down() diff --git a/tests/SiteTest.php b/tests/SiteTest.php index 07d3354..039f899 100644 --- a/tests/SiteTest.php +++ b/tests/SiteTest.php @@ -12,11 +12,14 @@ class SiteTest extends Yoast\PHPUnitPolyfills\TestCases\TestCase { + use UsesNullWriter; + public function set_up() { $_SERVER['SUDO_USER'] = user(); Container::setInstance(new Container); + $this->setNullWriter(); } public function tear_down() diff --git a/tests/UsesNullWriter.php b/tests/UsesNullWriter.php new file mode 100644 index 0000000..0b1a71b --- /dev/null +++ b/tests/UsesNullWriter.php @@ -0,0 +1,17 @@ +instance('writer', new class + { + public function writeLn($msg) + { + // do nothing + } + }); + } +}