Skip to content

Commit 3bd9f03

Browse files
authored
[dx] Report rule-scoped skips that matched a file but never changed it (#8853)
1 parent ec71117 commit 3bd9f03

8 files changed

Lines changed: 328 additions & 0 deletions

File tree

‎src/Console/Command/ProcessCommand.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int
202202
$this->missConfigurationReporter->reportSkippedNonRectorClasses();
203203
$this->missConfigurationReporter->reportUnusedSkips($processResult);
204204

205+
// the verification re-run is forced to a dry run, so it is safe on an apply run too
206+
$this->missConfigurationReporter->reportUnnecessarySkips();
207+
205208
return $this->resolveReturnCode($processResult, $configuration);
206209
}
207210

‎src/Reporting/MissConfigurationReporter.php‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ public function __construct(
2121
private SymfonyStyle $symfonyStyle,
2222
private VendorMissAnalyseGuard $vendorMissAnalyseGuard,
2323
private UnusedSkipResolver $unusedSkipResolver,
24+
private NeededSkipVerifier $neededSkipVerifier,
2425
) {
2526
}
2627

@@ -47,6 +48,33 @@ public function reportUnusedSkips(ProcessResult $processResult): void
4748
$this->symfonyStyle->listing($spacedUnusedSkips);
4849
}
4950

51+
/**
52+
* Reports rule-scoped skips that matched a file but whose rule would not have changed it, so the
53+
* skip is unnecessary. Enabled with "->reportUnusedSkips()". The re-run is forced to a dry run,
54+
* so it is safe on an apply run too.
55+
*/
56+
public function reportUnnecessarySkips(): void
57+
{
58+
$unnecessarySkips = $this->neededSkipVerifier->verify();
59+
if ($unnecessarySkips === []) {
60+
return;
61+
}
62+
63+
$this->symfonyStyle->warning(sprintf(
64+
'%s matched a file, but the rule would not have changed it. You can remove %s from "->withSkip()"',
65+
count($unnecessarySkips) > 1 ? 'These skips are unnecessary, they' : 'This skip is unnecessary, it',
66+
count($unnecessarySkips) > 1 ? 'them' : 'it'
67+
));
68+
69+
// add a blank line between items, so grouped rule skips stay visually separated
70+
$spacedUnnecessarySkips = array_map(
71+
static fn (string $unnecessarySkip): string => $unnecessarySkip . "\n",
72+
$unnecessarySkips
73+
);
74+
75+
$this->symfonyStyle->listing($spacedUnnecessarySkips);
76+
}
77+
5078
public function reportSkippedNeverRegisteredRules(): int
5179
{
5280
$registeredRules = SimpleParameterProvider::provideArrayParameter(Option::REGISTERED_RECTOR_RULES);
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rector\Reporting;
6+
7+
use Nette\Utils\FileSystem;
8+
use Rector\Application\FileProcessor;
9+
use Rector\Application\Provider\CurrentFileProvider;
10+
use Rector\FileSystem\FilePathHelper;
11+
use Rector\Skipper\Skipper\Skipper;
12+
use Rector\ValueObject\Application\File;
13+
use Rector\ValueObject\Configuration;
14+
15+
/**
16+
* Re-runs each rule-scoped skip on its exact file with skipping off. A skip whose rule still does
17+
* not change the file never prevented anything and can be removed. The re-processing is forced to a
18+
* dry run, so it never writes, no matter the mode of the real run.
19+
*
20+
* @see \Rector\Tests\Reporting\NeededSkipVerifierTest
21+
*/
22+
final readonly class NeededSkipVerifier
23+
{
24+
public function __construct(
25+
private Skipper $skipper,
26+
private FileProcessor $fileProcessor,
27+
private CurrentFileProvider $currentFileProvider,
28+
private FilePathHelper $filePathHelper,
29+
) {
30+
}
31+
32+
/**
33+
* Unnecessary skips grouped under their rule, ready for "->listing()".
34+
*
35+
* @return string[]
36+
*/
37+
public function verify(): array
38+
{
39+
$skippedFilePathsByRule = $this->skipper->provideSkippedFilePathsByRule();
40+
if ($skippedFilePathsByRule === []) {
41+
return [];
42+
}
43+
44+
$changedRulesByFilePath = $this->resolveChangedRulesByFilePath($skippedFilePathsByRule);
45+
46+
$unnecessarySkips = [];
47+
foreach ($skippedFilePathsByRule as $rectorClass => $filePaths) {
48+
$unnecessaryRelativePaths = [];
49+
foreach ($filePaths as $filePath) {
50+
// file could not be re-processed (e.g. parse error), keep the skip to stay safe
51+
if (! array_key_exists($filePath, $changedRulesByFilePath)) {
52+
continue;
53+
}
54+
55+
// the rule changed the file, so the skip really prevents a change - keep it
56+
if (in_array($rectorClass, $changedRulesByFilePath[$filePath], true)) {
57+
continue;
58+
}
59+
60+
$unnecessaryRelativePaths[] = $this->filePathHelper->relativePath($filePath);
61+
}
62+
63+
if ($unnecessaryRelativePaths === []) {
64+
continue;
65+
}
66+
67+
// rule on its own line, with each unnecessary path nested below it as a sub-item
68+
$unnecessarySkips[] = $rectorClass . ':' . "\n * " . implode("\n * ", $unnecessaryRelativePaths);
69+
}
70+
71+
return $unnecessarySkips;
72+
}
73+
74+
/**
75+
* @param array<class-string, string[]> $skippedFilePathsByRule
76+
* @return array<string, string[]> real file path => rule classes that changed it
77+
*/
78+
private function resolveChangedRulesByFilePath(array $skippedFilePathsByRule): array
79+
{
80+
$uniqueFilePaths = [];
81+
foreach ($skippedFilePathsByRule as $filePaths) {
82+
foreach ($filePaths as $filePath) {
83+
$uniqueFilePaths[$filePath] = true;
84+
}
85+
}
86+
87+
// force a dry run, so re-processing detects the change but never writes the skipped file
88+
$dryRunConfiguration = new Configuration(isDryRun: true);
89+
90+
$this->skipper->startVerifyingSkips();
91+
92+
$changedRulesByFilePath = [];
93+
try {
94+
foreach (array_keys($uniqueFilePaths) as $filePath) {
95+
$file = new File($filePath, FileSystem::read($filePath));
96+
$this->currentFileProvider->setFile($file);
97+
98+
$fileProcessResult = $this->fileProcessor->processFile($file, $dryRunConfiguration);
99+
100+
// a broken file is not verifiable, leave it out so its skips are kept
101+
if ($fileProcessResult->getSystemErrors() !== []) {
102+
continue;
103+
}
104+
105+
$fileDiff = $fileProcessResult->getFileDiff();
106+
$changedRulesByFilePath[$filePath] = $fileDiff?->getRectorClasses() ?? [];
107+
}
108+
} finally {
109+
$this->skipper->stopVerifyingSkips();
110+
}
111+
112+
return $changedRulesByFilePath;
113+
}
114+
}

‎src/Skipper/Skipper/Skipper.php‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,17 @@ final class Skipper
3131
*/
3232
private array $usedSkips = [];
3333

34+
/**
35+
* Real file paths skipped per rule, kept only when unused-skip reporting is on, so a matched
36+
* skip can be re-run on the exact file to learn whether it ever prevented a change.
37+
*
38+
* @var array<class-string, array<string, true>>
39+
*/
40+
private array $skippedFilePathsByRule = [];
41+
42+
// flipped on while the needed-skip verification re-runs rules with skipping off
43+
private bool $isVerifyingSkips = false;
44+
3445
public function __construct(
3546
private readonly PathSkipper $pathSkipper,
3647
private readonly FileInfoMatcher $fileInfoMatcher,
@@ -51,15 +62,55 @@ public function shouldSkipFilePath(string $filePath): bool
5162

5263
public function shouldSkipRectorAndFile(object $rector, string $filePath): bool
5364
{
65+
// verification re-runs every rule with skipping off, to learn which skips really matter
66+
if ($this->isVerifyingSkips) {
67+
return false;
68+
}
69+
5470
$skipMatch = $this->matchSkip($rector, $filePath);
5571
if (! $skipMatch instanceof SkipMatch) {
5672
return false;
5773
}
5874

5975
$this->markSkipUsed($skipMatch);
76+
77+
// remember the real skipped file so a rule-scoped skip can be verified later; only path
78+
// skips are re-runnable, and only when reporting is on, so normal runs pay nothing
79+
if ($skipMatch->getMatchedPath() !== null && SimpleParameterProvider::provideBoolParameter(
80+
Option::REPORT_UNUSED_SKIPS,
81+
false
82+
)) {
83+
$this->skippedFilePathsByRule[$rector::class][$filePath] = true;
84+
}
85+
6086
return true;
6187
}
6288

89+
public function startVerifyingSkips(): void
90+
{
91+
$this->isVerifyingSkips = true;
92+
}
93+
94+
public function stopVerifyingSkips(): void
95+
{
96+
$this->isVerifyingSkips = false;
97+
}
98+
99+
/**
100+
* Real file paths that were skipped per rule-scoped path skip during the run.
101+
*
102+
* @return array<class-string, string[]>
103+
*/
104+
public function provideSkippedFilePathsByRule(): array
105+
{
106+
$skippedFilePathsByRule = [];
107+
foreach ($this->skippedFilePathsByRule as $rectorClass => $filePaths) {
108+
$skippedFilePathsByRule[$rectorClass] = array_keys($filePaths);
109+
}
110+
111+
return $skippedFilePathsByRule;
112+
}
113+
63114
/**
64115
* Match a class/path skip without marking it used. Callers that can only tell whether the skip
65116
* actually prevented a change later on must mark it used themselves via markSkipUsed().

‎tests/Console/Command/ValidateConfigCommandTest.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use Rector\Php85\Rector\FuncCall\OrdSingleByteRector;
1414
use Rector\Reporting\DeprecatedRulesReporter;
1515
use Rector\Reporting\MissConfigurationReporter;
16+
use Rector\Reporting\NeededSkipVerifier;
1617
use Rector\Reporting\UnusedSkipResolver;
1718
use Rector\Skipper\Skipper\Skipper;
1819
use Rector\Testing\PHPUnit\AbstractLazyTestCase;
@@ -53,6 +54,7 @@ protected function setUp(): void
5354
$symfonyStyle,
5455
new VendorMissAnalyseGuard(),
5556
$this->make(UnusedSkipResolver::class),
57+
$this->make(NeededSkipVerifier::class),
5658
),
5759
$this->make(Skipper::class),
5860
);

‎tests/Reporting/MissConfigurationReporterTest.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use Rector\Php85\Rector\FuncCall\OrdSingleByteRector;
1111
use Rector\PostRector\Rector\NameImportingPostRector;
1212
use Rector\Reporting\MissConfigurationReporter;
13+
use Rector\Reporting\NeededSkipVerifier;
1314
use Rector\Reporting\UnusedSkipResolver;
1415
use Rector\Testing\PHPUnit\AbstractLazyTestCase;
1516
use Rector\Tests\Skipper\Skipper\Fixture\Element\FifthElement;
@@ -45,6 +46,7 @@ protected function setUp(): void
4546
$symfonyStyle,
4647
new VendorMissAnalyseGuard(),
4748
$this->make(UnusedSkipResolver::class),
49+
$this->make(NeededSkipVerifier::class),
4850
);
4951

5052
SimpleParameterProvider::setParameter(Option::SKIP, [
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rector\Tests\Reporting;
6+
7+
use Nette\Utils\FileSystem;
8+
use Rector\Config\RectorConfig;
9+
use Rector\Configuration\Option;
10+
use Rector\Configuration\Parameter\SimpleParameterProvider;
11+
use Rector\DependencyInjection\LazyContainerFactory;
12+
use Rector\Reporting\NeededSkipVerifier;
13+
use Rector\Skipper\Skipper\Skipper;
14+
use Rector\Testing\PHPUnit\AbstractLazyTestCase;
15+
use Rector\Tests\Reporting\Source\MakeClassFinalRector;
16+
17+
final class NeededSkipVerifierTest extends AbstractLazyTestCase
18+
{
19+
private string $tempDirectory;
20+
21+
protected function setUp(): void
22+
{
23+
parent::setUp();
24+
25+
$this->tempDirectory = sys_get_temp_dir() . '/rector_needed_skip_' . uniqid();
26+
}
27+
28+
protected function tearDown(): void
29+
{
30+
FileSystem::delete($this->tempDirectory);
31+
32+
SimpleParameterProvider::setParameter(Option::SKIP, []);
33+
SimpleParameterProvider::setParameter(Option::REPORT_UNUSED_SKIPS, false);
34+
}
35+
36+
public function testReportsSkipThatRuleWouldNotHaveChanged(): void
37+
{
38+
// the rule would turn this into "final class", so skipping it really prevents a change
39+
$neededFilePath = $this->tempDirectory . '/needed_skip.php';
40+
FileSystem::write($neededFilePath, '<?php class SomeClass {}', null);
41+
42+
// already final, so the rule changes nothing - skipping it is unnecessary
43+
$unnecessaryFilePath = $this->tempDirectory . '/unnecessary_skip.php';
44+
FileSystem::write($unnecessaryFilePath, '<?php final class AlreadyFinal {}', null);
45+
46+
SimpleParameterProvider::setParameter(Option::REPORT_UNUSED_SKIPS, true);
47+
SimpleParameterProvider::setParameter(Option::SKIP, [
48+
MakeClassFinalRector::class => [$neededFilePath, $unnecessaryFilePath],
49+
]);
50+
51+
$rectorConfig = $this->createContainerWithRule();
52+
53+
// simulate the run skipping the rule on both files, so they are captured for verification
54+
$skipper = $rectorConfig->make(Skipper::class);
55+
$rule = $rectorConfig->make(MakeClassFinalRector::class);
56+
$this->assertTrue($skipper->shouldSkipRectorAndFile($rule, $neededFilePath));
57+
$this->assertTrue($skipper->shouldSkipRectorAndFile($rule, $unnecessaryFilePath));
58+
59+
$neededSkipVerifier = $rectorConfig->make(NeededSkipVerifier::class);
60+
$unnecessarySkips = $neededSkipVerifier->verify();
61+
62+
// one rule group, listing only the unnecessary file
63+
$this->assertCount(1, $unnecessarySkips);
64+
$this->assertStringContainsString(MakeClassFinalRector::class, $unnecessarySkips[0]);
65+
$this->assertStringContainsString('unnecessary_skip.php', $unnecessarySkips[0]);
66+
$this->assertStringNotContainsString('needed_skip.php', $unnecessarySkips[0]);
67+
68+
// the verification is forced to a dry run, so the skipped file on disk stays untouched
69+
$this->assertSame('<?php class SomeClass {}', FileSystem::read($neededFilePath));
70+
}
71+
72+
public function testReportsNothingWithoutCapturedSkips(): void
73+
{
74+
$rectorConfig = $this->createContainerWithRule();
75+
76+
$neededSkipVerifier = $rectorConfig->make(NeededSkipVerifier::class);
77+
$this->assertSame([], $neededSkipVerifier->verify());
78+
}
79+
80+
private function createContainerWithRule(): RectorConfig
81+
{
82+
$rectorConfig = new LazyContainerFactory()->create();
83+
$rectorConfig->rule(MakeClassFinalRector::class);
84+
$rectorConfig->boot();
85+
86+
return $rectorConfig;
87+
}
88+
}

0 commit comments

Comments
 (0)