diff --git a/bin/rector.php b/bin/rector.php index bb3825b0b93..59a5246c643 100755 --- a/bin/rector.php +++ b/bin/rector.php @@ -3,20 +3,20 @@ declare(strict_types=1); use Composer\XdebugHandler\XdebugHandler; +use Entropy\Console\ConsoleApplication; use Nette\Utils\Json; use PHPStan\PharAutoloader; use PHPStan\Turbo\TurboExtensionEnabler; +use Rector\Application\VersionResolver; use Rector\Bootstrap\AutoloadFileParameterResolver; +use Rector\Bootstrap\CliOptionValueResolver; use Rector\Bootstrap\RectorConfigsResolver; use Rector\ChangesReporting\Output\JsonOutputFormatter; use Rector\Configuration\Option; -use Rector\Console\Style\SymfonyStyleFactory; +use Rector\Console\ExitCode; +use Rector\Console\Style\RectorStyleFactory; use Rector\DependencyInjection\LazyContainerFactory; use Rector\DependencyInjection\RectorContainerFactory; -use Rector\Util\Reflection\PrivatesAccessor; -use Symfony\Component\Console\Application; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\ArgvInput; // @ intentionally: continue anyway @ini_set('memory_limit', '-1'); @@ -160,7 +160,7 @@ public function loadIfExistsAndNotLoadedYet(string $filePath): void $autoloadIncluder->autoloadFromCommandLine(); // restart without Xdebug before the container is built, so the restarted process does not repeat that work -if (! new ArgvInput()->hasParameterOption('--xdebug')) { +if (! in_array('--xdebug', $_SERVER['argv'] ?? [], true)) { $xdebugHandler = new XdebugHandler('rector'); $xdebugHandler->setPersistent(); $xdebugHandler->check(); @@ -177,8 +177,7 @@ public function loadIfExistsAndNotLoadedYet(string $filePath): void $container = $rectorContainerFactory->createFromBootstrapConfigs($bootstrapConfigs); } catch (Throwable $throwable) { // for json output - $argvInput = new ArgvInput(); - $outputFormat = $argvInput->getParameterOption('--' . Option::OUTPUT_FORMAT); + $outputFormat = CliOptionValueResolver::resolve($_SERVER['argv'] ?? [], ['--' . Option::OUTPUT_FORMAT]); // report fatal error in json format if ($outputFormat === JsonOutputFormatter::NAME) { @@ -192,16 +191,75 @@ public function loadIfExistsAndNotLoadedYet(string $filePath): void ]); } else { // report fatal errors in console format - $symfonyStyleFactory = new SymfonyStyleFactory(new PrivatesAccessor()); - $symfonyStyle = $symfonyStyleFactory->create(); + $rectorStyleFactory = new RectorStyleFactory(); + $rectorStyle = $rectorStyleFactory->create(); do { - $symfonyStyle->error(str_replace("\r\n", "\n", $throwable->getMessage())); + $rectorStyle->error(str_replace("\r\n", "\n", $throwable->getMessage())); } while ($throwable = $throwable->getPrevious()); } - exit(Command::FAILURE); + exit(ExitCode::FAILURE); } -/** @var Application $application */ -$application = $container->get(Application::class); -exit($application->run()); +$application = $container->make(ConsoleApplication::class); +$application->setVersion(sprintf('Rector %s', VersionResolver::PACKAGE_VERSION)); + +exit($application->run(rector_normalize_argv($_SERVER['argv'] ?? []))); + +/** + * Strip global decoration flags the former symfony/console handled implicitly, so the Entropy input + * parser does not treat them as unknown options. Inject the default "process" command when the first + * argument is an option or a path, and expand the "p" alias. + * + * @param array $argv + * @return array + */ +function rector_normalize_argv(array $argv): array +{ + $decorationFlags = ['--ansi', '--no-ansi', '--quiet', '-q', '--no-interaction', '-v', '-vv', '-vvv', '--xdebug']; + + if (in_array('--no-ansi', $argv, true)) { + putenv('NO_COLOR=1'); + } + + $normalized = array_values(array_filter( + $argv, + static fn (string $arg): bool => ! in_array($arg, $decorationFlags, true) + )); + + // expand the "p" alias to the "process" command name + if (isset($normalized[1]) && $normalized[1] === 'p') { + $normalized[1] = 'process'; + } + + // leading "help" or "list" tokens show the application help, matching the former symfony/console behavior + if (isset($normalized[1]) && ($normalized[1] === 'help' || $normalized[1] === 'list')) { + return [$normalized[0], '--help']; + } + + // first real argument is an option or a path - inject the default "process" command, so the parser + // does not mistake a leading "--option" or a path for an unknown command + $helpFlags = ['-h', '--help']; + if ( + isset($normalized[1]) + && $normalized[1] !== 'process' + && ! in_array($normalized[1], $helpFlags, true) + && (str_starts_with($normalized[1], '-') || ! rector_is_known_command($normalized[1])) + ) { + array_splice($normalized, 1, 0, 'process'); + } + + return $normalized; +} + +/** + * The commands a leading token may name; anything else is a path for the default "process" command. + */ +function rector_is_known_command(string $token): bool +{ + return in_array( + $token, + ['process', 'worker', 'list-rules', 'validate-config', 'composer-based'], + true + ); +} diff --git a/build/build-preload.php b/build/build-preload.php index 9f1d2f04428..75c89dcd0ac 100755 --- a/build/build-preload.php +++ b/build/build-preload.php @@ -5,9 +5,8 @@ declare(strict_types=1); use Nette\Utils\Strings; -use Rector\Console\Style\SymfonyStyleFactory; -use Rector\Util\Reflection\PrivatesAccessor; -use Symfony\Component\Console\Command\Command; +use Rector\Console\ExitCode; +use Rector\Console\Style\RectorStyleFactory; use Symfony\Component\Finder\Finder; $possiblePaths = [ @@ -28,13 +27,13 @@ $buildDirectory = $argv[1]; -$symfonyStyleFactory = new SymfonyStyleFactory(new PrivatesAccessor()); -$symfonyStyle = $symfonyStyleFactory->create(); +$rectorStyleFactory = new RectorStyleFactory(); +$rectorStyle = $rectorStyleFactory->create(); if (! is_string($buildDirectory)) { $errorMessage = 'Provide build directory path as an argument, e.g. "php build-preload.php rector-build-directory"'; - $symfonyStyle->error($errorMessage); - exit(Command::FAILURE); + $rectorStyle->error($errorMessage); + exit(ExitCode::FAILURE); } $preloadBuilder = new PreloadBuilder(); diff --git a/composer.json b/composer.json index 1fc9f53c175..9a05a5832d3 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ "composer/pcre": "^3.4.0", "composer/semver": "^3.6", "composer/xdebug-handler": "^3.0.5", - "entropy/entropy": "^0.4.12", + "entropy/entropy": "^0.4.37", "fidry/cpu-core-counter": "^1.4", "nette/utils": "^4.1.5", "nikic/php-parser": "^5.9", @@ -33,7 +33,6 @@ "rector/rector-phpunit": "dev-main", "rector/rector-symfony": "dev-main", "sebastian/diff": "^9.0", - "symfony/console": "^6.4.24", "symfony/filesystem": "^8.1", "symfony/finder": "^8.1", "webmozart/assert": "^2.5" diff --git a/e2e/e2eTestRunner.php b/e2e/e2eTestRunner.php index 7734416a891..7029a811e50 100644 --- a/e2e/e2eTestRunner.php +++ b/e2e/e2eTestRunner.php @@ -6,10 +6,9 @@ use Rector\Console\Formatter\ColorConsoleDiffFormatter; use Rector\Console\Formatter\ConsoleDiffer; -use Rector\Console\Style\SymfonyStyleFactory; +use Rector\Console\ExitCode; +use Rector\Console\Style\RectorStyleFactory; use Rector\Differ\DefaultDiffer; -use Rector\Util\Reflection\PrivatesAccessor; -use Symfony\Component\Console\Command\Command; $projectRoot = __DIR__ .'/..'; $rectorBin = $projectRoot . '/bin/rector'; @@ -59,20 +58,20 @@ exit($exitCode); } -$symfonyStyleFactory = new SymfonyStyleFactory(new PrivatesAccessor()); -$symfonyStyle = $symfonyStyleFactory->create(); +$rectorStyleFactory = new RectorStyleFactory(); +$rectorStyle = $rectorStyleFactory->create(); $matchedExpectedOutput = false; $expectedOutput = trim((string) file_get_contents($expectedDiff)); if ($output === $expectedOutput) { - $symfonyStyle->success('End-to-end test successfully completed'); - exit(Command::SUCCESS); + $rectorStyle->success('End-to-end test successfully completed'); + exit(ExitCode::SUCCESS); } // print color diff, to make easy find the differences $defaultDiffer = new DefaultDiffer(); $colorConsoleDiffFormatter = new ColorConsoleDiffFormatter(); $diff = $colorConsoleDiffFormatter->format($defaultDiffer->diff($output, $expectedOutput)); -$symfonyStyle->writeln($diff); +$rectorStyle->writeln($diff); -exit(Command::FAILURE); +exit(ExitCode::FAILURE); diff --git a/e2e/parallel-reflection-resolver/expected-output.diff b/e2e/parallel-reflection-resolver/expected-output.diff index a9e4b1fbc8f..ab74b6019ba 100644 --- a/e2e/parallel-reflection-resolver/expected-output.diff +++ b/e2e/parallel-reflection-resolver/expected-output.diff @@ -15,7 +15,6 @@ Applied rules: * RemoveUnusedPrivatePropertyRector - 2) src/SomeClassNotFound.php:4 ---------- begin diff ---------- diff --git a/e2e/parallel-system-errors-limit/expected-output.diff b/e2e/parallel-system-errors-limit/expected-output.diff index ef787becca4..e158ce0d9dc 100644 --- a/e2e/parallel-system-errors-limit/expected-output.diff +++ b/e2e/parallel-system-errors-limit/expected-output.diff @@ -1,156 +1,155 @@ [ERROR] Could not process "src/File05.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File06.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File07.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File08.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File09.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File10.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File11.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File12.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File13.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File14.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File15.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File16.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File17.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File18.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File19.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File20.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File21.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File22.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File23.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File24.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File25.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File26.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File27.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File28.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File29.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File30.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File31.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File32.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File33.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File34.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File35.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File36.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File37.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File38.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File39.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File40.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File41.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File42.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File43.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File44.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File45.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File46.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File47.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File48.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File49.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File50.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File51.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File52.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File53.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process "src/File54.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process some files, due to: - "Reached system errors count limit of 50, exiting...". +"Reached system errors count limit of 50, exiting...". [ERROR] Could not process some files, due to: - "Some parallel jobs have not finished, results for 1 of 55 files are - missing". +"Some parallel jobs have not finished, results for 1 of 55 files are missing". diff --git a/e2e/parallel-unfinished-jobs/expected-output.diff b/e2e/parallel-unfinished-jobs/expected-output.diff index 59be2f290fe..6890d9bfd07 100644 --- a/e2e/parallel-unfinished-jobs/expected-output.diff +++ b/e2e/parallel-unfinished-jobs/expected-output.diff @@ -16,8 +16,7 @@ Applied rules: [ERROR] Could not process "src/File2.php" file, due to: - "Syntax error, unexpected ';'". On line: 3 +"Syntax error, unexpected ';'". On line: 3 [ERROR] Could not process some files, due to: - "Some parallel jobs have not finished, results for 2 of 4 files are - missing". +"Some parallel jobs have not finished, results for 2 of 4 files are missing". diff --git a/e2e/parallel-unused-skips/expected-output.diff b/e2e/parallel-unused-skips/expected-output.diff index adbcf14bc47..8d9ec6e65e8 100644 --- a/e2e/parallel-unused-skips/expected-output.diff +++ b/e2e/parallel-unused-skips/expected-output.diff @@ -1,7 +1,5 @@ [OK] Rector is done! - [WARNING] This skip is unused, it never matched any element. You can remove it - from "->withSkip()" - + [WARNING] This skip is unused, it never matched any element. You can remove it from "->withSkip()" * Rector\CodeQuality\Rector\FunctionLike\SimplifyUselessVariableRector: * */NonexistentUnused/* diff --git a/e2e/parallel-worker-respawn/expected-output.diff b/e2e/parallel-worker-respawn/expected-output.diff index 59e4cf1eb40..84747c6ecc8 100644 --- a/e2e/parallel-worker-respawn/expected-output.diff +++ b/e2e/parallel-worker-respawn/expected-output.diff @@ -14,7 +14,6 @@ Applied rules: * LongArrayToShortArrayRector - 2) src/File02.php:1 ---------- begin diff ---------- @@ -28,7 +27,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 3) src/File03.php:1 ---------- begin diff ---------- @@ -42,7 +40,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 4) src/File04.php:1 ---------- begin diff ---------- @@ -56,7 +53,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 5) src/File05.php:1 ---------- begin diff ---------- @@ -70,7 +66,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 6) src/File06.php:1 ---------- begin diff ---------- @@ -84,7 +79,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 7) src/File07.php:1 ---------- begin diff ---------- @@ -98,7 +92,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 8) src/File08.php:1 ---------- begin diff ---------- @@ -112,7 +105,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 9) src/File09.php:1 ---------- begin diff ---------- @@ -126,7 +118,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 10) src/File10.php:1 ---------- begin diff ---------- @@ -140,7 +131,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 11) src/File11.php:1 ---------- begin diff ---------- @@ -154,7 +144,6 @@ Applied rules: Applied rules: * LongArrayToShortArrayRector - 12) src/File12.php:1 ---------- begin diff ---------- diff --git a/e2e/rules-summary-option/expected-output.diff b/e2e/rules-summary-option/expected-output.diff index 15dfdaa0ad6..6d430b2a993 100644 --- a/e2e/rules-summary-option/expected-output.diff +++ b/e2e/rules-summary-option/expected-output.diff @@ -1,3 +1,5 @@ +[WARNING] The "--rules-summary" option is deprecated and will be removed. Use "--output-format=json" instead, which reports every applied rule with its file and line. + 3 files with changes ==================== @@ -22,7 +24,6 @@ Applied rules: * RemoveAlwaysTrueIfConditionRector - 2) src/AnotherAlwaysTrue.php:4 ---------- begin diff ---------- @@ -41,7 +42,6 @@ Applied rules: Applied rules: * RemoveAlwaysTrueIfConditionRector - 3) src/DeadConstructor.php:2 ---------- begin diff ---------- @@ -61,8 +61,8 @@ Applied rules: Rules Summary ------------- - * RemoveAlwaysTrueIfConditionRector would have been applied 2 times * RemoveEmptyClassMethodRector would have been applied 1 time - [OK] 3 files would have been changed (dry-run) by Rector \ No newline at end of file + + [OK] 3 files would have been changed (dry-run) by Rector diff --git a/phpstan.neon b/phpstan.neon index c154214183a..ac96ab6e6f5 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -127,9 +127,6 @@ parameters: identifier: argument.type message: '#expects array, array given#' - # unable for the downgraded rector to find the class, but it is there - - identifier: symplify.commandHasAsCommandAttribute - # false positive, can accept non-class string - identifier: argument.type diff --git a/scripts/avoid-short-node-names-in-fixtures.php b/scripts/avoid-short-node-names-in-fixtures.php index 3c488da66b4..65c96213d40 100644 --- a/scripts/avoid-short-node-names-in-fixtures.php +++ b/scripts/avoid-short-node-names-in-fixtures.php @@ -5,10 +5,8 @@ declare(strict_types=1); use Nette\Utils\Strings; +use Rector\Console\Style\RectorStyleFactory; use Rector\Scripts\Finder\FixtureFinder; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; @@ -31,7 +29,7 @@ $shortNodeClassNames[] = $nodeFileInfo->getBasename('.php'); } -$symfonyStyle = new SymfonyStyle(new ArrayInput([]), new ConsoleOutput()); +$rectorStyle = new RectorStyleFactory()->create(); $hasErrors = false; @@ -49,7 +47,7 @@ continue; } - $symfonyStyle->writeln(sprintf( + $rectorStyle->writeln(sprintf( 'Fixture class name "%s" conflicts with native short node name.%sChange it to different to avoid IDE incorrect autocomplete:%s%s%s', $fixtureClassName, PHP_EOL, diff --git a/scripts/check-before-after-same-fixtures.php b/scripts/check-before-after-same-fixtures.php index 8127038d1bc..1d4f68e5a24 100644 --- a/scripts/check-before-after-same-fixtures.php +++ b/scripts/check-before-after-same-fixtures.php @@ -6,24 +6,22 @@ use Rector\Scripts\Finder\FixtureFinder; require __DIR__ . '/../vendor/autoload.php'; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\ArgvInput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Style\SymfonyStyle; +use Rector\Console\ExitCode; +use Rector\Console\Style\RectorStyle; +use Rector\Console\Style\RectorStyleFactory; use Symfony\Component\Finder\SplFileInfo; final readonly class SameBeforeAfterFixtureDetector { - private SymfonyStyle $symfonyStyle; + private RectorStyle $rectorStyle; public function __construct() { - $this->symfonyStyle = new SymfonyStyle(new ArgvInput(), new ConsoleOutput()); + $this->rectorStyle = new RectorStyleFactory()->create(); } /** * @param string[] $testDirectories - * @return Command::SUCCESS|Command::FAILURE */ public function run(array $testDirectories): int { @@ -39,16 +37,16 @@ public function run(array $testDirectories): int } if ($invalidFixturePaths === []) { - $this->symfonyStyle->success(sprintf('All %d fixtures are valid', count($fixtureFiles))); - return Command::SUCCESS; + $this->rectorStyle->success(sprintf('All %d fixtures are valid', count($fixtureFiles))); + return ExitCode::SUCCESS; } - $this->symfonyStyle->error( + $this->rectorStyle->error( 'The following fixtures have the same before and after content. Remove the part after "-----" to fix them' ); - $this->symfonyStyle->listing($invalidFixturePaths); + $this->rectorStyle->listing($invalidFixturePaths); - return Command::FAILURE; + return ExitCode::FAILURE; } private function hasFileSameBeforeAndAfterPart(SplFileInfo $fixtureFile): bool diff --git a/scripts/generate-composer-based-trigger-packages.php b/scripts/generate-composer-based-trigger-packages.php index 986a9f59c25..f0482a3873b 100644 --- a/scripts/generate-composer-based-trigger-packages.php +++ b/scripts/generate-composer-based-trigger-packages.php @@ -5,15 +5,13 @@ use Rector\Config\RectorConfig; use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; +use Rector\Console\Style\RectorStyleFactory; use Rector\Doctrine\Set\DoctrineSetList; use Rector\PHPUnit\Set\PHPUnitSetList; use Rector\Symfony\Set\SymfonySetList; use Rector\Symfony\Set\TwigSetList; use Rector\VersionBonding\Contract\ComposerPackageConstraintInterface; use Rector\VersionBonding\ValueObject\ComposerBoundRuleConfiguration; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Style\SymfonyStyle; require __DIR__ . '/../vendor/autoload.php'; @@ -123,10 +121,10 @@ final class ComposerBasedTriggerPackages $targetFilePath = __DIR__ . '/../src/Configuration/ComposerBasedTriggerPackages.php'; file_put_contents($targetFilePath, $fileContents); -$symfonyStyle = new SymfonyStyle(new ArrayInput([]), new ConsoleOutput()); +$rectorStyle = new RectorStyleFactory()->create(); foreach ($triggerPackages as $argumentName => $packageNames) { - $symfonyStyle->writeln(sprintf('%s: %d packages', $argumentName, count($packageNames))); + $rectorStyle->writeln(sprintf('%s: %d packages', $argumentName, count($packageNames))); } -$symfonyStyle->success(sprintf('File "%s" was generated', realpath($targetFilePath))); +$rectorStyle->success(sprintf('File "%s" was generated', realpath($targetFilePath))); diff --git a/scripts/list-non-composer-based-rules.php b/scripts/list-non-composer-based-rules.php index 337187818ac..d3af4ee7b23 100644 --- a/scripts/list-non-composer-based-rules.php +++ b/scripts/list-non-composer-based-rules.php @@ -2,12 +2,10 @@ declare(strict_types=1); +use Rector\Console\Style\RectorStyleFactory; use Rector\Scripts\Finder\RectorClassFinder; use Rector\Scripts\Finder\RectorSetFilesFinder; use Rector\Scripts\Resolver\UsedRectorClassResolver; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Style\SymfonyStyle; require __DIR__ . '/../vendor/autoload.php'; @@ -20,8 +18,8 @@ __DIR__ . '/../vendor/rector/rector-symfony', ]); -$symfonyStyle = new SymfonyStyle(new ArrayInput([]), new ConsoleOutput()); -$symfonyStyle->writeln(sprintf('Found Rector %d rules', count($rectorClasses))); +$rectorStyle = new RectorStyleFactory()->create(); +$rectorStyle->writeln(sprintf('Found Rector %d rules', count($rectorClasses))); // 2. find "composer-based.php" sets, that bind rules to the installed package version $rectorSetFilesFinder = new RectorSetFilesFinder(); @@ -37,13 +35,13 @@ static fn (string $rectorSetFile): bool => basename($rectorSetFile) === 'composer-based.php' ); -$symfonyStyle->writeln(sprintf('Found %d composer-based sets', count($composerBasedSetFiles))); -$symfonyStyle->listing($composerBasedSetFiles); +$rectorStyle->writeln(sprintf('Found %d composer-based sets', count($composerBasedSetFiles))); +$rectorStyle->listing($composerBasedSetFiles); $usedRectorClassResolver = new UsedRectorClassResolver(); $usedRectorRules = $usedRectorClassResolver->resolve($composerBasedSetFiles); -$symfonyStyle->writeln( +$rectorStyle->writeln( sprintf('Found %d Rector rules used in composer-based sets', count($usedRectorRules)) ); @@ -54,7 +52,7 @@ $versionAgnosticRectorRules = $usedRectorClassResolver->resolve($versionAgnosticSetFiles); -$symfonyStyle->writeln( +$rectorStyle->writeln( sprintf( 'Found %d Rector rules used in version-agnostic sets', count($versionAgnosticRectorRules) @@ -63,13 +61,13 @@ $nonComposerBasedRectorRules = array_diff($rectorClasses, $usedRectorRules, $versionAgnosticRectorRules); -$symfonyStyle->newLine(); -$symfonyStyle->listing($nonComposerBasedRectorRules); +$rectorStyle->newLine(); +$rectorStyle->listing($nonComposerBasedRectorRules); -$symfonyStyle->writeln( +$rectorStyle->writeln( sprintf( 'Found %d Rector rules not in any composer-based set, likely dead', count($nonComposerBasedRectorRules) ) ); -$symfonyStyle->newLine(); +$rectorStyle->newLine(); diff --git a/scripts/list-unused-rules.php b/scripts/list-unused-rules.php index 55bfee76e10..b45b096ddc5 100644 --- a/scripts/list-unused-rules.php +++ b/scripts/list-unused-rules.php @@ -3,13 +3,11 @@ declare(strict_types=1); use Rector\Configuration\Deprecation\Contract\DeprecatedInterface; +use Rector\Console\Style\RectorStyleFactory; use Rector\Contract\Rector\ConfigurableRectorInterface; use Rector\Scripts\Finder\RectorClassFinder; use Rector\Scripts\Finder\RectorSetFilesFinder; use Rector\Scripts\Resolver\UsedRectorClassResolver; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Style\SymfonyStyle; require __DIR__ . '/../vendor/autoload.php'; @@ -24,8 +22,8 @@ __DIR__ . '/../vendor/rector/rector-downgrade-php', ]); -$symfonyStyle = new SymfonyStyle(new ArrayInput([]), new ConsoleOutput()); -$symfonyStyle->writeln(sprintf('Found Rector %d rules', count($rectorClasses))); +$rectorStyle = new RectorStyleFactory()->create(); +$rectorStyle->writeln(sprintf('Found Rector %d rules', count($rectorClasses))); $rectorSeFinder = new RectorSetFilesFinder(); @@ -37,13 +35,13 @@ __DIR__ . '/../vendor/rector/rector-downgrade-php/config/set', ]); -$symfonyStyle->writeln(sprintf('Found %d sets', count($rectorSetFiles))); +$rectorStyle->writeln(sprintf('Found %d sets', count($rectorSetFiles))); $usedRectorClassResolver = new UsedRectorClassResolver(); $usedRectorRules = $usedRectorClassResolver->resolve($rectorSetFiles); -$symfonyStyle->newLine(); -$symfonyStyle->writeln(sprintf('Found %d used Rector rules in sets', count($usedRectorRules))); +$rectorStyle->newLine(); +$rectorStyle->writeln(sprintf('Found %d used Rector rules in sets', count($usedRectorRules))); $unusedRectorRules = array_diff($rectorClasses, $usedRectorRules); @@ -63,16 +61,16 @@ $unusedRectorRules = array_diff($unusedRectorRules, $deprecatedRectorRules); -$symfonyStyle->newLine(); -$symfonyStyle->listing($unusedRectorRules); +$rectorStyle->newLine(); +$rectorStyle->listing($unusedRectorRules); -$symfonyStyle->writeln( +$rectorStyle->writeln( sprintf('Found %d Rector rules not in any set', count($unusedRectorRules)) ); -$symfonyStyle->writeln( +$rectorStyle->writeln( sprintf('Skipped %d configurable Rector rules', count($configurableRectorRules)) ); -$symfonyStyle->writeln( +$rectorStyle->writeln( sprintf('Skipped %d deprecated Rector rules', count($deprecatedRectorRules)) ); -$symfonyStyle->newLine(); +$rectorStyle->newLine(); diff --git a/scripts/no-php-file-in-fixtures.php b/scripts/no-php-file-in-fixtures.php index 59107888ad6..7b5b1b37990 100644 --- a/scripts/no-php-file-in-fixtures.php +++ b/scripts/no-php-file-in-fixtures.php @@ -4,10 +4,9 @@ require __DIR__ . '/../vendor/autoload.php'; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\ArgvInput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Style\SymfonyStyle; +use Rector\Console\ExitCode; +use Rector\Console\Style\RectorStyle; +use Rector\Console\Style\RectorStyleFactory; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; use Webmozart\Assert\Assert; @@ -22,17 +21,16 @@ 'rules-tests/Renaming/Rector/Name/RenameClassRector/FixtureAutoImportNames/SomeShort.php', ]; - private SymfonyStyle $symfonyStyle; + private RectorStyle $rectorStyle; public function __construct() { - $this->symfonyStyle = new SymfonyStyle(new ArgvInput(), new ConsoleOutput()); + $this->rectorStyle = new RectorStyleFactory()->create(); } /** * @param string[] $ruleTestDirectories * @param string[] $testDirectories - * @return Command::SUCCESS|Command::FAILURE */ public function run(array $ruleTestDirectories, array $testDirectories): int { @@ -57,16 +55,16 @@ public function run(array $ruleTestDirectories, array $testDirectories): int } if ($relativeInvalidFilePaths === []) { - $this->symfonyStyle->success(sprintf('All %d fixtures are valid', count($allFixtureFiles))); - return Command::SUCCESS; + $this->rectorStyle->success(sprintf('All %d fixtures are valid', count($allFixtureFiles))); + return ExitCode::SUCCESS; } - $this->symfonyStyle->error( + $this->rectorStyle->error( 'The following files were found in /Fixtures directory, but only "*.php.inc" files are picked up and allowed. Rename their suffix or remove them' ); - $this->symfonyStyle->listing($relativeInvalidFilePaths); + $this->rectorStyle->listing($relativeInvalidFilePaths); - return Command::FAILURE; + return ExitCode::FAILURE; } /** diff --git a/scripts/validate-phpstan-version.php b/scripts/validate-phpstan-version.php index 577dac124c2..a49df0094e1 100644 --- a/scripts/validate-phpstan-version.php +++ b/scripts/validate-phpstan-version.php @@ -2,9 +2,9 @@ declare(strict_types=1); +use Rector\Console\ExitCode; use Rector\Exception\ShouldNotHappenException; use Rector\FileSystem\JsonFileSystem; -use Symfony\Component\Console\Command\Command; require __DIR__ . '/../vendor/autoload.php'; @@ -18,7 +18,7 @@ if ($localPHPStanVersion === $downgradedPHPStanVersion) { echo '[OK] PHPStan version in local and downgraded composer.json are equal, good job!' . PHP_EOL; - exit(Command::SUCCESS); + exit(ExitCode::SUCCESS); } echo sprintf( @@ -27,7 +27,7 @@ $downgradedPHPStanVersion, PHP_EOL ) . PHP_EOL; -exit(Command::FAILURE); +exit(ExitCode::FAILURE); final class PackageVersionResolver { diff --git a/scripts/validate-rule-definitions.php b/scripts/validate-rule-definitions.php index 5908dcf19d2..875d51562e4 100644 --- a/scripts/validate-rule-definitions.php +++ b/scripts/validate-rule-definitions.php @@ -3,15 +3,13 @@ declare(strict_types=1); use Rector\Console\ExitCode; +use Rector\Console\Style\RectorStyleFactory; use Rector\RuleDoc\Contract\DocumentedRuleInterface; use Rector\Scripts\Finder\RectorClassFinder; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Style\SymfonyStyle; require __DIR__ . '/../vendor/autoload.php'; -$symfonyStyle = new SymfonyStyle(new ArrayInput([]), new ConsoleOutput()); +$rectorStyle = new RectorStyleFactory()->create(); // core rules + all installed rector extensions (rector-doctrine, rector-symfony, rector-phpunit, ...) $ruleDirectories = array_merge( @@ -54,15 +52,15 @@ } if ($errorMessages !== []) { - $symfonyStyle->listing($errorMessages); - $symfonyStyle->error(sprintf('Found %d rule definition error(s), see above', count($errorMessages))); + $rectorStyle->listing($errorMessages); + $rectorStyle->error(sprintf('Found %d rule definition error(s), see above', count($errorMessages))); exit(ExitCode::FAILURE); } -$symfonyStyle->writeln('Scanned paths:'); -$symfonyStyle->listing(array_map(realpath(...), $ruleDirectories)); +$rectorStyle->writeln('Scanned paths:'); +$rectorStyle->listing(array_map(realpath(...), $ruleDirectories)); -$symfonyStyle->success(sprintf('All %d Rector rule definitions are valid!', count($rectorClasses))); +$rectorStyle->success(sprintf('All %d Rector rule definitions are valid!', count($rectorClasses))); exit(ExitCode::SUCCESS); diff --git a/src/Autoloading/AdditionalAutoloader.php b/src/Autoloading/AdditionalAutoloader.php index 699b9073497..eeceff8aa17 100644 --- a/src/Autoloading/AdditionalAutoloader.php +++ b/src/Autoloading/AdditionalAutoloader.php @@ -7,7 +7,6 @@ use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; use Rector\StaticReflection\DynamicSourceLocatorDecorator; -use Symfony\Component\Console\Input\InputInterface; use Webmozart\Assert\Assert; /** @@ -20,15 +19,14 @@ public function __construct( ) { } - public function autoloadInput(InputInterface $input): void + public function autoloadFile(): void { - if (! $input->hasOption(Option::AUTOLOAD_FILE)) { + if (! SimpleParameterProvider::hasParameter(Option::AUTOLOAD_FILE)) { return; } - /** @var string|null $autoloadFile */ - $autoloadFile = $input->getOption(Option::AUTOLOAD_FILE); - if ($autoloadFile === null) { + $autoloadFile = SimpleParameterProvider::provideStringParameter(Option::AUTOLOAD_FILE); + if ($autoloadFile === '') { return; } diff --git a/src/Bootstrap/RectorConfigsResolver.php b/src/Bootstrap/RectorConfigsResolver.php index 79f63ff109a..7216a6183b3 100644 --- a/src/Bootstrap/RectorConfigsResolver.php +++ b/src/Bootstrap/RectorConfigsResolver.php @@ -57,5 +57,4 @@ private function createFallbackFileInfoIfFound(string $fallbackFile): ?string return $rootFallbackFile; } - } diff --git a/src/ChangesReporting/Output/ConsoleOutputFormatter.php b/src/ChangesReporting/Output/ConsoleOutputFormatter.php index 796b7600cd7..16dc21996ad 100644 --- a/src/ChangesReporting/Output/ConsoleOutputFormatter.php +++ b/src/ChangesReporting/Output/ConsoleOutputFormatter.php @@ -13,7 +13,6 @@ use Rector\ValueObject\Error\SystemError; use Rector\ValueObject\ProcessResult; use Rector\ValueObject\Reporting\FileDiff; -use Symfony\Component\Console\Formatter\OutputFormatter; final readonly class ConsoleOutputFormatter implements OutputFormatterInterface { @@ -196,7 +195,8 @@ private function addEditorUrl( [(string) $absoluteFilePath, (string) $relativeFilePath, (string) $lineNumber], $editorUrl, ); - $filePath = '' . $filePath . ''; + // OSC-8 hyperlink keeps the path clickable without symfony/console's tag + $filePath = sprintf("\e]8;;%s\e\\%s\e]8;;\e\\", $editorUrl, $filePath); } return $filePath; diff --git a/src/Config/RectorConfig.php b/src/Config/RectorConfig.php index 4802bd9891e..5c356659000 100644 --- a/src/Config/RectorConfig.php +++ b/src/Config/RectorConfig.php @@ -5,6 +5,7 @@ namespace Rector\Config; use Composer\Semver\Semver; +use Entropy\Console\Contract\CommandInterface; use Entropy\Container\Container; use Rector\Composer\InstalledPackageResolver; use Rector\Configuration\Option; @@ -21,7 +22,6 @@ use Rector\ValueObject\PhpVersion; use Rector\ValueObject\PolyfillPackage; use Rector\VersionBonding\ValueObject\ComposerBoundRuleConfiguration; -use Symfony\Component\Console\Command\Command; use Webmozart\Assert\Assert; /** @@ -317,7 +317,7 @@ public function rule(string $rectorClass): void } /** - * @param class-string $commandClass + * @param class-string $commandClass */ public function command(string $commandClass): void { diff --git a/src/Configuration/ConfigurationFactory.php b/src/Configuration/ConfigurationFactory.php index 5242b7b1574..0af9b340b3d 100644 --- a/src/Configuration/ConfigurationFactory.php +++ b/src/Configuration/ConfigurationFactory.php @@ -10,7 +10,6 @@ use Rector\Console\Style\RectorStyle; use Rector\FileSystem\FilePathFilter; use Rector\ValueObject\Configuration; -use Symfony\Component\Console\Input\InputInterface; use Webmozart\Assert\Assert; /** @@ -51,38 +50,50 @@ public function createForTests(array $paths): Configuration /** * Needs to run in the start of the life cycle, since the rest of workflow uses it. + * + * @param string[] $commandLinePaths + * @param string[] $onlyRuleInputs */ - public function createFromInput(InputInterface $input): Configuration - { - $isDryRun = (bool) $input->getOption(Option::DRY_RUN); - $shouldClearCache = (bool) $input->getOption(Option::CLEAR_CACHE); - - $outputFormat = (string) $input->getOption(Option::OUTPUT_FORMAT); - $showProgressBar = $this->shouldShowProgressBar($input, $outputFormat); - - $showDiffs = $this->shouldShowDiffs($input); - - $paths = $this->resolvePaths($input); + public function create( + array $commandLinePaths, + bool $isDryRun, + bool $shouldClearCache, + bool $noProgressBar, + bool $noDiffs, + string $outputFormat, + array $onlyRuleInputs, + bool $isComposerBased, + bool $isPhpOnly, + ?string $onlySuffix, + ?string $rawFilter, + bool $isDebug, + ?string $memoryLimit, + string $parallelPort, + string $parallelIdentifier, + ?int $maxChanges, + bool $showRulesSummary, + ): Configuration { + $showProgressBar = $this->shouldShowProgressBar($noProgressBar, $outputFormat); + + $showDiffs = $this->shouldShowDiffs($noDiffs); + + $paths = $this->resolvePaths($commandLinePaths); $fileExtensions = SimpleParameterProvider::provideArrayParameter(Option::FILE_EXTENSIONS); // filter rule and path - /** @var string[] $onlyRuleInputs */ - $onlyRuleInputs = (array) $input->getOption(Option::ONLY); $onlyRules = array_map( $this->onlyRuleResolver->resolve(...), $onlyRuleInputs ); - $onlySuffix = $input->getOption(Option::ONLY_SUFFIX); if ($onlySuffix !== null) { $this->rectorStyle->warning( 'The "--only-suffix" option is deprecated and will be removed. Use "--filter" instead, e.g. --filter="*Controller.php"' ); } - $rawFilter = $input->getOption(Option::FILTER); - $filters = $rawFilter !== null ? $this->filePathFilter->parsePatterns((string) $rawFilter) : []; + $filters = $rawFilter !== null ? $this->filePathFilter->parsePatterns($rawFilter) : []; // "--only"/"--only-suffix"/"--filter" narrow the run, so skips outside the scope look falsely unused; // mark the run as narrowed to disable unused skip reporting and avoid false positives @@ -91,39 +102,30 @@ public function createFromInput(InputInterface $input): Configuration } $isParallel = SimpleParameterProvider::provideBoolParameter(Option::PARALLEL); - $parallelPort = (string) $input->getOption(Option::PARALLEL_PORT); - $parallelIdentifier = (string) $input->getOption(Option::PARALLEL_IDENTIFIER); - $isDebug = (bool) $input->getOption(Option::DEBUG); // using debug disables parallel, so emitting exception is straightforward and easier to debug if ($isDebug) { $isParallel = false; } - $maxChanges = $this->resolveMaxChanges($input); + $maxChanges = $this->resolveMaxChanges($maxChanges); // a global change counter cannot be shared across parallel workers, so enforce the limit in a single process if ($maxChanges !== null) { $isParallel = false; } - $memoryLimit = $this->resolveMemoryLimit($input); + $memoryLimit = $this->resolveMemoryLimit($memoryLimit); $isReportingWithRealPath = SimpleParameterProvider::provideBoolParameter(Option::ABSOLUTE_FILE_PATH); $levelOverflows = SimpleParameterProvider::provideArrayParameter(Option::LEVEL_OVERFLOWS); - $showRulesSummary = (bool) $input->getOption(Option::RULES_SUMMARY); - - $isComposerBased = (bool) $input->getOption(Option::COMPOSER_BASED); - // "--composer-based" narrows the run the same way "--only" does if ($isComposerBased) { SimpleParameterProvider::setParameter(Option::IS_RUN_NARROWED, true); } - $isPhpOnly = (bool) $input->getOption(Option::PHP); - // "--php" narrows the run the same way "--only" does if ($isPhpOnly) { SimpleParameterProvider::setParameter(Option::IS_RUN_NARROWED, true); @@ -154,22 +156,19 @@ public function createFromInput(InputInterface $input): Configuration ); } - private function resolveMaxChanges(InputInterface $input): ?int + private function resolveMaxChanges(?int $maxChanges): ?int { - $maxChanges = $input->getOption(Option::MAX_CHANGES); if ($maxChanges === null) { return null; } - $maxChanges = (int) $maxChanges; Assert::positiveInteger($maxChanges); return $maxChanges; } - private function shouldShowProgressBar(InputInterface $input, string $outputFormat): bool + private function shouldShowProgressBar(bool $noProgressBar, string $outputFormat): bool { - $noProgressBar = (bool) $input->getOption(Option::NO_PROGRESS_BAR); if ($noProgressBar) { return false; } @@ -186,9 +185,8 @@ private function shouldShowProgressBar(InputInterface $input, string $outputForm return $outputFormat === ConsoleOutputFormatter::NAME; } - private function shouldShowDiffs(InputInterface $input): bool + private function shouldShowDiffs(bool $noDiffs): bool { - $noDiffs = (bool) $input->getOption(Option::NO_DIFFS); if ($noDiffs) { return false; } @@ -198,12 +196,11 @@ private function shouldShowDiffs(InputInterface $input): bool } /** + * @param string[] $commandLinePaths * @return string[]|mixed[] */ - private function resolvePaths(InputInterface $input): array + private function resolvePaths(array $commandLinePaths): array { - $commandLinePaths = (array) $input->getArgument(Option::SOURCE); - // give priority to command line if ($commandLinePaths !== []) { // mark the run as narrowed, so unused skip reporting can be disabled to avoid false positives @@ -241,11 +238,10 @@ private function setFilesWithoutExtensionParameter(array $paths): void } } - private function resolveMemoryLimit(InputInterface $input): string|null + private function resolveMemoryLimit(?string $memoryLimit): string|null { - $memoryLimit = $input->getOption(Option::MEMORY_LIMIT); if ($memoryLimit !== null) { - return (string) $memoryLimit; + return $memoryLimit; } if (! SimpleParameterProvider::hasParameter(Option::MEMORY_LIMIT)) { diff --git a/src/Configuration/Option.php b/src/Configuration/Option.php index 65b8e438eb3..fb2eba3abcf 100644 --- a/src/Configuration/Option.php +++ b/src/Configuration/Option.php @@ -17,12 +17,8 @@ final class Option public const string DRY_RUN = 'dry-run'; - public const string DRY_RUN_SHORT = 'n'; - public const string OUTPUT_FORMAT = 'output-format'; - public const string NO_PROGRESS_BAR = 'no-progress-bar'; - /** * @internal Use @see \Rector\Config\RectorConfig::phpVersion() instead */ @@ -128,14 +124,6 @@ final class Option */ public const string CACHE_DIR = 'cache_dir'; - public const string DEBUG = 'debug'; - - public const string XDEBUG = 'xdebug'; - - public const string RULES_SUMMARY = 'rules-summary'; - - public const string MAX_CHANGES = 'max-changes'; - public const string CONFIG = 'config'; /** @@ -145,7 +133,13 @@ final class Option public const string NO_DIFFS = 'no-diffs'; - public const string AUTOLOAD_FILE_SHORT = 'a'; + public const string DEBUG = 'debug'; + + public const string XDEBUG = 'xdebug'; + + public const string MAX_CHANGES = 'max-changes'; + + public const string FILTER = 'filter'; public const string PARALLEL_IDENTIFIER = 'identifier'; @@ -276,11 +270,6 @@ final class Option */ public const string ONLY_SUFFIX = 'only-suffix'; - /** - * @internal To keep only files matching all given patterns - */ - public const string FILTER = 'filter'; - /** * @internal To report overflow levels in ->with*Level() methods */ diff --git a/src/Console/Command/ComposerBasedCommand.php b/src/Console/Command/ComposerBasedCommand.php index 9146ecce656..14d7b02ff34 100644 --- a/src/Console/Command/ComposerBasedCommand.php +++ b/src/Console/Command/ComposerBasedCommand.php @@ -5,44 +5,49 @@ namespace Rector\Console\Command; use Composer\Semver\Semver; +use Entropy\Console\Contract\CommandInterface; use Nette\Utils\Strings; use Rector\Composer\InstalledPackageResolver; use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; +use Rector\Console\ExitCode; use Rector\Console\Style\RectorStyle; use Rector\Contract\Rector\RectorInterface; use Rector\VersionBonding\Contract\ComposerPackageConstraintInterface; use Rector\VersionBonding\ValueObject\ComposerBoundRuleConfiguration; use ReflectionObject; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Helper\TableCell; -use Symfony\Component\Console\Helper\TableSeparator; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; /** * @see \Rector\Tests\Console\Command\ComposerBasedCommandTest */ -final class ComposerBasedCommand extends Command +final readonly class ComposerBasedCommand implements CommandInterface { /** * @param RectorInterface[] $rectors */ public function __construct( - private readonly RectorStyle $rectorStyle, - private readonly InstalledPackageResolver $installedPackageResolver, - private readonly array $rectors + private RectorStyle $rectorStyle, + private InstalledPackageResolver $installedPackageResolver, + private array $rectors ) { - parent::__construct(); } - protected function configure(): void + public function getName(): string { - $this->setName('composer-based'); - $this->setDescription('Show loaded rules that are triggered by an installed composer package version'); + return 'composer-based'; } - protected function execute(InputInterface $input, OutputInterface $output): int + public function getDescription(): string + { + return 'Show loaded rules that are triggered by an installed composer package version'; + } + + /** + * @api invoked via reflection by the Entropy console application + * + * @return ExitCode::* + */ + public function run(): int { $tableRows = $this->createTableRows(); $configurationTableRows = $this->createConfigurationTableRows(); @@ -50,7 +55,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($tableRows === [] && $configurationTableRows === []) { $this->rectorStyle->warning('No composer package bound rule is loaded'); - return Command::SUCCESS; + return ExitCode::SUCCESS; } if ($tableRows !== []) { @@ -60,24 +65,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($configurationTableRows !== []) { $this->rectorStyle->title('Composer package bound rule configuration'); - - $headers = ['Rule', 'Package', 'Requires', 'Installed', 'Active']; - - $table = $this->rectorStyle->createTable(); - $table->setHeaders($headers); - $table->setRows($this->createConfigurationDisplayRows($configurationTableRows)); - - // keep columns as narrow as their content, so the full-width configuration line does not stretch them - foreach ($headers as $columnPosition => $header) { - $columnWidth = max(array_map( - static fn (array $configurationTableRow): int => strlen($configurationTableRow[$columnPosition]), - $configurationTableRows - )); - - $table->setColumnMaxWidth($columnPosition, max($columnWidth, strlen($header))); - } - - $table->render(); + $this->rectorStyle->table( + ['Rule', 'Package', 'Requires', 'Installed', 'Active', 'Configuration'], + $configurationTableRows + ); } $allTableRows = [...$tableRows, ...$configurationTableRows]; @@ -87,7 +78,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int sprintf('%d of %d composer package bound items are active', $activeCount, count($allTableRows)) ); - return Command::SUCCESS; + return ExitCode::SUCCESS; } /** @@ -165,30 +156,6 @@ private function createConfigurationTableRows(): array return $tableRows; } - /** - * The configuration is printed on a separated full-width line, to avoid breaking the table layout - * - * @param array $configurationTableRows - * @return array|TableSeparator> - */ - private function createConfigurationDisplayRows(array $configurationTableRows): array - { - $displayRows = []; - - foreach ($configurationTableRows as $configurationTableRow) { - if ($displayRows !== []) { - $displayRows[] = new TableSeparator(); - } - - $displayRows[] = array_slice($configurationTableRow, 0, 5); - $displayRows[] = [new TableCell($configurationTableRow[5], [ - 'colspan' => 5, - ])]; - } - - return $displayRows; - } - /** * @param mixed[] $configuration */ diff --git a/src/Console/Command/ListRulesCommand.php b/src/Console/Command/ListRulesCommand.php index 05eddd3ed42..cc3318275ef 100644 --- a/src/Console/Command/ListRulesCommand.php +++ b/src/Console/Command/ListRulesCommand.php @@ -4,67 +4,57 @@ namespace Rector\Console\Command; +use Entropy\Console\Contract\CommandInterface; use Nette\Utils\Json; use Rector\ChangesReporting\Output\ConsoleOutputFormatter; -use Rector\Configuration\Option; +use Rector\Console\ExitCode; use Rector\Console\Rule\AllRectorRulesProvider; use Rector\Console\Style\RectorStyle; use Rector\Contract\Rector\RectorInterface; use Rector\PostRector\Contract\Rector\PostRectorInterface; use Rector\Skipper\Skipper\Skipper; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Output\OutputInterface; -final class ListRulesCommand extends Command +final readonly class ListRulesCommand implements CommandInterface { /** * @param RectorInterface[] $rectors */ public function __construct( - private readonly RectorStyle $rectorStyle, - private readonly Skipper $skipper, - private readonly AllRectorRulesProvider $allRectorRulesProvider, - private readonly array $rectors + private RectorStyle $rectorStyle, + private Skipper $skipper, + private AllRectorRulesProvider $allRectorRulesProvider, + private array $rectors ) { - parent::__construct(); } - protected function configure(): void + public function getName(): string { - $this->setName('list-rules'); - $this->setDescription('Show loaded Rectors'); - - $this->setAliases(['show-rules']); - - $this->addOption( - Option::OUTPUT_FORMAT, - null, - InputOption::VALUE_REQUIRED, - 'Select output format', - ConsoleOutputFormatter::NAME - ); - - $this->addOption(Option::ONLY, null, InputOption::VALUE_REQUIRED, 'Fully qualified rule class name'); + return 'list-rules'; + } - $this->addOption( - 'all', - null, - InputOption::VALUE_NONE, - 'List all existing rules in core and rector-* packages, not only the loaded ones' - ); + public function getDescription(): string + { + return 'Show loaded Rectors'; } - protected function execute(InputInterface $input, OutputInterface $output): int + /** + * @param bool $all List all existing rules in core and rector-* packages, not only the loaded ones + * @param string $outputFormat Select output format + * + * @option $outputFormat + * + * @api invoked via reflection by the Entropy console application + * + * @return ExitCode::* + */ + public function run(bool $all = false, string $outputFormat = ConsoleOutputFormatter::NAME): int { - $rectorClasses = $input->getOption('all') + $rectorClasses = $all ? $this->allRectorRulesProvider->provide() : $this->resolveRectorClasses(); $skippedClasses = $this->getSkippedRectorClasses(); - $outputFormat = $input->getOption(Option::OUTPUT_FORMAT); if ($outputFormat === 'json') { $data = [ 'rectors' => $rectorClasses, @@ -72,7 +62,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int ]; echo Json::encode($data, pretty: true) . PHP_EOL; - return Command::SUCCESS; + return ExitCode::SUCCESS; } $this->rectorStyle->title('Loaded Rector rules'); @@ -86,7 +76,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->rectorStyle->newLine(); $this->rectorStyle->note(sprintf('Loaded %d rules', count($rectorClasses))); - return Command::SUCCESS; + return ExitCode::SUCCESS; } /** diff --git a/src/Console/Command/ProcessCommand.php b/src/Console/Command/ProcessCommand.php index 8d628bdf3ad..0efd86c2dfb 100644 --- a/src/Console/Command/ProcessCommand.php +++ b/src/Console/Command/ProcessCommand.php @@ -4,19 +4,19 @@ namespace Rector\Console\Command; +use Entropy\Console\Contract\CommandInterface; +use Entropy\Console\Contract\DefaultCommandInterface; use Rector\Application\ApplicationFileProcessor; use Rector\Autoloading\AdditionalAutoloader; use Rector\Caching\Detector\ChangedFilesDetector; +use Rector\ChangesReporting\Output\ConsoleOutputFormatter; use Rector\ChangesReporting\Output\JsonOutputFormatter; use Rector\Configuration\ConfigInitializer; use Rector\Configuration\ConfigurationFactory; use Rector\Configuration\ConfigurationRuleFilter; -use Rector\Configuration\Option; use Rector\Console\ExitCode; use Rector\Console\Output\OutputFormatterCollector; -use Rector\Console\ProcessConfigureDecorator; use Rector\Console\Style\RectorStyle; -use Rector\Exception\ShouldNotHappenException; use Rector\Reporting\DeprecatedRulesReporter; use Rector\Reporting\MissConfigurationReporter; use Rector\Skipper\Skipper\Skipper; @@ -25,77 +25,123 @@ use Rector\ValueObject\Configuration; use Rector\ValueObject\Configuration\LevelOverflow; use Rector\ValueObject\ProcessResult; -use Symfony\Component\Console\Application; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -final class ProcessCommand extends Command +final readonly class ProcessCommand implements CommandInterface, DefaultCommandInterface { public function __construct( - private readonly AdditionalAutoloader $additionalAutoloader, - private readonly ChangedFilesDetector $changedFilesDetector, - private readonly ConfigInitializer $configInitializer, - private readonly ApplicationFileProcessor $applicationFileProcessor, - private readonly DynamicSourceLocatorDecorator $dynamicSourceLocatorDecorator, - private readonly OutputFormatterCollector $outputFormatterCollector, - private readonly RectorStyle $rectorStyle, - private readonly MemoryLimiter $memoryLimiter, - private readonly ConfigurationFactory $configurationFactory, - private readonly DeprecatedRulesReporter $deprecatedRulesReporter, - private readonly MissConfigurationReporter $missConfigurationReporter, - private readonly ConfigurationRuleFilter $configurationRuleFilter, - private readonly Skipper $skipper, + private AdditionalAutoloader $additionalAutoloader, + private ChangedFilesDetector $changedFilesDetector, + private ConfigInitializer $configInitializer, + private ApplicationFileProcessor $applicationFileProcessor, + private DynamicSourceLocatorDecorator $dynamicSourceLocatorDecorator, + private OutputFormatterCollector $outputFormatterCollector, + private RectorStyle $rectorStyle, + private MemoryLimiter $memoryLimiter, + private ConfigurationFactory $configurationFactory, + private DeprecatedRulesReporter $deprecatedRulesReporter, + private MissConfigurationReporter $missConfigurationReporter, + private ConfigurationRuleFilter $configurationRuleFilter, + private Skipper $skipper, ) { - parent::__construct(); } - protected function configure(): void + public function getName(): string { - $this->setName('process'); - $this->setAliases(['p']); - $this->setDescription('Upgrades or refactors source code with provided Rector rules'); - $this->setHelp( - <<<'EOF' -The %command.name% command will run Rector main feature: - - vendor/bin/rector - -To specify a folder or a file, you can run: - - vendor/bin/rector src/Controller - -You can also dry run to see the changes that Rector will make with the --dry-run option: - - vendor/bin/rector src/Controller --dry-run - -It's also possible to get debug via the --debug option: - - vendor/bin/rector src/Controller --dry-run --debug -EOF - ); - - ProcessConfigureDecorator::decorate($this); - - parent::configure(); + return 'process'; } - protected function execute(InputInterface $input, OutputInterface $output): int + public function getDescription(): string { + return 'Upgrades or refactors source code with provided Rector rules'; + } + + /** + * @param string[] $only Fully qualified rule class name; repeat to run several rules + * @param string $config Path to config file + * @param string $autoloadFile Path to file with extra autoload (will be included) + * @param string $outputFormat Select output format + * @param string $onlySuffix Deprecated, use "--filter" instead + * @param string $filter Keep only files matching all comma-separated patterns + * @param string $memoryLimit Memory limit for process + * @param string $maxChanges Stop after this many changes are made + * @param string $port [INTERNAL] parallel TCP port + * @param string $identifier [INTERNAL] parallel identifier + * @param string ...$paths Files or directories to be upgraded + * + * @option $dryRun -n + * @option $only + * @option $config -c + * @option $autoloadFile -a + * @option $outputFormat + * @option $onlySuffix + * @option $filter + * @option $memoryLimit + * @option $maxChanges + * @option $port + * @option $identifier + * + * @api invoked via reflection by the Entropy console application + * + * @return ExitCode::* + */ + public function run( + bool $dryRun = false, + bool $clearCache = false, + bool $noProgressBar = false, + bool $noDiffs = false, + bool $debug = false, + bool $composerBased = false, + bool $php = false, + bool $rulesSummary = false, + array $only = [], + string $config = '', + string $autoloadFile = '', + string $outputFormat = ConsoleOutputFormatter::NAME, + string $onlySuffix = '', + string $filter = '', + string $memoryLimit = '', + string $maxChanges = '', + string $port = '', + string $identifier = '', + string ...$paths, + ): int { // missing config? add it :) if (! $this->configInitializer->areSomeRectorsLoaded()) { - $this->configInitializer->createConfig(getcwd()); - return self::SUCCESS; + $this->configInitializer->createConfig((string) getcwd()); + return ExitCode::SUCCESS; } - $configuration = $this->configurationFactory->createFromInput($input); + $configuration = $this->configurationFactory->create( + array_values($paths), + $dryRun, + $clearCache, + $noProgressBar, + $noDiffs, + $outputFormat, + $only, + $composerBased, + $php, + $onlySuffix !== '' ? $onlySuffix : null, + $filter !== '' ? $filter : null, + $debug, + $memoryLimit !== '' ? $memoryLimit : null, + $port, + $identifier, + $maxChanges !== '' ? (int) $maxChanges : null, + $rulesSummary, + ); + + // clear cache in debug run, so nothing is skipped and errors show up clearly + if ($debug) { + $this->changedFilesDetector->clear(); + } $this->memoryLimiter->adjust($configuration); $this->configurationRuleFilter->setConfiguration($configuration); // disable console output in case of json output formatter if ($configuration->getOutputFormat() === JsonOutputFormatter::NAME) { - $this->rectorStyle->setVerbosity(OutputInterface::VERBOSITY_QUIET); + $this->rectorStyle->setVerbosity(RectorStyle::VERBOSITY_QUIET); } // "--rules-summary" is a human-only table; the JSON format carries richer per-rule data @@ -106,7 +152,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int ); } - $this->additionalAutoloader->autoloadInput($input); + $this->additionalAutoloader->autoloadFile(); $paths = $configuration->getPaths(); @@ -199,21 +245,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int return $this->resolveReturnCode($processResult, $configuration); } - protected function initialize(InputInterface $input, OutputInterface $output): void - { - $application = $this->getApplication(); - if (! $application instanceof Application) { - throw new ShouldNotHappenException(); - } - - $optionDebug = (bool) $input->getOption(Option::DEBUG); - // clear cache - if ($optionDebug) { - $application->setCatchExceptions(false); - $this->changedFilesDetector->clear(); - } - } - /** * @return ExitCode::* */ diff --git a/src/Console/Command/ValidateConfigCommand.php b/src/Console/Command/ValidateConfigCommand.php index 3c2f953e911..87bf30a7fa3 100644 --- a/src/Console/Command/ValidateConfigCommand.php +++ b/src/Console/Command/ValidateConfigCommand.php @@ -4,55 +4,56 @@ namespace Rector\Console\Command; +use Entropy\Console\Contract\CommandInterface; use Nette\Utils\Json; use Rector\ChangesReporting\Output\ConsoleOutputFormatter; use Rector\ChangesReporting\Output\JsonOutputFormatter; -use Rector\Configuration\Option; use Rector\Console\ExitCode; use Rector\Console\Style\RectorStyle; use Rector\Reporting\DeprecatedRulesReporter; use Rector\Reporting\MissConfigurationReporter; use Rector\Skipper\Skipper\Skipper; use Rector\ValueObject\Configuration; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Output\OutputInterface; /** * @see \Rector\Tests\Console\Command\ValidateConfigCommandTest */ -final class ValidateConfigCommand extends Command +final readonly class ValidateConfigCommand implements CommandInterface { public function __construct( - private readonly RectorStyle $rectorStyle, - private readonly DeprecatedRulesReporter $deprecatedRulesReporter, - private readonly MissConfigurationReporter $missConfigurationReporter, - private readonly Skipper $skipper, + private RectorStyle $rectorStyle, + private DeprecatedRulesReporter $deprecatedRulesReporter, + private MissConfigurationReporter $missConfigurationReporter, + private Skipper $skipper, ) { - parent::__construct(); } - protected function configure(): void + public function getName(): string { - $this->setName('validate-config'); - $this->setDescription('Report config hygiene issues without processing any files'); - $this->addOption( - Option::OUTPUT_FORMAT, - null, - InputOption::VALUE_REQUIRED, - sprintf('Output format: "%s" or "%s"', ConsoleOutputFormatter::NAME, JsonOutputFormatter::NAME), - ConsoleOutputFormatter::NAME - ); + return 'validate-config'; } - protected function execute(InputInterface $input, OutputInterface $output): int + public function getDescription(): string { - $isJsonOutput = $input->getOption(Option::OUTPUT_FORMAT) === JsonOutputFormatter::NAME; + return 'Report config hygiene issues without processing any files'; + } + + /** + * @param string $outputFormat Output format: "console" or "json" + * + * @option $outputFormat + * + * @api invoked via reflection by the Entropy console application + * + * @return ExitCode::* + */ + public function run(string $outputFormat = ConsoleOutputFormatter::NAME): int + { + $isJsonOutput = $outputFormat === JsonOutputFormatter::NAME; // silence the human-readable warnings, so only the JSON payload lands on stdout if ($isJsonOutput) { - $this->rectorStyle->setVerbosity(OutputInterface::VERBOSITY_QUIET); + $this->rectorStyle->setVerbosity(RectorStyle::VERBOSITY_QUIET); } $issueCount = 0; diff --git a/src/Console/Command/WorkerCommand.php b/src/Console/Command/WorkerCommand.php index cf5cf822fea..6a00bc06ef8 100644 --- a/src/Console/Command/WorkerCommand.php +++ b/src/Console/Command/WorkerCommand.php @@ -6,15 +6,18 @@ use Clue\React\NDJson\Decoder; use Clue\React\NDJson\Encoder; +use Entropy\Console\Contract\CommandInterface; +use Entropy\Console\Contract\HiddenCommandInterface; use React\EventLoop\StreamSelectLoop; use React\Socket\ConnectionInterface; use React\Socket\TcpConnector; use Rector\Application\ApplicationFileProcessor; use Rector\Autoloading\AdditionalAutoloader; +use Rector\ChangesReporting\Output\ConsoleOutputFormatter; +use Rector\ChangesReporting\Output\JsonOutputFormatter; use Rector\Configuration\ConfigurationFactory; use Rector\Configuration\ConfigurationRuleFilter; -use Rector\Configuration\Option; -use Rector\Console\ProcessConfigureDecorator; +use Rector\Console\ExitCode; use Rector\Parallel\Enum\Action; use Rector\Parallel\Enum\ReactCommand; use Rector\Parallel\Enum\ReactEvent; @@ -24,9 +27,6 @@ use Rector\Util\MemoryLimiter; use Rector\ValueObject\Configuration; use Rector\ValueObject\Error\SystemError; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; use Throwable; use Webmozart\Assert\Assert; @@ -37,34 +37,100 @@ * ↓↓↓ * https://github.com/phpstan/phpstan-src/commit/b84acd2e3eadf66189a64fdbc6dd18ff76323f67#diff-7f625777f1ce5384046df08abffd6c911cfbb1cfc8fcb2bdeaf78f337689e3e2 */ -final class WorkerCommand extends Command +final readonly class WorkerCommand implements CommandInterface, HiddenCommandInterface { private const string RESULT = 'result'; public function __construct( - private readonly AdditionalAutoloader $additionalAutoloader, - private readonly DynamicSourceLocatorDecorator $dynamicSourceLocatorDecorator, - private readonly ApplicationFileProcessor $applicationFileProcessor, - private readonly MemoryLimiter $memoryLimiter, - private readonly ConfigurationFactory $configurationFactory, - private readonly ConfigurationRuleFilter $configurationRuleFilter, + private AdditionalAutoloader $additionalAutoloader, + private DynamicSourceLocatorDecorator $dynamicSourceLocatorDecorator, + private ApplicationFileProcessor $applicationFileProcessor, + private MemoryLimiter $memoryLimiter, + private ConfigurationFactory $configurationFactory, + private ConfigurationRuleFilter $configurationRuleFilter, ) { - parent::__construct(); } - protected function configure(): void + public function getName(): string { - $this->setName('worker'); - $this->setDescription('[INTERNAL] Support for parallel process'); - - ProcessConfigureDecorator::decorate($this); - - parent::configure(); + return 'worker'; } - protected function execute(InputInterface $input, OutputInterface $output): int + public function getDescription(): string { - $configuration = $this->configurationFactory->createFromInput($input); + return '[INTERNAL] Support for parallel process'; + } + + /** + * @param string[] $only Fully qualified rule class name; repeat to run several rules + * @param string $config Path to config file + * @param string $autoloadFile Path to file with extra autoload (will be included) + * @param string $outputFormat Select output format + * @param string $onlySuffix Deprecated, use "--filter" instead + * @param string $filter Keep only files matching all comma-separated patterns + * @param string $memoryLimit Memory limit for process + * @param string $maxChanges Stop after this many changes are made + * @param string $port [INTERNAL] parallel TCP port + * @param string $identifier [INTERNAL] parallel identifier + * @param string ...$paths Files or directories to be upgraded + * + * @option $dryRun -n + * @option $only + * @option $config -c + * @option $autoloadFile -a + * @option $outputFormat + * @option $onlySuffix + * @option $filter + * @option $memoryLimit + * @option $maxChanges + * @option $port + * @option $identifier + * + * @api invoked via reflection by the Entropy console application + * + * @return ExitCode::* + */ + public function run( + bool $dryRun = false, + bool $clearCache = false, + bool $noProgressBar = false, + bool $noDiffs = false, + bool $debug = false, + bool $composerBased = false, + bool $php = false, + bool $rulesSummary = false, + array $only = [], + string $config = '', + string $autoloadFile = '', + string $outputFormat = ConsoleOutputFormatter::NAME, + string $onlySuffix = '', + string $filter = '', + string $memoryLimit = '', + string $maxChanges = '', + string $port = '', + string $identifier = '', + string ...$paths, + ): int { + $configuration = $this->configurationFactory->create( + array_values($paths), + $dryRun, + $clearCache, + $noProgressBar, + $noDiffs, + $outputFormat, + $only, + $composerBased, + $php, + $onlySuffix !== '' ? $onlySuffix : null, + $filter !== '' ? $filter : null, + $debug, + $memoryLimit !== '' ? $memoryLimit : null, + $port, + $identifier, + $maxChanges !== '' ? (int) $maxChanges : null, + $rulesSummary, + ); + $this->memoryLimiter->adjust($configuration); $this->configurationRuleFilter->setConfiguration($configuration); @@ -76,9 +142,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $promise = $tcpConnector->connect('127.0.0.1:' . $configuration->getParallelPort()); $promise->then(function (ConnectionInterface $connection) use ( $parallelIdentifier, - $configuration, - $input, - $output + $configuration ): void { $inDecoder = new Decoder($connection, true, StreamFormat::DEPTH, JSON_INVALID_UTF8_IGNORE, StreamFormat::MAX_LENGTH); $outEncoder = new Encoder($connection, JSON_INVALID_UTF8_IGNORE); @@ -88,27 +152,27 @@ protected function execute(InputInterface $input, OutputInterface $output): int ReactCommand::IDENTIFIER => $parallelIdentifier, ]); - $this->runWorker($outEncoder, $inDecoder, $configuration, $input, $output); + $this->runWorker($outEncoder, $inDecoder, $configuration); }); $streamSelectLoop->run(); - return self::SUCCESS; + return ExitCode::SUCCESS; } private function runWorker( Encoder $encoder, Decoder $decoder, - Configuration $configuration, - InputInterface $input, - OutputInterface $output + Configuration $configuration ): void { + $this->additionalAutoloader->autoloadFile(); $this->additionalAutoloader->autoloadPaths(); + $this->dynamicSourceLocatorDecorator->addPaths($configuration->getPaths()); if ($configuration->isDebug()) { - $preFileCallback = static function (string $filePath) use ($output): void { - $output->writeln($filePath); + $preFileCallback = static function (string $filePath): void { + echo $filePath . PHP_EOL; }; } else { $preFileCallback = null; @@ -135,8 +199,7 @@ private function runWorker( $decoder->on(ReactEvent::DATA, function (array $json) use ( $preFileCallback, $encoder, - $configuration, - $input + $configuration ): void { $action = $json[ReactCommand::ACTION]; if ($action !== Action::MAIN) { @@ -161,7 +224,7 @@ private function runWorker( ReactCommand::ACTION => Action::RESULT, self::RESULT => [ Bridge::FILE_DIFFS => $processResult->getFileDiffs( - $input->getOption(Option::OUTPUT_FORMAT) !== 'json' + $configuration->getOutputFormat() !== JsonOutputFormatter::NAME ), Bridge::FILES_COUNT => count($filePaths), Bridge::SYSTEM_ERRORS => $processResult->getSystemErrors(), diff --git a/src/Console/ConsoleApplication.php b/src/Console/ConsoleApplication.php deleted file mode 100644 index 1d09cec2277..00000000000 --- a/src/Console/ConsoleApplication.php +++ /dev/null @@ -1,165 +0,0 @@ -addCommands($commands); - - // run this command, if no command name is provided - $this->setDefaultCommand('process'); - } - - public function doRun(InputInterface $input, OutputInterface $output): int - { - // support "-v" as an alias for "--version", as "verbose" option is removed - if ($input->hasParameterOption('-v', true)) { - $output->writeln($this->getLongVersion()); - - return ExitCode::SUCCESS; - } - - $shouldFollowByNewline = false; - - // skip in this case, since generate content must be clear from meta-info - if ($this->shouldPrintMetaInformation($input)) { - $output->writeln($this->getLongVersion()); - $shouldFollowByNewline = true; - } - - if ($shouldFollowByNewline) { - $output->write(PHP_EOL); - } - - $commandName = $input->getFirstArgument(); - - if ($commandName === null) { - return parent::doRun($input, $output); - } - - // if paths exist or if the command name is not the first argument but with --option, eg: - // bin/rector src - // bin/rector --only "RemovePhpVersionIdCheckRector" - // file_exists() can check directory and file - if (( - file_exists($commandName) || isset($_SERVER['argv'][1]) - && $commandName !== $_SERVER['argv'][1] - // ensure verify has parameter option, eg: --only - && $input->hasParameterOption($_SERVER['argv'][1]) - ) - ) { - // prepend command name if implicit - $privatesAccessor = new PrivatesAccessor(); - $tokens = $privatesAccessor->getPrivateProperty($input, 'tokens'); - $tokens = array_merge(['process'], $tokens); - $privatesAccessor->setPrivateProperty($input, 'tokens', $tokens); - } elseif (! $this->has($commandName)) { - $this->rectorStyle->error( - sprintf( - 'The following given path does not match any files or directories: %s%s', - "\n\n - ", - $commandName - ) - ); - - return ExitCode::FAILURE; - } - - return parent::doRun($input, $output); - } - - protected function getDefaultInputDefinition(): InputDefinition - { - $defaultInputDefinition = parent::getDefaultInputDefinition(); - - $this->removeUnusedOptions($defaultInputDefinition); - $this->addCustomOptions($defaultInputDefinition); - - return $defaultInputDefinition; - } - - private function shouldPrintMetaInformation(InputInterface $input): bool - { - $hasNoArguments = $input->getFirstArgument() === null; - if ($hasNoArguments) { - return false; - } - - $hasVersionOption = $input->hasParameterOption('--version'); - if ($hasVersionOption) { - return false; - } - - $outputFormat = $input->getParameterOption(['-o', '--output-format']); - return $outputFormat === ConsoleOutputFormatter::NAME; - } - - private function removeUnusedOptions(InputDefinition $inputDefinition): void - { - $options = $inputDefinition->getOptions(); - - unset($options['quiet'], $options['verbose'], $options['no-interaction']); - - $inputDefinition->setOptions($options); - } - - private function addCustomOptions(InputDefinition $inputDefinition): void - { - $inputDefinition->addOption(new InputOption( - Option::CONFIG, - 'c', - InputOption::VALUE_REQUIRED, - 'Path to config file' - )); - - $inputDefinition->addOption(new InputOption( - Option::DEBUG, - null, - InputOption::VALUE_NONE, - 'Enable debug verbosity' - )); - - $inputDefinition->addOption(new InputOption( - Option::XDEBUG, - null, - InputOption::VALUE_NONE, - 'Allow running xdebug' - )); - - $inputDefinition->addOption(new InputOption( - Option::CLEAR_CACHE, - null, - InputOption::VALUE_NONE, - 'Clear cache before starting the execution of the command' - )); - } -} diff --git a/src/Console/Formatter/ColorConsoleDiffFormatter.php b/src/Console/Formatter/ColorConsoleDiffFormatter.php index 62788ea19dd..5e50967e524 100644 --- a/src/Console/Formatter/ColorConsoleDiffFormatter.php +++ b/src/Console/Formatter/ColorConsoleDiffFormatter.php @@ -6,7 +6,6 @@ use Nette\Utils\Strings; use Rector\Util\NewLineSplitter; -use Symfony\Component\Console\Formatter\OutputFormatter; /** * Inspired by @see https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/master/src/Differ/DiffConsoleFormatter.php to be @@ -54,9 +53,7 @@ public function format(string $diff): string private function formatWithTemplate(string $diff, string $template): string { - $escapedDiff = OutputFormatter::escape(rtrim($diff)); - - $escapedDiffLines = NewLineSplitter::split($escapedDiff); + $escapedDiffLines = NewLineSplitter::split(rtrim($diff)); // remove description of added + remove, obvious on diffs // decorize lines diff --git a/src/Console/Notifier.php b/src/Console/Notifier.php index 347c3505f17..b6b55408365 100644 --- a/src/Console/Notifier.php +++ b/src/Console/Notifier.php @@ -4,10 +4,8 @@ namespace Rector\Console; +use Rector\Console\Style\RectorStyleFactory; use Rector\Exception\Configuration\InvalidConfigurationException; -use Symfony\Component\Console\Input\ArgvInput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Style\SymfonyStyle; final class Notifier { @@ -22,8 +20,8 @@ public static function notifyNotSuitableMethodForPHP74(string $calledMethod): vo $calledMethod ); - $symfonyStyle = new SymfonyStyle(new ArgvInput(), new ConsoleOutput()); - $symfonyStyle->warning($message); + $rectorStyle = new RectorStyleFactory()->create(); + $rectorStyle->warning($message); sleep(3); } @@ -36,8 +34,8 @@ public static function notifyDeprecatedPhpSet(string $set): void $set ); - $symfonyStyle = new SymfonyStyle(new ArgvInput(), new ConsoleOutput()); - $symfonyStyle->warning($message); + $rectorStyle = new RectorStyleFactory()->create(); + $rectorStyle->warning($message); } public static function notifyDeprecatedNamingSet(): void @@ -45,8 +43,8 @@ public static function notifyDeprecatedNamingSet(): void $message = 'The "naming" prepared set is deprecated, as it often causes conflicting variable and param names and removes context. ' . 'Renaming to match types belongs to a coding standard tool rather than Rector.'; - $symfonyStyle = new SymfonyStyle(new ArgvInput(), new ConsoleOutput()); - $symfonyStyle->warning($message); + $rectorStyle = new RectorStyleFactory()->create(); + $rectorStyle->warning($message); } public static function errorWithPhpSetsNotSuitableForPHP74AndLower(): void diff --git a/src/Console/ProcessConfigureDecorator.php b/src/Console/ProcessConfigureDecorator.php deleted file mode 100644 index 800168aba89..00000000000 --- a/src/Console/ProcessConfigureDecorator.php +++ /dev/null @@ -1,118 +0,0 @@ -addArgument( - Option::SOURCE, - InputArgument::OPTIONAL | InputArgument::IS_ARRAY, - 'Files or directories to be upgraded.' - ); - - $command->addOption( - Option::DRY_RUN, - Option::DRY_RUN_SHORT, - InputOption::VALUE_NONE, - 'Only see the diff of changes, do not save them to files.' - ); - - $command->addOption( - Option::AUTOLOAD_FILE, - Option::AUTOLOAD_FILE_SHORT, - InputOption::VALUE_REQUIRED, - 'Path to file with extra autoload (will be included)' - ); - - $command->addOption( - Option::NO_PROGRESS_BAR, - null, - InputOption::VALUE_NONE, - 'Hide progress bar. Useful e.g. for nicer CI output.' - ); - - $command->addOption( - Option::NO_DIFFS, - null, - InputOption::VALUE_NONE, - 'Hide diffs of changed files. Useful e.g. for nicer CI output.' - ); - - $command->addOption( - Option::OUTPUT_FORMAT, - null, - InputOption::VALUE_REQUIRED, - 'Select output format', - ConsoleOutputFormatter::NAME - ); - - // filter by rule and path - $command->addOption( - Option::ONLY, - null, - InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, - 'Fully qualified rule class name; repeat to run several rules, e.g. --only=A --only=B' - ); - - $command->addOption( - Option::COMPOSER_BASED, - null, - InputOption::VALUE_NONE, - 'Run only rules bound to an installed composer package version' - ); - - $command->addOption( - Option::PHP, - null, - InputOption::VALUE_NONE, - 'Run only PHP rules, e.g. rules bound to a minimal PHP version' - ); - - $command->addOption( - Option::ONLY_SUFFIX, - null, - InputOption::VALUE_REQUIRED, - 'Deprecated, use "--filter" instead. Filter only files with specific suffix in name, e.g. "Controller"' - ); - - $command->addOption( - Option::FILTER, - null, - InputOption::VALUE_REQUIRED, - 'Keep only files matching all comma-separated patterns: "/Controller/" (path substring), "*Repository.php" (basename glob), "tests" (Test.php and TestCase.php files)' - ); - - $command->addOption(Option::DEBUG, null, InputOption::VALUE_NONE, 'Display debug output.'); - $command->addOption(Option::MEMORY_LIMIT, null, InputOption::VALUE_REQUIRED, 'Memory limit for process'); - $command->addOption(Option::CLEAR_CACHE, null, InputOption::VALUE_NONE, 'Clear unchanged files cache'); - - $command->addOption(Option::PARALLEL_PORT, null, InputOption::VALUE_REQUIRED); - $command->addOption(Option::PARALLEL_IDENTIFIER, null, InputOption::VALUE_REQUIRED); - - $command->addOption(Option::XDEBUG, null, InputOption::VALUE_NONE, 'Display xdebug output.'); - - $command->addOption( - Option::RULES_SUMMARY, - null, - InputOption::VALUE_NONE, - 'Show summary of rules applied during the run.' - ); - - $command->addOption( - Option::MAX_CHANGES, - null, - InputOption::VALUE_REQUIRED, - 'Stop after this many changes are made, leaving the rest untouched. Forces non-parallel run.' - ); - } -} diff --git a/src/Console/Style/RectorStyle.php b/src/Console/Style/RectorStyle.php index 0b8b5d7c4dc..3b33bc7daf9 100644 --- a/src/Console/Style/RectorStyle.php +++ b/src/Console/Style/RectorStyle.php @@ -4,81 +4,252 @@ namespace Rector\Console\Style; -use OndraM\CiDetector\CiDetector; -use Symfony\Component\Console\Exception\RuntimeException; -use Symfony\Component\Console\Helper\ProgressBar; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Style\SymfonyStyle; - -final class RectorStyle extends SymfonyStyle +use Entropy\Console\ConsoleTable\ConsoleTable; +use Entropy\Console\Enum\Color; +use Entropy\Console\Output\OutputColorizer; +use Entropy\Console\Output\OutputPrinter; +use Entropy\Console\Output\ProgressBar; + +/** + * Entropy-backed console style, replacing the former symfony/console SymfonyStyle. + */ +final class RectorStyle { - private ?ProgressBar $progressBar = null; + public const int VERBOSITY_QUIET = 16; - private bool|null $isCiDetected = null; + public const int VERBOSITY_NORMAL = 32; - public function __construct(InputInterface $input, OutputInterface $output) + public const int VERBOSITY_VERBOSE = 64; + + public const int VERBOSITY_DEBUG = 256; + + private int $verbosity = self::VERBOSITY_NORMAL; + + private bool $isRecording = false; + + /** + * @var string[] + */ + private array $recordedMessages = []; + + public function __construct( + private readonly OutputPrinter $outputPrinter, + private readonly OutputColorizer $outputColorizer, + private readonly ProgressBar $progressBar, + ) { + } + + public function setVerbosity(int $verbosity): void + { + $this->verbosity = $verbosity; + } + + /** + * Collect emitted messages in memory, so tests can assert on them even though the + * underlying OutputPrinter stays silent during a PHPUnit run. + * + * @api used in tests + */ + public function startRecording(): void + { + $this->isRecording = true; + $this->recordedMessages = []; + } + + /** + * @api used in tests + */ + public function getRecordedOutput(): string + { + return implode("\n", $this->recordedMessages); + } + + public function isVerbose(): bool + { + return $this->verbosity >= self::VERBOSITY_VERBOSE; + } + + public function isDebug(): bool + { + return $this->verbosity >= self::VERBOSITY_DEBUG; + } + + public function writeln(string $message): void + { + $this->record($message); + + if ($this->isQuiet()) { + return; + } + + $this->outputPrinter->writeln($this->normalizeTags($message)); + } + + public function newLine(int $count = 1): void + { + if ($this->isQuiet()) { + return; + } + + $this->outputPrinter->newline($count); + } + + public function title(string $message): void + { + $this->record($message); + + if ($this->isQuiet()) { + return; + } + + $this->outputPrinter->title($message); + } + + public function section(string $message): void + { + $this->record($message); + + if ($this->isQuiet()) { + return; + } + + $this->outputPrinter->section($message); + } + + public function success(string $message): void + { + $this->record($message); + + if ($this->isQuiet()) { + return; + } + + $this->outputPrinter->success($message); + } + + public function warning(string $message): void { - parent::__construct($input, $output); + $this->record($message); - // silent output in tests - if (defined('PHPUNIT_COMPOSER_INSTALL')) { - $this->setVerbosity(OutputInterface::VERBOSITY_QUIET); + if ($this->isQuiet()) { + return; } + + $this->outputPrinter->warning($message); + } + + public function note(string $message): void + { + $this->record($message); + + if ($this->isQuiet()) { + return; + } + + $this->outputPrinter->writeln($this->normalizeTags($message)); + } + + public function error(string $message): void + { + $this->record($message); + + // errors are shown even in quiet mode, so failures are never swallowed + $this->outputPrinter->error($message); } /** - * @see https://github.com/phpstan/phpstan-src/commit/0993d180e5a15a17631d525909356081be59ffeb + * @param string[] $items */ - public function createProgressBar(int $max = 0): ProgressBar - { - $progressBar = parent::createProgressBar($max); - $progressBar->setOverwrite(! $this->isCiDetected()); - - $isCiDetected = $this->isCiDetected(); - $progressBar->setOverwrite(! $isCiDetected); - - if ($isCiDetected) { - $progressBar->minSecondsBetweenRedraws(15); - $progressBar->maxSecondsBetweenRedraws(30); - } elseif (DIRECTORY_SEPARATOR === '\\') { - // windows - $progressBar->minSecondsBetweenRedraws(0.5); - $progressBar->maxSecondsBetweenRedraws(2); - } else { - // *nix - $progressBar->minSecondsBetweenRedraws(0.1); - $progressBar->maxSecondsBetweenRedraws(0.5); + public function listing(array $items): void + { + foreach ($items as $item) { + $this->record($item); } - $this->progressBar = $progressBar; + if ($this->isQuiet()) { + return; + } - return $progressBar; + $this->outputPrinter->listing($items); + } + + /** + * @param string[] $headers + * @param array> $rows + */ + public function table(array $headers, array $rows): void + { + foreach ($rows as $row) { + $this->record(implode(' ', $row)); + } + + if ($this->isQuiet()) { + return; + } + + $consoleTable = new ConsoleTable($this->outputPrinter); + $consoleTable->render($headers, $rows); + } + + public function ask(string $question, ?string $default = null): ?string + { + return $this->outputPrinter->ask($question, $default); + } + + public function getErrorStyle(): self + { + return $this; + } + + public function progressStart(int $max): void + { + if ($this->isQuiet()) { + return; + } + + $this->progressBar->start($max); } public function progressAdvance(int $step = 1): void { - // hide progress bar in tests - if (defined('PHPUNIT_COMPOSER_INSTALL')) { + if ($this->isQuiet()) { return; } - $progressBar = $this->getProgressBar(); - $progressBar->advance($step); + $this->progressBar->advance($step); } - private function isCiDetected(): bool + private function isQuiet(): bool { - if ($this->isCiDetected === null) { - $ciDetector = new CiDetector(); - $this->isCiDetected = $ciDetector->isCiDetected(); + return $this->verbosity <= self::VERBOSITY_QUIET; + } + + private function record(string $message): void + { + if (! $this->isRecording) { + return; } - return $this->isCiDetected; + $this->recordedMessages[] = $message; } - private function getProgressBar(): ProgressBar + /** + * Translate the former symfony/console tags still emitted by the reporters into + * the smaller tag vocabulary understood by Entropy's OutputColorizer. + */ + private function normalizeTags(string $text): string { - return $this->progressBar ?? throw new RuntimeException('The ProgressBar is not started.'); + $text = (string) preg_replace('#(.*?)#su', '$1', $text); + $text = (string) preg_replace('#(.*?)#su', '$1', $text); + + // grey is not handled by OutputColorizer::colorize(), apply it directly + $text = (string) preg_replace_callback( + '#(.*?)#su', + fn (array $matches): string => $this->outputColorizer->color($matches[1], Color::GREY), + $text + ); + + // normalize explicit closing tags (e.g. ) to the generic closing tag + return (string) preg_replace('##', '', $text); } } diff --git a/src/Console/Style/RectorStyleFactory.php b/src/Console/Style/RectorStyleFactory.php new file mode 100644 index 00000000000..a64961c2a00 --- /dev/null +++ b/src/Console/Style/RectorStyleFactory.php @@ -0,0 +1,46 @@ +setVerbosity(RectorStyle::VERBOSITY_DEBUG); + } + + // disable output for tests + if ($this->isPHPUnitRun()) { + $rectorStyle->setVerbosity(RectorStyle::VERBOSITY_QUIET); + } + + return $rectorStyle; + } + + /** + * Never ever used static methods if not necessary, this is just handy for tests + src to prevent duplication. + */ + private function isPHPUnitRun(): bool + { + return defined('PHPUNIT_COMPOSER_INSTALL') || defined('__PHPUNIT_PHAR__'); + } +} diff --git a/src/Console/Style/SymfonyStyleFactory.php b/src/Console/Style/SymfonyStyleFactory.php deleted file mode 100644 index f68d70c300a..00000000000 --- a/src/Console/Style/SymfonyStyleFactory.php +++ /dev/null @@ -1,56 +0,0 @@ -privatesAccessor->callPrivateMethod(new Application(), 'configureIO', [$argvInput, $consoleOutput]); - - // --debug is called - if ($argvInput->hasParameterOption('--debug')) { - $consoleOutput->setVerbosity(OutputInterface::VERBOSITY_DEBUG); - } - - // disable output for tests - if ($this->isPHPUnitRun()) { - $consoleOutput->setVerbosity(OutputInterface::VERBOSITY_QUIET); - } - - // no interactive terminal, e.g. piped output, CI or an agent - never emit ANSI, even if forced via --ansi - if (! TerminalDetector::isOutputTty()) { - $consoleOutput->setDecorated(false); - } - - return new RectorStyle($argvInput, $consoleOutput); - } - - /** - * Never ever used static methods if not necessary, this is just handy for tests + src to prevent duplication. - */ - private function isPHPUnitRun(): bool - { - return defined('PHPUNIT_COMPOSER_INSTALL') || defined('__PHPUNIT_PHAR__'); - } -} diff --git a/src/DependencyInjection/LazyContainerFactory.php b/src/DependencyInjection/LazyContainerFactory.php index 0c9feaa1c9a..087fd60bc88 100644 --- a/src/DependencyInjection/LazyContainerFactory.php +++ b/src/DependencyInjection/LazyContainerFactory.php @@ -28,10 +28,9 @@ use Rector\Console\Command\ProcessCommand; use Rector\Console\Command\ValidateConfigCommand; use Rector\Console\Command\WorkerCommand; -use Rector\Console\ConsoleApplication; use Rector\Console\Rule\AllRectorRulesProvider; use Rector\Console\Style\RectorStyle; -use Rector\Console\Style\SymfonyStyleFactory; +use Rector\Console\Style\RectorStyleFactory; use Rector\Contract\PhpParser\DecoratingNodeVisitorInterface; use Rector\NodeNameResolver\NodeNameResolver; use Rector\NodeTypeResolver\DependencyInjection\PHPStanServicesFactory; @@ -56,8 +55,6 @@ use Rector\PhpParser\NodeVisitor\ReboundClosureNodeVisitor; use Rector\PostRector\Application\PostFileProcessor; use Rector\Rector\AbstractRector; -use Symfony\Component\Console\Application; -use Symfony\Component\Console\Style\SymfonyStyle; use Webmozart\Assert\Assert; final class LazyContainerFactory @@ -110,18 +107,6 @@ public function create(): RectorConfig private function registerConsole(RectorConfig $rectorConfig): void { - $rectorConfig->singleton(Application::class, static function (RectorConfig $rectorConfig): Application { - $consoleApplication = $rectorConfig->make(ConsoleApplication::class); - - $commandNamesToHide = ['list', 'completion', 'help', 'worker']; - foreach ($commandNamesToHide as $commandNameToHide) { - $commandToHide = $consoleApplication->get($commandNameToHide); - $commandToHide->setHidden(); - } - - return $consoleApplication; - }); - $rectorConfig->singleton(ConfigurationRuleFilter::class); $rectorConfig->singleton(ProcessCommand::class); @@ -130,7 +115,6 @@ private function registerConsole(RectorConfig $rectorConfig): void $rectorConfig->singleton(AllRectorRulesProvider::class); $rectorConfig->singleton(ListRulesCommand::class); $rectorConfig->singleton(ComposerBasedCommand::class); - } private function registerFileProcessing(RectorConfig $rectorConfig): void @@ -201,17 +185,10 @@ private function registerTaggedServices(RectorConfig $rectorConfig): void $rectorConfig->singleton( RectorStyle::class, static function (RectorConfig $rectorConfig): RectorStyle { - $symfonyStyleFactory = $rectorConfig->make(SymfonyStyleFactory::class); - return $symfonyStyleFactory->create(); + $rectorStyleFactory = $rectorConfig->make(RectorStyleFactory::class); + return $rectorStyleFactory->create(); } ); - - // kept for extensions that still inject SymfonyStyle - $rectorConfig->singleton( - SymfonyStyle::class, - static fn (RectorConfig $rectorConfig): SymfonyStyle => $rectorConfig->make(RectorStyle::class) - ); - } private function registerAnnotationToAttributeSetters(RectorConfig $rectorConfig): void diff --git a/src/DependencyInjection/RectorContainerFactory.php b/src/DependencyInjection/RectorContainerFactory.php index 601c0281a1e..cea3735170f 100644 --- a/src/DependencyInjection/RectorContainerFactory.php +++ b/src/DependencyInjection/RectorContainerFactory.php @@ -9,7 +9,6 @@ use Rector\Config\RectorConfig; use Rector\NodeTypeResolver\DependencyInjection\PHPStanServicesFactory; use Rector\ValueObject\Bootstrap\BootstrapConfigs; -use Symfony\Component\Console\Input\ArgvInput; final class RectorContainerFactory { @@ -21,7 +20,7 @@ public function createFromBootstrapConfigs(BootstrapConfigs $bootstrapConfigs): // only the main process checks the configuration: the parallel workers share its cache directory, // and a worker that clears the cache would delete files the other workers are writing - if ($mainConfigFile !== null && new ArgvInput()->getFirstArgument() !== 'worker') { + if ($mainConfigFile !== null && ! $this->isWorkerRun()) { /** @var ChangedFilesDetector $changedFilesDetector */ $changedFilesDetector = $rectorConfig->make(ChangedFilesDetector::class); $changedFilesDetector->setFirstResolvedConfigFileInfo($mainConfigFile); @@ -50,4 +49,20 @@ private function createFromConfigs(array $configFiles): RectorConfig return $rectorConfig; } + + /** + * The parallel workers are launched with "worker" as the first CLI argument. + */ + private function isWorkerRun(): bool + { + foreach (array_slice($_SERVER['argv'] ?? [], 1) as $arg) { + if (! is_string($arg) || str_starts_with($arg, '-')) { + continue; + } + + return $arg === 'worker'; + } + + return false; + } } diff --git a/src/NodeTypeResolver/DependencyInjection/PHPStanServicesFactory.php b/src/NodeTypeResolver/DependencyInjection/PHPStanServicesFactory.php index 8755e439efa..00a3df96c9a 100644 --- a/src/NodeTypeResolver/DependencyInjection/PHPStanServicesFactory.php +++ b/src/NodeTypeResolver/DependencyInjection/PHPStanServicesFactory.php @@ -15,10 +15,8 @@ use PHPStan\Reflection\ReflectionProvider; use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; +use Rector\Console\Style\RectorStyleFactory; use Rector\NodeTypeResolver\Reflection\BetterReflection\SourceLocatorProvider\DynamicSourceLocatorProvider; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\ConsoleOutput; -use Symfony\Component\Console\Style\SymfonyStyle; use Throwable; use Webmozart\Assert\Assert; @@ -54,8 +52,8 @@ public function __construct() ); } catch (Throwable $throwable) { if ($throwable->getMessage() === "File 'phar://phpstan.phar/conf/bleedingEdge.neon' is missing or is not readable.") { - $symfonyStyle = new SymfonyStyle(new ArrayInput([]), new ConsoleOutput()); - $symfonyStyle->error( + $rectorStyle = new RectorStyleFactory()->create(); + $rectorStyle->error( str_replace("\r\n", "\n", sprintf( self::INVALID_BLEEDING_EDGE_PATH_MESSAGE, $throwable->getMessage() diff --git a/src/Parallel/Command/WorkerCommandLineFactory.php b/src/Parallel/Command/WorkerCommandLineFactory.php index 0b16ce677b9..34ad85482f5 100644 --- a/src/Parallel/Command/WorkerCommandLineFactory.php +++ b/src/Parallel/Command/WorkerCommandLineFactory.php @@ -53,10 +53,6 @@ public function create( $workerCommandArray[] = self::OPTION_DASHES . Option::PARALLEL_IDENTIFIER; $workerCommandArray[] = escapeshellarg($identifier); - foreach ($configuration->getPaths() as $path) { - $workerCommandArray[] = escapeshellarg($path); - } - // set json output $workerCommandArray[] = self::OPTION_DASHES . Option::OUTPUT_FORMAT; $workerCommandArray[] = escapeshellarg(JsonOutputFormatter::NAME); @@ -74,6 +70,11 @@ public function create( $workerCommandArray[] = escapeshellarg($this->filePathHelper->relativePath($config)); } + // paths last, as positional arguments + foreach ($configuration->getPaths() as $path) { + $workerCommandArray[] = escapeshellarg($path); + } + return implode(' ', $workerCommandArray); } @@ -138,7 +139,7 @@ private function createValueOptions(Configuration $configuration): array $memoryLimit = $configuration->getMemoryLimit(); if ($memoryLimit !== null && $memoryLimit !== '') { - // "=" form, symfony/console does not accept -1 as value without assign + // "=" form, so a negative value like -1 is not parsed as another option $workerOptions[] = self::OPTION_DASHES . Option::MEMORY_LIMIT . '=' . escapeshellarg($memoryLimit); } diff --git a/src/functions/node_helper.php b/src/functions/node_helper.php index d0d69a2ca36..d0d11a67bdf 100644 --- a/src/functions/node_helper.php +++ b/src/functions/node_helper.php @@ -4,11 +4,10 @@ use PhpParser\Node; use PhpParser\PrettyPrinter\Standard; -use Rector\Console\Style\SymfonyStyleFactory; +use Rector\Console\Style\RectorStyle; +use Rector\Console\Style\RectorStyleFactory; use Rector\PhpParser\Node\FileNode; use Rector\Util\NodePrinter; -use Rector\Util\Reflection\PrivatesAccessor; -use Symfony\Component\Console\Output\OutputInterface; if (! function_exists('print_node')) { /** @@ -36,12 +35,12 @@ function print_node(Node|array $node): void */ function dump_node(Node|array $node): void { - $symfonyStyleFactory = new SymfonyStyleFactory(new PrivatesAccessor()); - $rectorStyle = $symfonyStyleFactory->create(); + $rectorStyleFactory = new RectorStyleFactory(); + $rectorStyle = $rectorStyleFactory->create(); // we turn up the verbosity so it's visible in tests overriding the // default which is to be quite during tests - $rectorStyle->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); + $rectorStyle->setVerbosity(RectorStyle::VERBOSITY_VERBOSE); $rectorStyle->newLine(); $nodePrinter = new NodePrinter($rectorStyle); diff --git a/tests/Bin/RectorTest.php b/tests/Bin/RectorTest.php index bf8e51fb747..c651645a4de 100644 --- a/tests/Bin/RectorTest.php +++ b/tests/Bin/RectorTest.php @@ -22,7 +22,7 @@ public static function outputProvider(): Iterator ]; yield 'Exception with previous console output' => [ 'command' => PHP_BINARY . ' bin/rector -c tests/Bin/config/incorrect-phpstan-files.php', - 'expectedOutput' => PHP_EOL . " [ERROR] Unexpected item 'parameters › invalidParameters'. " . PHP_EOL . PHP_EOL, + 'expectedOutput' => PHP_EOL . " [ERROR] Unexpected item 'parameters › invalidParameters'." . PHP_EOL, ]; yield 'Exception with previous console output in JSON format' => [ 'command' => PHP_BINARY . ' bin/rector -c tests/Bin/config/incorrect-phpstan-files.php --output-format json', diff --git a/tests/Composer/InstalledPackageResolverTest.php b/tests/Composer/InstalledPackageResolverTest.php index 6ce3f23441a..4c66c9e5cc5 100644 --- a/tests/Composer/InstalledPackageResolverTest.php +++ b/tests/Composer/InstalledPackageResolverTest.php @@ -17,7 +17,7 @@ public function test(): void $installedPackages = $installedPackageResolver->resolve(); $this->assertContainsOnlyInstancesOf(InstalledPackage::class, $installedPackages); - $this->assertGreaterThan(77, count($installedPackages)); + $this->assertGreaterThan(70, count($installedPackages)); } public function testFallbackToCurrentWorkingDirectory(): void @@ -26,7 +26,7 @@ public function testFallbackToCurrentWorkingDirectory(): void $installedPackages = $installedPackageResolver->resolve(); $this->assertContainsOnlyInstancesOf(InstalledPackage::class, $installedPackages); - $this->assertGreaterThan(77, count($installedPackages)); + $this->assertGreaterThan(70, count($installedPackages)); } public function testComposerJsonHasPriorityOverOutdatedInstalledJson(): void diff --git a/tests/Configuration/ConfigurationFactoryTest.php b/tests/Configuration/ConfigurationFactoryTest.php index fdd51ecd78f..1451ef6d651 100644 --- a/tests/Configuration/ConfigurationFactoryTest.php +++ b/tests/Configuration/ConfigurationFactoryTest.php @@ -4,15 +4,14 @@ namespace Rector\Tests\Configuration; +use Rector\ChangesReporting\Output\ConsoleOutputFormatter; use Rector\Configuration\ConfigurationFactory; use Rector\Configuration\Option; use Rector\Configuration\Parameter\SimpleParameterProvider; -use Rector\Console\ProcessConfigureDecorator; use Rector\FileSystem\FilesFinder; use Rector\Testing\PHPUnit\AbstractLazyTestCase; +use Rector\ValueObject\Configuration; use stdClass; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\ArrayInput; final class ConfigurationFactoryTest extends AbstractLazyTestCase { @@ -61,8 +60,7 @@ public function testPublishesCommandLinePathsAsSourceParameter(): void { SimpleParameterProvider::setParameter(Option::PATHS, [__DIR__ . '/config']); - $this->make(ConfigurationFactory::class) - ->createFromInput($this->createInput([__DIR__ . '/Source'])); + $this->createConfiguration([__DIR__ . '/Source']); $this->assertSame( [__DIR__ . '/Source'], @@ -74,8 +72,7 @@ public function testPublishesConfiguredPathsAsSourceParameterWhenNoneGivenOnTheC { SimpleParameterProvider::setParameter(Option::PATHS, [__DIR__ . '/config']); - $this->make(ConfigurationFactory::class) - ->createFromInput($this->createInput([])); + $this->createConfiguration([]); $this->assertSame( [__DIR__ . '/config'], @@ -125,13 +122,27 @@ public function testObjectPropertyOrderIsOutsideTheCacheInvalidationHash(): void /** * @param string[] $paths */ - private function createInput(array $paths): ArrayInput + private function createConfiguration(array $paths): Configuration { - $command = new Command('process'); - ProcessConfigureDecorator::decorate($command); - - return new ArrayInput([ - Option::SOURCE => $paths, - ], $command->getDefinition()); + return $this->make(ConfigurationFactory::class) + ->create( + $paths, + false, + false, + false, + false, + ConsoleOutputFormatter::NAME, + [], + false, + false, + null, + null, + false, + null, + '', + '', + null, + false, + ); } } diff --git a/tests/Console/Command/ComposerBasedCommandTest.php b/tests/Console/Command/ComposerBasedCommandTest.php index 3ca3fb46dad..09abb502d2a 100644 --- a/tests/Console/Command/ComposerBasedCommandTest.php +++ b/tests/Console/Command/ComposerBasedCommandTest.php @@ -11,20 +11,16 @@ use Rector\Configuration\Parameter\SimpleParameterProvider; use Rector\Console\Command\ComposerBasedCommand; use Rector\Console\Style\RectorStyle; +use Rector\Console\Style\RectorStyleFactory; use Rector\Renaming\Rector\Name\RenameClassRector; use Rector\Tests\Console\Command\Source\ComposerBoundRector; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\BufferedOutput; -use Symfony\Component\Console\Output\OutputInterface; final class ComposerBasedCommandTest extends TestCase { - private BufferedOutput $bufferedOutput; + private RectorStyle $rectorStyle; protected function setUp(): void { - $this->bufferedOutput = new BufferedOutput(); - // the parameter provider is static, reset it between tests SimpleParameterProvider::setParameter(Option::COMPOSER_BOUND_RULE_CONFIGURATIONS, []); } @@ -39,9 +35,9 @@ public function testName(): void public function testSkipWithoutComposerBoundRules(): void { $composerBasedCommand = $this->createComposerBasedCommand([]); - $composerBasedCommand->run(new ArrayInput([]), $this->bufferedOutput); + $composerBasedCommand->run(); - $this->assertStringContainsString('No composer package bound rule is loaded', $this->bufferedOutput->fetch()); + $this->assertStringContainsString('No composer package bound rule is loaded', $this->rectorStyle->getRecordedOutput()); } public function testActiveRule(): void @@ -50,9 +46,9 @@ public function testActiveRule(): void $composerBoundRector = new ComposerBoundRector('phpunit/phpunit', '>=9.0'); $composerBasedCommand = $this->createComposerBasedCommand([$composerBoundRector]); - $composerBasedCommand->run(new ArrayInput([]), $this->bufferedOutput); + $composerBasedCommand->run(); - $output = $this->bufferedOutput->fetch(); + $output = $this->rectorStyle->getRecordedOutput(); $this->assertStringContainsString('phpunit/phpunit', $output); $this->assertStringContainsString('>=9.0', $output); @@ -64,9 +60,9 @@ public function testNotInstalledPackage(): void $composerBoundRector = new ComposerBoundRector('not-installed/package', '>=1.0'); $composerBasedCommand = $this->createComposerBasedCommand([$composerBoundRector]); - $composerBasedCommand->run(new ArrayInput([]), $this->bufferedOutput); + $composerBasedCommand->run(); - $output = $this->bufferedOutput->fetch(); + $output = $this->rectorStyle->getRecordedOutput(); $this->assertStringContainsString('not-installed/package', $output); $this->assertStringContainsString('0 of 1 composer package bound items are active', $output); @@ -87,9 +83,9 @@ public function testRuleConfiguration(): void ); $composerBasedCommand = $this->createComposerBasedCommand([]); - $composerBasedCommand->run(new ArrayInput([]), $this->bufferedOutput); + $composerBasedCommand->run(); - $output = $this->bufferedOutput->fetch(); + $output = $this->rectorStyle->getRecordedOutput(); $this->assertStringContainsString('Composer package bound rule configuration', $output); $this->assertStringContainsString('SomeOldClass: SomeNewClass', $output); @@ -110,9 +106,9 @@ public function testInactiveRuleConfigurationIsReported(): void ); $composerBasedCommand = $this->createComposerBasedCommand([]); - $composerBasedCommand->run(new ArrayInput([]), $this->bufferedOutput); + $composerBasedCommand->run(); - $output = $this->bufferedOutput->fetch(); + $output = $this->rectorStyle->getRecordedOutput(); $this->assertStringContainsString('not-installed/package', $output); $this->assertStringContainsString('0 of 1 composer package bound items are active', $output); @@ -123,10 +119,9 @@ public function testInactiveRuleConfigurationIsReported(): void */ private function createComposerBasedCommand(array $rectors): ComposerBasedCommand { - $rectorStyle = new RectorStyle(new ArrayInput([]), $this->bufferedOutput); - // RectorStyle is quiet under PHPUnit, output is asserted here - $rectorStyle->setVerbosity(OutputInterface::VERBOSITY_NORMAL); + $this->rectorStyle = new RectorStyleFactory()->create(); + $this->rectorStyle->startRecording(); - return new ComposerBasedCommand($rectorStyle, new InstalledPackageResolver(getcwd()), $rectors); + return new ComposerBasedCommand($this->rectorStyle, new InstalledPackageResolver(getcwd()), $rectors); } } diff --git a/tests/Console/Command/ValidateConfigCommandTest.php b/tests/Console/Command/ValidateConfigCommandTest.php index f8b6f8b7929..57a8646ab2d 100644 --- a/tests/Console/Command/ValidateConfigCommandTest.php +++ b/tests/Console/Command/ValidateConfigCommandTest.php @@ -10,7 +10,7 @@ use Rector\Configuration\VendorMissAnalyseGuard; use Rector\Console\Command\ValidateConfigCommand; use Rector\Console\ExitCode; -use Rector\Console\Style\RectorStyle; +use Rector\Console\Style\RectorStyleFactory; use Rector\Php85\Rector\FuncCall\OrdSingleByteRector; use Rector\Reporting\DeprecatedRulesReporter; use Rector\Reporting\MissConfigurationReporter; @@ -19,14 +19,10 @@ use Rector\Skipper\Skipper\Skipper; use Rector\Testing\PHPUnit\AbstractLazyTestCase; use Rector\Tests\Console\Command\Source\DeprecatedFixtureRule; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\BufferedOutput; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Tester\CommandTester; final class ValidateConfigCommandTest extends AbstractLazyTestCase { - private CommandTester $commandTester; + private ValidateConfigCommand $validateConfigCommand; protected function setUp(): void { @@ -47,11 +43,9 @@ protected function setUp(): void SimpleParameterProvider::setParameter($optionName, []); } - $rectorStyle = new RectorStyle(new ArrayInput([]), new BufferedOutput()); - // RectorStyle is quiet under PHPUnit, output is asserted here - $rectorStyle->setVerbosity(OutputInterface::VERBOSITY_NORMAL); + $rectorStyle = new RectorStyleFactory()->create(); - $validateConfigCommand = new ValidateConfigCommand( + $this->validateConfigCommand = new ValidateConfigCommand( $rectorStyle, new DeprecatedRulesReporter($rectorStyle), new MissConfigurationReporter( @@ -62,8 +56,6 @@ protected function setUp(): void ), $this->make(Skipper::class), ); - - $this->commandTester = new CommandTester($validateConfigCommand); } protected function tearDown(): void @@ -75,7 +67,7 @@ public function testFailsOnDeprecatedRegisteredRule(): void { SimpleParameterProvider::setParameter(Option::REGISTERED_RECTOR_RULES, [DeprecatedFixtureRule::class]); - $this->assertSame(ExitCode::FAILURE, $this->commandTester->execute([])); + $this->assertSame(ExitCode::FAILURE, $this->validateConfigCommand->run()); } public function testFailsOnDeprecatedPreparedSetsArg(): void @@ -83,14 +75,14 @@ public function testFailsOnDeprecatedPreparedSetsArg(): void SimpleParameterProvider::setParameter(Option::REGISTERED_RECTOR_RULES, [OrdSingleByteRector::class]); SimpleParameterProvider::setParameter(Option::DEPRECATED_PREPARED_SETS_ARGS, ['earlyReturn']); - $this->assertSame(ExitCode::FAILURE, $this->commandTester->execute([])); + $this->assertSame(ExitCode::FAILURE, $this->validateConfigCommand->run()); } public function testSucceedsOnCleanConfig(): void { SimpleParameterProvider::setParameter(Option::REGISTERED_RECTOR_RULES, [OrdSingleByteRector::class]); - $this->assertSame(ExitCode::SUCCESS, $this->commandTester->execute([])); + $this->assertSame(ExitCode::SUCCESS, $this->validateConfigCommand->run()); } public function testJsonOutputOnCleanConfig(): void @@ -98,9 +90,7 @@ public function testJsonOutputOnCleanConfig(): void SimpleParameterProvider::setParameter(Option::REGISTERED_RECTOR_RULES, [OrdSingleByteRector::class]); ob_start(); - $exitCode = $this->commandTester->execute([ - '--output-format' => 'json', - ]); + $exitCode = $this->validateConfigCommand->run(outputFormat: 'json'); $json = (string) ob_get_clean(); $this->assertSame(ExitCode::SUCCESS, $exitCode); @@ -115,9 +105,7 @@ public function testJsonOutputOnDeprecatedRegisteredRule(): void SimpleParameterProvider::setParameter(Option::REGISTERED_RECTOR_RULES, [DeprecatedFixtureRule::class]); ob_start(); - $exitCode = $this->commandTester->execute([ - '--output-format' => 'json', - ]); + $exitCode = $this->validateConfigCommand->run(outputFormat: 'json'); $json = (string) ob_get_clean(); $this->assertSame(ExitCode::FAILURE, $exitCode); diff --git a/tests/Parallel/Command/WorkerCommandLineFactoryTest.php b/tests/Parallel/Command/WorkerCommandLineFactoryTest.php index bddd00d77ea..4bad38f01c6 100644 --- a/tests/Parallel/Command/WorkerCommandLineFactoryTest.php +++ b/tests/Parallel/Command/WorkerCommandLineFactoryTest.php @@ -50,7 +50,7 @@ public function testSpacedMainScript(): void ); $expectedCommand = $this->normalizeExpectedCommandOutput( - "'" . PHP_BINARY . "' " . $this->turboExtensionArguments() . "'" . self::SPACED_DUMMY_MAIN_SCRIPT . "' worker --port 2000 --identifier 'identifier' 'src' --output-format 'json' --no-ansi" + "'" . PHP_BINARY . "' " . $this->turboExtensionArguments() . "'" . self::SPACED_DUMMY_MAIN_SCRIPT . "' worker --port 2000 --identifier 'identifier' --output-format 'json' --no-ansi 'src'" ); $this->assertSame($expectedCommand, $workerCommandLine); @@ -85,7 +85,7 @@ public function test(array $argv, Configuration $configuration, string $expected public static function provideData(): Iterator { $defaultArgv = ['bin/rector', 'process', 'src']; - $suffix = "--port 2000 --identifier 'identifier' 'src' --output-format 'json' --no-ansi"; + $suffix = "--port 2000 --identifier 'identifier' --output-format 'json' --no-ansi 'src'"; yield 'no options' => [$defaultArgv, new Configuration(paths: ['src']), $suffix]; @@ -131,7 +131,7 @@ public static function provideData(): Iterator yield 'explicit config' => [ [...$defaultArgv, '--config', 'some config/rector.php'], new Configuration(paths: ['src']), - $suffix . " --config 'some config/rector.php'", + "--port 2000 --identifier 'identifier' --output-format 'json' --no-ansi --config 'some config/rector.php' 'src'", ]; } diff --git a/tests/Reporting/MissConfigurationReporterTest.php b/tests/Reporting/MissConfigurationReporterTest.php index f4311713caa..c9e6aaaece4 100644 --- a/tests/Reporting/MissConfigurationReporterTest.php +++ b/tests/Reporting/MissConfigurationReporterTest.php @@ -8,6 +8,7 @@ use Rector\Configuration\Parameter\SimpleParameterProvider; use Rector\Configuration\VendorMissAnalyseGuard; use Rector\Console\Style\RectorStyle; +use Rector\Console\Style\RectorStyleFactory; use Rector\Php85\Rector\FuncCall\OrdSingleByteRector; use Rector\PostRector\Rector\NameImportingPostRector; use Rector\Reporting\MissConfigurationReporter; @@ -20,9 +21,6 @@ use Rector\Tests\Skipper\Skipper\Source\NotSkippedClass; use Rector\Validation\RectorConfigValidator; use Rector\ValueObject\ProcessResult; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\BufferedOutput; -use Symfony\Component\Console\Output\OutputInterface; final class MissConfigurationReporterTest extends AbstractLazyTestCase { @@ -32,7 +30,7 @@ final class MissConfigurationReporterTest extends AbstractLazyTestCase private const string GLOBAL_MASK = '*/global-mask/*'; - private BufferedOutput $bufferedOutput; + private RectorStyle $rectorStyle; private MissConfigurationReporter $missConfigurationReporter; @@ -40,13 +38,11 @@ protected function setUp(): void { parent::setUp(); - $this->bufferedOutput = new BufferedOutput(); - $rectorStyle = new RectorStyle(new ArrayInput([]), $this->bufferedOutput); - // RectorStyle is quiet under PHPUnit, output is asserted here - $rectorStyle->setVerbosity(OutputInterface::VERBOSITY_NORMAL); + $this->rectorStyle = new RectorStyleFactory()->create(); + $this->rectorStyle->startRecording(); $this->missConfigurationReporter = new MissConfigurationReporter( - $rectorStyle, + $this->rectorStyle, new VendorMissAnalyseGuard(), $this->make(UnusedSkipResolver::class), $this->make(NeededSkipVerifier::class), @@ -84,7 +80,7 @@ public function testReportsSkippedNonRectorClass(): void $this->missConfigurationReporter->reportSkippedNonRectorClasses(); - $output = $this->bufferedOutput->fetch(); + $output = $this->rectorStyle->getRecordedOutput(); $this->assertStringContainsString('NotSkippedClass', $output); @@ -100,7 +96,7 @@ public function testReportsNothingOnRectorClassesOnly(): void $this->missConfigurationReporter->reportSkippedNonRectorClasses(); - $this->assertSame('', $this->bufferedOutput->fetch()); + $this->assertSame('', $this->rectorStyle->getRecordedOutput()); } public function testReportsOnlyTrackableUnusedSkips(): void @@ -113,7 +109,7 @@ public function testReportsOnlyTrackableUnusedSkips(): void ]); $this->missConfigurationReporter->reportUnusedSkips($processResult); - $output = $this->bufferedOutput->fetch(); + $output = $this->rectorStyle->getRecordedOutput(); // unused rule-scoped path is reported as "rule => path", so both are shown $this->assertStringContainsString('dead-rule', $output); @@ -137,6 +133,6 @@ public function testReportsNothingWhenDisabled(): void $processResult = new ProcessResult([], [], 0, []); $this->missConfigurationReporter->reportUnusedSkips($processResult); - $this->assertSame('', $this->bufferedOutput->fetch()); + $this->assertSame('', $this->rectorStyle->getRecordedOutput()); } }