-
-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathProcessCommand.php
More file actions
276 lines (226 loc) · 10.6 KB
/
ProcessCommand.php
File metadata and controls
276 lines (226 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
<?php
declare(strict_types=1);
namespace Rector\Console\Command;
use Rector\Application\ApplicationFileProcessor;
use Rector\Autoloading\AdditionalAutoloader;
use Rector\Caching\Detector\ChangedFilesDetector;
use Rector\ChangesReporting\Output\JsonOutputFormatter;
use Rector\Configuration\ConfigInitializer;
use Rector\Configuration\ConfigurationFactory;
use Rector\Configuration\ConfigurationRuleFilter;
use Rector\Configuration\Option;
use Rector\Configuration\Parameter\SimpleParameterProvider;
use Rector\Console\ExitCode;
use Rector\Console\Output\OutputFormatterCollector;
use Rector\Console\ProcessConfigureDecorator;
use Rector\Exception\ShouldNotHappenException;
use Rector\Reporting\DeprecatedRulesReporter;
use Rector\Reporting\MissConfigurationReporter;
use Rector\Skipper\SkipCriteriaResolver\SkippedClassResolver;
use Rector\StaticReflection\DynamicSourceLocatorDecorator;
use Rector\Util\MemoryLimiter;
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\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
final class ProcessCommand extends Command
{
private SymfonyStyle $errorSymfonyStyle;
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 SymfonyStyle $symfonyStyle,
private readonly MemoryLimiter $memoryLimiter,
private readonly ConfigurationFactory $configurationFactory,
private readonly DeprecatedRulesReporter $deprecatedRulesReporter,
private readonly MissConfigurationReporter $missConfigurationReporter,
private readonly ConfigurationRuleFilter $configurationRuleFilter,
private readonly SkippedClassResolver $skippedClassResolver,
) {
parent::__construct();
}
protected function configure(): void
{
$this->setName('process');
$this->setDescription('Upgrades or refactors source code with provided Rector rules');
$this->setHelp(
<<<'EOF'
The <info>%command.name%</info> command will run Rector main feature:
<info>vendor/bin/rector</info>
To specify a folder or a file, you can run:
<info>vendor/bin/rector src/Controller</info>
You can also dry run to see the changes that Rector will make with the <comment>--dry-run</comment> option:
<info>vendor/bin/rector src/Controller --dry-run</info>
It's also possible to get debug via the <comment>--debug</comment> option:
<info>vendor/bin/rector src/Controller --dry-run --debug</info>
EOF
);
ProcessConfigureDecorator::decorate($this);
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->errorSymfonyStyle = $output instanceof ConsoleOutputInterface
? new SymfonyStyle($input, $output->getErrorOutput())
: $this->symfonyStyle;
// missing config? add it :)
if (! $this->configInitializer->areSomeRectorsLoaded()) {
$this->configInitializer->createConfig(getcwd());
return self::SUCCESS;
}
$configuration = $this->configurationFactory->createFromInput($input);
$this->memoryLimiter->adjust($configuration);
$this->configurationRuleFilter->setConfiguration($configuration);
// disable console output in case of json output formatter
if ($configuration->getOutputFormat() === JsonOutputFormatter::NAME) {
$this->symfonyStyle->setVerbosity(OutputInterface::VERBOSITY_QUIET);
}
$this->additionalAutoloader->autoloadInput($input);
$paths = $configuration->getPaths();
// 0. warn about too high levels
foreach ($configuration->getLevelOverflows() as $levelOverflow) {
$this->reportLevelOverflow($levelOverflow);
}
// 0. warn about skipped rules that are deprecated
if ($this->skippedClassResolver->resolveDeprecatedSkippedClasses() !== []) {
$this->errorSymfonyStyle->warning(sprintf(
'These rules are skipped, but are deprecated. Most likely you do not need to skip them anymore as not part of any set and remove them: %s* %s',
"\n\n",
implode(' * ', $this->skippedClassResolver->resolveDeprecatedSkippedClasses()) . "\n"
));
}
// 1. warn about rules registered in both withRules() and sets to avoid bloated rector.php configs
$setAndRulesDuplicatedRegistrations = $configuration->getBothSetAndRulesDuplicatedRegistrations();
if ($setAndRulesDuplicatedRegistrations !== []) {
$this->errorSymfonyStyle->warning(sprintf(
'These rules are registered in both sets and "withRules()". Remove them from "withRules()" to avoid duplications: %s* %s',
"\n\n",
implode(' * ', $setAndRulesDuplicatedRegistrations) . "\n"
));
}
// 2. add files and directories to static locator
$this->dynamicSourceLocatorDecorator->addPaths($paths);
if ($this->dynamicSourceLocatorDecorator->arePathsEmpty()) {
// read from rector.php, no paths definition needs withPaths() config
if ($paths === []) {
$this->symfonyStyle->error(
'Provide paths in Rector config. See ways: https://getrector.com/documentation/define-paths'
);
return ExitCode::FAILURE;
}
// read from cli paths arguments, eg: vendor/bin/rector process A B C which A, B, and C not exists
$isSingular = count($paths) === 1;
$this->symfonyStyle->error(
sprintf(
'The following given path%s do%s not match any file%s or director%s: %s%s',
$isSingular ? '' : 's',
$isSingular ? 'es' : '',
$isSingular ? '' : 's',
$isSingular ? 'y' : 'ies',
"\n\n" . ' - ',
implode("\n" . ' - ', $paths)
)
);
return ExitCode::FAILURE;
}
// autoload paths is register to DynamicSourceLocatorProvider,
// so check after arePathsEmpty() above
// check in no parallel since parallel will require register on its own process
if (! $configuration->isParallel()) {
$this->additionalAutoloader->autoloadPaths();
}
// show debug info
if ($configuration->isDebug()) {
$this->reportLoadedComposerBasedSets();
}
// MAIN PHASE
// 2. run Rector
$processResult = $this->applicationFileProcessor->run($configuration, $input);
// REPORTING PHASE
// 3. reporting phaseRunning 2nd time with collectors data
// report diffs and errors
$outputFormat = $configuration->getOutputFormat();
$outputFormatter = $this->outputFormatterCollector->getByName($outputFormat);
$outputFormatter->report($processResult, $configuration);
// 4. Deprecations reporter
$this->deprecatedRulesReporter->reportDeprecatedRules();
$this->deprecatedRulesReporter->reportDeprecatedSkippedRules();
$this->deprecatedRulesReporter->reportDeprecatedNodeTypes();
$this->deprecatedRulesReporter->reportDeprecatedRectorUnsupportedMethods();
$this->missConfigurationReporter->reportSkippedNeverRegisteredRules();
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);
if ($optionDebug) {
$application->setCatchExceptions(false);
}
// clear cache
$optionClearCache = (bool) $input->getOption(Option::CLEAR_CACHE);
if ($optionDebug || $optionClearCache) {
$this->changedFilesDetector->clear();
}
}
/**
* @return ExitCode::*
*/
private function resolveReturnCode(ProcessResult $processResult, Configuration $configuration): int
{
// some system errors were found → fail
if ($processResult->getSystemErrors() !== []) {
return ExitCode::FAILURE;
}
// inverse error code for CI dry-run
if (! $configuration->isDryRun()) {
return ExitCode::SUCCESS;
}
if ($processResult->getFileDiffs() !== []) {
return ExitCode::CHANGED_CODE;
}
if ($processResult->getTotalChanged() > 0) {
return ExitCode::CHANGED_CODE;
}
return ExitCode::SUCCESS;
}
private function reportLoadedComposerBasedSets(): void
{
if (! SimpleParameterProvider::hasParameter(Option::COMPOSER_BASED_SETS)) {
return;
}
$composerBasedSets = SimpleParameterProvider::provideArrayParameter(Option::COMPOSER_BASED_SETS);
if ($composerBasedSets === []) {
return;
}
$this->errorSymfonyStyle->writeln('[info] Sets loaded based on installed packages:');
$this->errorSymfonyStyle->listing($composerBasedSets);
}
private function reportLevelOverflow(LevelOverflow $levelOverflow): void
{
$suggestedSetMethod = PHP_VERSION_ID >= 80000 ? sprintf(
'->withPreparedSets(%s: true)',
$levelOverflow->getSuggestedRuleset()
) : sprintf('->withSets(SetList::%s)', $levelOverflow->getSuggestedSetListConstant());
$this->errorSymfonyStyle->warning(sprintf(
'The "->%s()" level contains only %d rules, but you set level to %d.%sYou are using the full set now! Time to switch to more efficient "%s".',
$levelOverflow->getConfigurationName(),
$levelOverflow->getRuleCount(),
$levelOverflow->getLevel(),
"\n",
$suggestedSetMethod,
));
}
}