fix(tia): restrict Xdebug coverage to the source scope before tracing (#2091)

* fix(tia): restrict Xdebug coverage to the source scope before tracing

* fix(tia): set the Xdebug exclude filter before the bootstrap and keep case twins traced

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
This commit is contained in:
Jhon Farias
2026-12-04 09:43:25 +01:00
committed by GitHub
parent 586add8ff2
commit cd5bae7e91
10 changed files with 395 additions and 28 deletions
+4 -4
View File
@@ -1218,7 +1218,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return $arguments;
}
$recorder->activate();
$recorder->activate($this->configuration);
$this->recordingActive = true;
return $arguments;
@@ -1290,7 +1290,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return $arguments;
}
$recorder->activate();
$recorder->activate($this->configuration);
$this->recordingActive = true;
return $arguments;
@@ -1428,7 +1428,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
if ($this->piggybackCoverage) {
$this->recorder->activateLinkTracking();
} else {
$this->recorder->activate();
$this->recorder->activate($this->configuration);
}
$this->recordingActive = true;
@@ -1716,7 +1716,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return $arguments;
}
$recorder->activate();
$recorder->activate($this->configuration);
$this->recordingActive = true;
if ($this->driftLabel !== null || $this->freshGraphReason !== null) {
+51 -4
View File
@@ -4,9 +4,20 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia;
use PHPUnit\Event\Dispatcher;
use PHPUnit\Event\DispatchingEmitter;
use PHPUnit\Event\Emitter;
use PHPUnit\Event\Event;
use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\Event\Telemetry\System;
use PHPUnit\Event\Telemetry\SystemCpuTimeMeter;
use PHPUnit\Event\Telemetry\SystemGarbageCollectorStatusProvider;
use PHPUnit\Event\Telemetry\SystemMemoryMeter;
use PHPUnit\Event\Telemetry\SystemStopWatch;
use PHPUnit\TextUI\CliArguments\Builder;
use PHPUnit\TextUI\CliArguments\XmlConfigurationFileFinder;
use PHPUnit\TextUI\XmlConfiguration\DefaultConfiguration;
use PHPUnit\TextUI\XmlConfiguration\Loader;
use Throwable;
/**
@@ -18,16 +29,18 @@ final readonly class ConfigurationFile
private const array DEFAULT_NAMES = ['phpunit.xml', 'phpunit.dist.xml', 'phpunit.xml.dist'];
private const array VALUE_OPTIONS = ['--configuration', '--bootstrap', '--include-path'];
private const array VALUE_OPTIONS = ['--configuration', '--bootstrap', '--include-path', '--coverage-filter'];
/**
* @param list<string>|null $includePaths
* @param list<string> $coverageFilter
*/
private function __construct(
private ?string $path,
private bool $suppressed,
private ?string $bootstrap = null,
private ?array $includePaths = null,
private array $coverageFilter = [],
) {}
/**
@@ -45,19 +58,20 @@ final readonly class ConfigurationFile
$includePaths = $configuration->hasIncludePath()
? array_map(self::resolved(...), explode(PATH_SEPARATOR, $configuration->includePath()))
: null;
$coverageFilter = $configuration->hasCoverageFilter() ? $configuration->coverageFilter() : [];
if (! $configuration->hasConfigurationFile() && ! $configuration->useDefaultConfiguration()) {
return new self(null, true, $bootstrap, $includePaths);
return new self(null, true, $bootstrap, $includePaths, $coverageFilter);
}
$file = new XmlConfigurationFileFinder()->find($configuration);
$path = $file === false ? false : realpath($file);
if ($path !== false && $generatedPath !== null && $path === realpath($generatedPath)) {
return new self(null, false, $bootstrap, $includePaths);
return new self(null, false, $bootstrap, $includePaths, $coverageFilter);
}
return new self($path === false ? null : $path, false, $bootstrap, $includePaths);
return new self($path === false ? null : $path, false, $bootstrap, $includePaths, $coverageFilter);
}
public static function at(string $path): self
@@ -70,6 +84,23 @@ final readonly class ConfigurationFile
return new self(null, false);
}
public function sourceScope(string $projectRoot): ?SourceScope
{
$path = $this->suppressed ? null : ($this->path ?? $this->defaultIn($projectRoot));
if ($path === null) {
return SourceScope::fromSource($projectRoot, DefaultConfiguration::create()->source(), $this->coverageFilter);
}
try {
$source = new Loader($this->silentEmitter())->load($path)->source();
} catch (Throwable) {
return null;
}
return SourceScope::fromSource($projectRoot, $source, $this->coverageFilter);
}
public function bootstrapFingerprint(string $projectRoot): ?string
{
return $this->bootstrap === null ? null : $this->relativeTo($projectRoot, $this->bootstrap);
@@ -174,6 +205,22 @@ final readonly class ConfigurationFile
return $argument;
}
private function silentEmitter(): Emitter
{
return new DispatchingEmitter(
new class implements Dispatcher
{
public function dispatch(Event $event): void {}
},
new System(
new SystemStopWatch,
new SystemMemoryMeter,
new SystemGarbageCollectorStatusProvider,
new SystemCpuTimeMeter,
),
);
}
private function withForwardSlashes(string $path): string
{
return DIRECTORY_SEPARATOR === '\\' ? str_replace('\\', '/', $path) : $path;
+36 -1
View File
@@ -47,13 +47,19 @@ final class Recorder
private ?SourceScope $sourceScope = null;
private bool $coverageFilterApplied = false;
/** @var (Closure(string): bool)|null */
private ?Closure $recordsTestFile = null;
public function activate(): void
public function activate(?ConfigurationFile $configuration = null): void
{
$this->active = true;
$this->captureCoverage = true;
if ($configuration instanceof ConfigurationFile) {
$this->restrictCoverageToSourceScope($configuration);
}
}
public function activateLinkTracking(): void
@@ -427,6 +433,30 @@ final class Recorder
return $out;
}
private function restrictCoverageToSourceScope(ConfigurationFile $configuration): void
{
if ($this->coverageFilterApplied || ! $this->driverAvailable() || $this->driver !== 'xdebug') {
return;
}
$projectRoot = TestSuite::getInstance()->rootPath;
$scope = $configuration->sourceScope($projectRoot);
if (! $scope instanceof SourceScope) {
return;
}
$excludedPaths = $scope->coverageExcludePaths($projectRoot);
if ($excludedPaths === []) {
return;
}
\xdebug_set_filter(\XDEBUG_FILTER_CODE_COVERAGE, \XDEBUG_PATH_EXCLUDE, $excludedPaths);
$this->coverageFilterApplied = true;
}
private function sourceScope(): SourceScope
{
return $this->sourceScope ??= SourceScope::fromProjectRoot(TestSuite::getInstance()->rootPath);
@@ -436,6 +466,11 @@ final class Recorder
{
ReadCapture::stop();
if ($this->coverageFilterApplied) {
\xdebug_set_filter(\XDEBUG_FILTER_CODE_COVERAGE, \XDEBUG_FILTER_NONE, []);
$this->coverageFilterApplied = false;
}
$this->currentTestFile = null;
$this->perTestFiles = [];
$this->perTestTables = [];
+113 -16
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia;
use PHPUnit\TextUI\Configuration\Registry;
use PHPUnit\TextUI\Configuration\Source;
use Throwable;
/**
@@ -52,27 +53,44 @@ final class SourceScope
public static function fromProjectRoot(string $projectRoot): self
{
$phpunitIncludes = [];
$phpunitExcludes = [];
try {
$source = Registry::get()->source();
foreach ($source->includeDirectories() as $dir) {
$phpunitIncludes[] = self::normalise($dir->path());
}
foreach ($source->excludeDirectories() as $dir) {
$phpunitExcludes[] = [
'path' => self::normalise(@realpath($dir->path()) ?: $dir->path()),
'prefix' => $dir->prefix(),
'suffix' => $dir->suffix(),
];
}
} catch (Throwable) {
//
return self::build($projectRoot, [], []);
}
return self::fromSource($projectRoot, $source, []);
}
/**
* @param list<string> $coverageFilter
*/
public static function fromSource(string $projectRoot, Source $source, array $coverageFilter): self
{
$phpunitIncludes = array_map(self::normalise(...), $coverageFilter);
$phpunitExcludes = [];
foreach ($source->includeDirectories() as $dir) {
$phpunitIncludes[] = self::normalise($dir->path());
}
foreach ($source->excludeDirectories() as $dir) {
$phpunitExcludes[] = [
'path' => self::normalise(@realpath($dir->path()) ?: $dir->path()),
'prefix' => $dir->prefix(),
'suffix' => $dir->suffix(),
];
}
return self::build($projectRoot, $phpunitIncludes, $phpunitExcludes);
}
/**
* @param list<string> $phpunitIncludes
* @param list<array{path: string, prefix: string, suffix: string}> $phpunitExcludes
*/
private static function build(string $projectRoot, array $phpunitIncludes, array $phpunitExcludes): self
{
$rootIncludes = self::topLevelProjectDirs($projectRoot);
$includes = array_values(array_unique([...$phpunitIncludes, ...$rootIncludes]));
@@ -112,6 +130,30 @@ final class SourceScope
return array_values(array_unique($out));
}
/**
* @return list<string>
*/
public function coverageExcludePaths(string $projectRoot): array
{
$out = [];
foreach (self::noiseDirectories() as $relative) {
$real = @realpath($projectRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative));
if ($real === false || ! is_dir($real)) {
continue;
}
$directory = self::normalise($real);
if ($this->rejectsEveryFileIn($directory) && ! $this->hasCaseTwin($directory)) {
$out[] = $directory.DIRECTORY_SEPARATOR;
}
}
return $out;
}
public function contains(string $absoluteFile): bool
{
if (isset($this->containsCache[$absoluteFile])) {
@@ -194,6 +236,61 @@ final class SourceScope
return $out;
}
private function rejectsEveryFileIn(string $directory): bool
{
foreach ($this->includes as $included) {
if ($this->overlapsIgnoringCase($directory, $included) && ! $this->overlaps($directory, $included)) {
return false;
}
}
foreach ($this->excludes as $excluded) {
if ($excluded['prefix'] === '' && $excluded['suffix'] === '' && $this->startsWithDir($directory, $excluded['path'])) {
return true;
}
}
return array_all($this->includes, fn (string $included): bool => ! $this->overlapsIgnoringCase($directory, $included));
}
private function hasCaseTwin(string $directory): bool
{
$segments = explode(DIRECTORY_SEPARATOR, $directory);
$parent = array_shift($segments).DIRECTORY_SEPARATOR;
foreach ($segments as $segment) {
if ($segment === '') {
continue;
}
$entries = @scandir($parent);
if ($entries === false) {
return true;
}
foreach ($entries as $entry) {
if ($entry !== $segment && strtolower($entry) === strtolower($segment)) {
return true;
}
}
$parent = rtrim($parent, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$segment;
}
return false;
}
private function overlaps(string $first, string $second): bool
{
return $this->startsWithDir($first, $second) || $this->startsWithDir($second, $first);
}
private function overlapsIgnoringCase(string $first, string $second): bool
{
return $this->overlaps(strtolower($first), strtolower($second));
}
private static function normalise(string $path): string
{
return rtrim($path, '/\\');