diff --git a/src/Plugins/Tia.php b/src/Plugins/Tia.php index 62396dd3..013d2313 100644 --- a/src/Plugins/Tia.php +++ b/src/Plugins/Tia.php @@ -27,6 +27,7 @@ use Pest\Plugins\Tia\CiBranch; use Pest\Plugins\Tia\ConfigurationFile; use Pest\Plugins\Tia\Contracts\State; use Pest\Plugins\Tia\CoverageCollector; +use Pest\Plugins\Tia\ExternalSources; use Pest\Plugins\Tia\Fingerprint; use Pest\Plugins\Tia\Graph; use Pest\Plugins\Tia\JsModuleGraph; @@ -192,6 +193,16 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument private ?string $startSha = null; + /** + * @var array|null + */ + private ?array $ignoredInputsAtStart = null; + + /** + * @var array + */ + private array $ignoredInputsChangedDuringRun = []; + private bool $piggybackCoverage = false; private bool $recordingActive = false; @@ -204,6 +215,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument private bool $writesSuppressed = false; + private bool $dirtyExternalSourcesResolved = false; + + /** @var array|null */ + private ?array $dirtyExternalSources = null; + private bool $resultsOnlyWrites = false; private bool $flushesWorkerResults = false; @@ -494,6 +510,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $configurationPlugin = Container::getInstance()->get(Configuration::class); assert($configurationPlugin instanceof Configuration); $this->configuration = ConfigurationFile::fromArguments($arguments, $configurationPlugin->generatedConfigurationPath()); + ExternalSources::pinWorkingDirectory(TestSuite::getInstance()->rootPath); $isWorker = Parallel::isWorker(); $recordingGlobal = $isWorker && (string) Parallel::getGlobal(self::RECORDING_GLOBAL) === '1'; @@ -653,7 +670,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $changedFiles = new ChangedFiles($projectRoot); $currentSha = $changedFiles->currentSha(); - $currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration); + $currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration, $this->originalArguments); if ($this->structuralFingerprintShifted($currentFingerprint)) { $this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.'); @@ -672,12 +689,20 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return; } + if ($this->externalSourcesChangedDuringRun($projectRoot)) { + $this->renderExternalSourcesChangedDuringRun('discarding recorded edges'); + $recorder->reset(); + $this->coverageCollector->reset(); + + return; + } + $graph = $this->loadGraph($projectRoot) ?? new Graph($projectRoot); $graph->setFingerprint($currentFingerprint); $graph->setRecordedAtSha($this->branch, $currentSha); $graph->setLastRunTree( $this->branch, - $changedFiles->snapshotTree($changedFiles->since($currentSha) ?? []), + $changedFiles->baselineTree($currentSha, ExternalSources::ignoredInputs($projectRoot, $this->originalArguments)), ); $graph->replaceEdges($perTest, keepExisting: $this->piggybackCoverage); $graph->replaceTestTables($perTestTables); @@ -747,7 +772,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $changedFiles = new ChangedFiles($projectRoot); $currentSha = $changedFiles->currentSha(); - $currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration); + $currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration, $this->originalArguments); if ($this->structuralFingerprintShifted($currentFingerprint)) { $this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.'); @@ -770,12 +795,22 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return $exitCode; } + if ($this->externalSourcesChangedDuringRun($projectRoot)) { + $this->renderExternalSourcesChangedDuringRun('discarding recorded edges'); + + foreach ($partialKeys as $key) { + $this->state->delete($key); + } + + return $exitCode; + } + $graph = $this->loadGraph($projectRoot) ?? new Graph($projectRoot); $graph->setFingerprint($currentFingerprint); $graph->setRecordedAtSha($this->branch, $currentSha); $graph->setLastRunTree( $this->branch, - $changedFiles->snapshotTree($changedFiles->since($currentSha) ?? []), + $changedFiles->baselineTree($currentSha, ExternalSources::ignoredInputs($projectRoot, $this->originalArguments)), ); [$finalised, $finalisedTables, $finalisedInertia] = $this->consumePartials($partialKeys); @@ -892,9 +927,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument : new TiaRequiresRemote); } - $fingerprint = Fingerprint::compute($projectRoot, $this->configuration); + $fingerprint = Fingerprint::compute($projectRoot, $this->configuration, $this->originalArguments); $this->startFingerprint = $fingerprint; $this->startSha = new ChangedFiles($projectRoot)->currentSha(); + $this->ignoredInputsAtStart = $this->ignoredInputHashes($projectRoot); if ($forceRebuild && $this->canRebuildGraph()) { $this->purgeState(); @@ -930,6 +966,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument } } + if ($this->holdsDirtyExternalSources($projectRoot) || $this->holdsUnverifiableExternalSources($projectRoot)) { + return $arguments; + } + $uncommittedPhpChanges = $this->uncommittedPhpChangesOutsideProject($projectRoot); if ($uncommittedPhpChanges !== []) { @@ -965,6 +1005,134 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return $this->enterRecordMode($arguments); } + private function holdsUnverifiableExternalSources(string $projectRoot): bool + { + $unverifiable = ExternalSources::unverifiable($projectRoot, $this->originalArguments); + + if ($unverifiable === []) { + return false; + } + + $this->writesSuppressed = true; + + $this->renderBadge('WARN', sprintf( + 'This project loads %d path%s whose changes git cannot report.', + count($unverifiable), + count($unverifiable) === 1 ? '' : 's', + )); + + foreach (array_slice($unverifiable, 0, $this->output->isVerbose() ? count($unverifiable) : 5) as $path) { + $this->output->writeln(sprintf(' %s', $path)); + } + + $this->renderChild('Running the full suite, and recording nothing — git reports no change there, so no result could stand behind a replay.'); + $this->renderChild('Move what the project loads into the repository to let TIA select tests again.'); + + return true; + } + + private function holdsDirtyExternalSources(string $projectRoot): bool + { + $dirty = $this->dirtyExternalSources($projectRoot); + + if ($dirty === []) { + return false; + } + + $this->writesSuppressed = true; + + if ($dirty === null) { + $this->renderBadge('WARN', 'Git could not read the working tree of the code this project loads from outside its root.'); + $this->renderChild('Running the full suite, and recording nothing.'); + + return true; + } + + $this->renderBadge('WARN', sprintf( + 'Detected %d uncommitted change%s this project loads from outside its root.', + count($dirty), + count($dirty) === 1 ? '' : 's', + )); + + foreach (array_slice($dirty, 0, $this->output->isVerbose() ? count($dirty) : 5) as $file) { + $this->output->writeln(sprintf(' %s', $file)); + } + + $this->renderChild('Running the full suite, and recording nothing — git stops reporting such an edit once it is undone.'); + $this->renderChild('Commit what you changed there to let a run leave a baseline behind.'); + + return true; + } + + private function externalSourcesChangedDuringRun(string $projectRoot): bool + { + $this->dirtyExternalSourcesResolved = false; + $this->ignoredInputsChangedDuringRun = $this->ignoredInputsAtStart === null + ? [] + : new ChangedFiles($projectRoot)->changedExternalInputs($this->ignoredInputsAtStart, $this->ignoredInputHashes($projectRoot)); + + return $this->dirtyExternalSources($projectRoot) !== [] || $this->ignoredInputsChangedDuringRun !== []; + } + + /** + * @return array + */ + private function ignoredInputHashes(string $projectRoot): array + { + $ignored = ExternalSources::ignoredState($projectRoot, $this->originalArguments); + + return new ChangedFiles($projectRoot)->externalInputHashes($ignored['inputs'], $ignored['repositories'], [...$ignored['failed'], ...$ignored['unreadable']]); + } + + private function renderExternalSourcesChangedDuringRun(string $consequence): void + { + $this->renderBadge('WARN', 'Code this project loads from outside its root changed during the run — '.$consequence.'.'); + + if ($this->ignoredInputsChangedDuringRun !== []) { + foreach (array_slice($this->ignoredInputsChangedDuringRun, 0, $this->output->isVerbose() ? count($this->ignoredInputsChangedDuringRun) : 5) as $file) { + $this->output->writeln(sprintf(' %s', $file)); + } + + $this->renderChild('These files changed during the run, or git stopped ignoring them. Keep what the run writes out of the paths this project loads to let TIA record again.'); + } + + if ($this->ignoredInputsChangedDuringRun === [] || $this->dirtyExternalSources !== []) { + $this->renderChild('Re-run --tia after your edits settle to record a fresh dependency graph.'); + } + } + + /** + * @return array|null + */ + private function dirtyExternalSources(string $projectRoot): ?array + { + if ($this->dirtyExternalSourcesResolved) { + return $this->dirtyExternalSources; + } + + $this->dirtyExternalSourcesResolved = true; + + if (ExternalSources::rootsFor($projectRoot, $this->originalArguments) === []) { + return $this->dirtyExternalSources = []; + } + + $changedFiles = new ChangedFiles($projectRoot); + + try { + $changedFiles->since(null); + } catch (MissingDependency) { + return $this->dirtyExternalSources = []; + } catch (TiaGitFailed) { + return $this->dirtyExternalSources = null; + } + + return $this->dirtyExternalSources = ExternalSources::matching( + $projectRoot, + $changedFiles->outsideProjectDirty(), + $this->originalArguments, + ); + } + private function purgeState(): void { foreach ([ @@ -1119,17 +1287,60 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $outsideProject = $changedFiles->outsideProject(); + [$changed, $changedExternalInputs] = $changedFiles->changedSinceLastRun( + $changed, + ExternalSources::ignoredInputs($projectRoot, $this->originalArguments), + $graph->lastRunTree($this->branch), + ); + + $externalChanges = array_values(array_unique([ + ...ExternalSources::matching($projectRoot, $outsideProject, $this->originalArguments), + ...$changedExternalInputs, + ])); + + if ($externalChanges !== []) { + $this->renderBadge('WARN', sprintf( + 'Detected changes in %d file%s this project loads from outside its root.', + count($externalChanges), + count($externalChanges) === 1 ? '' : 's', + )); + + foreach (array_slice($externalChanges, 0, $this->output->isVerbose() ? count($externalChanges) : 5) as $file) { + $this->output->writeln(sprintf(' %s', $file)); + } + + if ($this->canRebuildGraph()) { + $this->deleteState(self::KEY_GRAPH); + $this->deleteState(self::KEY_COVERAGE_CACHE); + + $this->freshGraphReason = 'code this project loads from outside its root changed'; + + return $this->enterRecordMode($arguments); + } + + $this->requestWorkerResults(); + + $this->renderChild('Running the full suite — the dependency graph only reaches files under the project root.'); + + if ($this->piggybackCoverage) { + $this->renderChild('Run --tia without --coverage to record a fresh dependency graph.'); + + return $arguments; + } + + $this->fullSuiteFallbackRan = true; + + $this->renderChild('Install / enable pcov or xdebug (mode: coverage) so edges can be safely refreshed after changes outside the project root.'); + + return $arguments; + } + $phpChangesOutsideProject = $this->phpFiles($outsideProject); if ($phpChangesOutsideProject !== []) { return $this->runFullSuiteForPhpChangesOutsideProject($phpChangesOutsideProject, $arguments); } - $changed = $changedFiles->filterUnchangedSinceLastRun( - $changed, - $graph->lastRunTree($this->branch), - ); - $hasProjectPhpSourceChanges = $this->hasProjectPhpSourceChanges($changed); $coverageAvailable = $this->piggybackCoverage || $this->recorder->driverAvailable(); @@ -1874,12 +2085,20 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return; } + if ($this->externalSourcesChangedDuringRun($projectRoot)) { + $this->renderExternalSourcesChangedDuringRun('keeping the baseline from before the run'); + + return; + } + if ($currentSha !== null) { $graph->setRecordedAtSha($this->branch, $currentSha); } - $workingTreeFiles = $changedFiles->since($currentSha) ?? []; - $graph->setLastRunTree($this->branch, $changedFiles->snapshotTree($workingTreeFiles)); + $graph->setLastRunTree( + $this->branch, + $changedFiles->baselineTree($currentSha, ExternalSources::ignoredInputs($projectRoot, $this->originalArguments)), + ); $this->saveGraph($graph); } @@ -2003,6 +2222,13 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return; } + if ($this->externalSourcesChangedDuringRun($projectRoot) + || ExternalSources::unverifiable($projectRoot, $this->originalArguments) !== []) { + $collector->reset(); + + return; + } + try { $this->resolveBranch($projectRoot); } catch (MissingDependency|TiaGitFailed) { @@ -2390,6 +2616,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument 'pest_factory' => 'Pest internals', 'pest_method_factory' => 'Pest internals', 'project_prefix' => 'project location in the repository', + 'external_roots' => 'the roots this project loads from outside itself', + 'include_path' => 'the include path', ]; $seen = []; diff --git a/src/Plugins/Tia/ChangedFiles.php b/src/Plugins/Tia/ChangedFiles.php index 8d6f77bf..c86e63b5 100644 --- a/src/Plugins/Tia/ChangedFiles.php +++ b/src/Plugins/Tia/ChangedFiles.php @@ -77,17 +77,17 @@ final class ChangedFiles /** * @return array */ - public function outsideProject(): array + public function outsideProjectDirty(): array { - return Arr::stringKeys($this->outsideProject); + return Arr::stringKeys($this->outsideProjectDirty); } /** * @return array */ - public function outsideProjectDirty(): array + public function outsideProject(): array { - return Arr::stringKeys($this->outsideProjectDirty); + return Arr::stringKeys($this->outsideProject); } /** @@ -121,6 +121,100 @@ final class ChangedFiles return $remaining; } + /** + * @param array $repositoryRelativeInputs + * @return array + */ + public function baselineTree(?string $sha, array $repositoryRelativeInputs): array + { + return $this->snapshotTree([...($this->since($sha) ?? []), ...$this->externalKeys($repositoryRelativeInputs)]); + } + + /** + * @param array $repositoryRelativeInputs + * @param array $repositoryRelativeRepositories + * @param array $repositoryRelativeUnlisted + * @return array + */ + public function externalInputHashes(array $repositoryRelativeInputs, array $repositoryRelativeRepositories = [], array $repositoryRelativeUnlisted = []): array + { + $hashes = $this->snapshotTree($this->externalKeys($repositoryRelativeInputs)); + + foreach ($this->externalKeys($repositoryRelativeRepositories) as $key) { + $hashes[$key] = 'repository'; + } + + foreach ($this->externalKeys($repositoryRelativeUnlisted) as $key) { + $hashes[$key] = 'unlisted'; + } + + return $hashes; + } + + /** + * @param array $before + * @param array $after + * @return array + */ + public function changedExternalInputs(array $before, array $after): array + { + $parent = $this->parentPath(); + $changed = []; + + foreach (Arr::stringKeys([...$before, ...$after]) as $key) { + if (($before[$key] ?? null) !== ($after[$key] ?? null)) { + $changed[] = $parent !== '' && str_starts_with($key, $parent) ? substr($key, strlen($parent)) : $key; + } + } + + sort($changed); + + return $changed; + } + + /** + * @param array $files + * @param array $repositoryRelativeInputs + * @param array $lastRunTree + * @return array{0: array, 1: array} + */ + public function changedSinceLastRun(array $files, array $repositoryRelativeInputs, array $lastRunTree): array + { + $parent = $this->parentPath(); + $projectFiles = []; + $externalInputsChanged = []; + + foreach ($this->filterUnchangedSinceLastRun([...$files, ...$this->externalKeys($repositoryRelativeInputs)], $lastRunTree) as $file) { + if ($parent !== '' && str_starts_with($file, $parent)) { + $externalInputsChanged[] = substr($file, strlen($parent)); + } else { + $projectFiles[] = $file; + } + } + + return [$projectFiles, $externalInputsChanged]; + } + + /** + * @param array $repositoryRelativeInputs + * @return array + */ + private function externalKeys(array $repositoryRelativeInputs): array + { + $parent = $this->parentPath(); + + if ($parent === '') { + return []; + } + + return array_map(static fn (string $input): string => $parent.$input, $repositoryRelativeInputs); + } + + private function parentPath(): string + { + return str_repeat('../', substr_count($this->gitPrefix(), '/')); + } + private function currentHash(string $relativePath): ?string { $absolute = $this->projectRoot.DIRECTORY_SEPARATOR.$relativePath; @@ -129,11 +223,22 @@ final class ChangedFiles return null; } - $hash = ContentHash::of($absolute); + $hash = $this->hashOf($relativePath, $absolute); return $hash === false ? null : $hash; } + private function hashOf(string $relativePath, string $absolute): string|false + { + $parent = $this->parentPath(); + + if ($parent !== '' && str_starts_with($relativePath, $parent)) { + return @hash_file('xxh128', $absolute); + } + + return ContentHash::of($absolute); + } + /** * @param array $files * @return array path → xxh128 content hash @@ -151,7 +256,7 @@ final class ChangedFiles continue; } - $hash = ContentHash::of($absolute); + $hash = $this->hashOf($file, $absolute); if ($hash !== false) { $out[$file] = $hash; @@ -276,25 +381,14 @@ final class ChangedFiles return $candidates; } - $result = $git->result( - ['check-ignore', '-z', '--stdin'], - implode("\x00", array_keys($candidates)), - ); + $result = $git->checkIgnore(Arr::stringKeys($candidates)); if ($result['exitCode'] !== 0 && $result['exitCode'] !== 1) { - throw $this->gitFailure($result); + throw $this->gitFailure(['exitCode' => $result['exitCode'], 'output' => '', 'errorOutput' => $result['errorOutput']]); } - $output = $result['output']; - - if ($output === '') { - return $candidates; - } - - foreach (explode("\x00", rtrim($output, "\x00")) as $ignored) { - if ($ignored !== '') { - unset($candidates[$ignored]); - } + foreach ($result['ignored'] as $ignored) { + unset($candidates[$ignored]); } return $candidates; diff --git a/src/Plugins/Tia/ExternalSources.php b/src/Plugins/Tia/ExternalSources.php new file mode 100644 index 00000000..bb849915 --- /dev/null +++ b/src/Plugins/Tia/ExternalSources.php @@ -0,0 +1,1065 @@ + + */ + private const array CONFIGURATION_FLAGS = ['-c', '--configuration']; + + /** + * @var list + */ + private const array BOOTSTRAP_FLAGS = ['--bootstrap']; + + /** + * @var list + */ + private const array INCLUDE_PATH_FLAGS = ['--include-path']; + + /** + * @var list + */ + private const array CONFIGURATION_NAMES = ['phpunit.xml', 'phpunit.dist.xml', 'phpunit.xml.dist']; + + private const string NO_CONFIGURATION_FLAG = '--no-configuration'; + + /** + * @var array, ignored: array, unverifiable: array}> + */ + private static array $cache = []; + + private static ?string $workingDirectory = null; + + /** + * @param array $arguments + * @return array + */ + public static function rootsFor(string $projectRoot, array $arguments = []): array + { + return self::resolved($projectRoot, $arguments)['roots']; + } + + /** + * @param array $arguments + * @return array + */ + public static function unverifiable(string $projectRoot, array $arguments = []): array + { + return self::resolved($projectRoot, $arguments)['unverifiable']; + } + + /** + * @param array $arguments + * @return array + */ + public static function ignoredInputs(string $projectRoot, array $arguments = []): array + { + return self::ignoredState($projectRoot, $arguments)['inputs']; + } + + /** + * @param array $arguments + * @return array{inputs: array, repositories: array, failed: array, unreadable: array} + */ + public static function ignoredState(string $projectRoot, array $arguments = []): array + { + $resolved = self::resolved($projectRoot, $arguments); + + if ($resolved['roots'] === [] && $resolved['ignored'] === []) { + return ['inputs' => [], 'repositories' => [], 'failed' => [], 'unreadable' => []]; + } + + $git = new Git($projectRoot); + $repositoryRoot = $git->repositoryRoot(); + + if ($repositoryRoot === null) { + return ['inputs' => [], 'repositories' => [], 'failed' => [], 'unreadable' => []]; + } + + $listing = self::ignoredEntries($repositoryRoot, $git->pathPrefix(), $resolved['roots'], $resolved['ignored']); + $inputs = []; + + foreach ($listing['entries'] as $path) { + if (is_file($repositoryRoot.'/'.$path)) { + $inputs[$path] = true; + } + } + + $inputs = Arr::stringKeys($inputs); + sort($inputs); + + return ['inputs' => $inputs, 'repositories' => $listing['repositories'], 'failed' => $listing['failed'], 'unreadable' => $listing['unreadable']]; + } + + /** + * @param array $roots + * @param array $ignoredRoots + * @return array{entries: array, repositories: array, failed: array, unreadable: array} + */ + private static function ignoredEntries(string $repositoryRoot, string $projectPrefix, array $roots, array $ignoredRoots): array + { + $queries = []; + $files = []; + + foreach ([...$roots, ...$ignoredRoots] as $root) { + if ($root === '' || str_ends_with($root, '/')) { + $queries[] = [[$root], self::pathspecsUnder($root)]; + } elseif (in_array($root, $ignoredRoots, true)) { + $files[] = $root; + } + } + + if ($files !== []) { + $queries[] = [$files, array_map(static fn (string $file): string => ':(literal)'.$file, $files)]; + } + + $repository = new Git($repositoryRoot); + $entries = []; + $repositories = []; + $failed = []; + $unreadable = []; + + foreach ($queries as [$queried, $pathspecs]) { + $result = $repository->result(['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--', ...$pathspecs]); + + if ($result['exitCode'] !== 0) { + array_push($failed, ...$queried); + + continue; + } + + foreach (explode("\x00", rtrim($result['output'], "\x00")) as $path) { + if ($path === '' || str_starts_with($path, $projectPrefix)) { + continue; + } + + if (preg_match('//u', $path) !== 1) { + $unreadable[$path] = true; + + continue; + } + + $entries[$path] = true; + + if (str_ends_with($path, '/') && ! self::isNoiseBelow($queried[0], $path)) { + $repositories[rtrim($path, '/')] = true; + } + } + } + + $repositories = Arr::stringKeys($repositories); + $unreadable = Arr::stringKeys($unreadable); + sort($repositories); + sort($failed); + sort($unreadable); + + return ['entries' => Arr::stringKeys($entries), 'repositories' => $repositories, 'failed' => $failed, 'unreadable' => $unreadable]; + } + + private static function isNoiseBelow(string $root, string $entry): bool + { + $below = '/'.substr($entry, strlen($root)); + + if (str_contains($below, '/.')) { + return true; + } + + return array_any(SourceScope::noiseDirectories(), static fn (string $directory): bool => str_contains($below, '/'.$directory.'/')); + } + + /** + * @return list + */ + private static function pathspecsUnder(string $root): array + { + $under = self::escapeGlob($root); + + return [ + ':(glob)'.$under.'**', + ':(exclude,glob)'.$under.'**/.*', + ':(exclude,glob)'.$under.'**/.*/**', + ...array_map( + static fn (string $directory): string => ':(exclude,glob)'.$under.'**/'.$directory.'/**', + SourceScope::noiseDirectories(), + ), + ]; + } + + private static function escapeGlob(string $path): string + { + return addcslashes($path, '\\*?['); + } + + /** + * @param array $arguments + * @return array{roots: array, ignored: array, unverifiable: array} + */ + private static function resolved(string $projectRoot, array $arguments): array + { + $configurations = self::configurations($projectRoot, $arguments); + + $key = $projectRoot."\x00".implode("\x00", [...array_map(static fn (array $configuration): string => $configuration[0]."\x00".$configuration[1], $configurations), ...$arguments]); + + return self::$cache[$key] ??= self::resolve($projectRoot, $configurations, $arguments); + } + + /** + * @param array $files + * @param array $arguments + * @return array + */ + public static function matching(string $projectRoot, array $files, array $arguments = []): array + { + $roots = self::rootsFor($projectRoot, $arguments); + + if ($roots === []) { + return []; + } + + $matched = []; + + foreach ($files as $file) { + foreach ($roots as $root) { + if (self::covers($root, $file)) { + $matched[] = $file; + + break; + } + } + } + + return $matched; + } + + /** + * @param array $arguments + * @return array + */ + public static function includePaths(string $projectRoot, array $arguments): array + { + $values = self::includePathValues($arguments); + + if ($values === []) { + return []; + } + + $repositoryRoot = new Git($projectRoot)->repositoryRoot(); + $paths = []; + + foreach ($values as $value) { + if (! self::isAbsolute($value)) { + $paths[] = 'relative:'.self::normalisedRelativePath($value); + + continue; + } + + $resolved = self::commandLinePath($projectRoot, $value) ?? $value; + + if ($repositoryRoot !== null && $resolved === $repositoryRoot) { + $resolved = '.'; + } elseif ($repositoryRoot !== null && str_starts_with($resolved, $repositoryRoot.'/')) { + $resolved = substr($resolved, strlen($repositoryRoot) + 1); + } + + $paths[] = 'absolute:'.$resolved; + } + + return $paths; + } + + private static function normalisedRelativePath(string $path): string + { + $segments = array_filter( + explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $path)), + static fn (string $segment): bool => $segment !== '' && $segment !== '.', + ); + + return $segments === [] ? '.' : implode('/', $segments); + } + + public static function flush(): void + { + self::$cache = []; + self::$workingDirectory = null; + } + + public static function pinWorkingDirectory(string $projectRoot): void + { + self::$workingDirectory = getcwd() ?: $projectRoot; + } + + private static function workingDirectory(string $projectRoot): string + { + return self::$workingDirectory ??= (getcwd() ?: $projectRoot); + } + + private static function covers(string $root, string $file): bool + { + if ($root === '') { + return true; + } + + $directory = str_ends_with($root, '/'); + $normalised = $directory ? rtrim($root, '/') : $root; + + if ($file === $normalised) { + return true; + } + + if ($directory && str_starts_with($file, $root)) { + return true; + } + + return str_starts_with($normalised, $file.'/'); + } + + /** + * @param array $configurations + * @param array $arguments + * @return array{roots: array, ignored: array, unverifiable: array} + */ + private static function resolve(string $projectRoot, array $configurations, array $arguments): array + { + $git = new Git($projectRoot); + $repositoryRoot = $git->repositoryRoot(); + $project = self::realpath($projectRoot); + + if ($repositoryRoot === null || $project === null) { + return ['roots' => [], 'ignored' => [], 'unverifiable' => []]; + } + + $roots = []; + $unverifiable = []; + + foreach (self::declarations($projectRoot, $configurations, $arguments) as [$resolved, $isDirectory]) { + if ($resolved === $project || str_starts_with($resolved, $project.'/')) { + continue; + } + + if ($resolved === $repositoryRoot) { + $relative = ''; + } elseif (str_starts_with($resolved, $repositoryRoot.'/')) { + $relative = substr($resolved, strlen($repositoryRoot) + 1); + } else { + $unverifiable[$resolved] = true; + + continue; + } + + $roots[$isDirectory && $relative !== '' ? $relative.'/' : $relative] = true; + } + + $roots = $git->pathPrefix() === '' ? [] : Arr::stringKeys($roots); + $unverifiable = Arr::stringKeys($unverifiable); + + $ignoredRoots = self::ignoredRoots($repositoryRoot, $roots); + $roots = array_values(array_diff($roots, $ignoredRoots)); + + $listing = self::ignoredEntries($repositoryRoot, $git->pathPrefix(), $roots, $ignoredRoots); + + foreach ($listing['repositories'] as $nested) { + $unverifiable[] = $repositoryRoot.'/'.$nested; + } + + foreach ($listing['failed'] as $root) { + $unverifiable[] = rtrim($repositoryRoot.'/'.$root, '/'); + } + + foreach ($listing['unreadable'] as $path) { + $unverifiable[] = rtrim($repositoryRoot.'/'.$path, '/'); + } + + sort($roots); + sort($ignoredRoots); + sort($unverifiable); + + return ['roots' => $roots, 'ignored' => $ignoredRoots, 'unverifiable' => $unverifiable]; + } + + /** + * @param array $roots + * @return array + */ + private static function ignoredRoots(string $repositoryRoot, array $roots): array + { + static $cache = []; + + $candidates = array_values(array_filter($roots, static fn (string $root): bool => $root !== '')); + + if ($candidates === []) { + return []; + } + + $key = $repositoryRoot."\x00".implode("\x00", $candidates); + + if (isset($cache[$key])) { + return $cache[$key]; + } + + $result = new Git($repositoryRoot)->checkIgnore( + array_map(static fn (string $root): string => rtrim($root, '/'), $candidates), + ); + + if ($result['exitCode'] !== 0 && $result['exitCode'] !== 1) { + return $cache[$key] = []; + } + + $ignored = []; + + foreach ($result['ignored'] as $path) { + foreach ($candidates as $root) { + if (rtrim($root, '/') === $path) { + $ignored[] = $root; + } + } + } + + return $cache[$key] = $ignored; + } + + /** + * @param array $arguments + * @return array + */ + private static function configurations(string $projectRoot, array $arguments): array + { + $values = self::argumentValues($arguments, self::CONFIGURATION_FLAGS); + $fromArguments = $values === [] ? null : $values[count($values) - 1]; + + if ($fromArguments !== null) { + $resolved = self::commandLinePath($projectRoot, $fromArguments); + $file = $resolved === null ? null : self::configurationFileAt($resolved); + + return $file === null ? [] : [[$file, dirname($file), true]]; + } + + $workingDirectory = self::workingDirectory($projectRoot); + $file = self::configurationFileIn($workingDirectory); + + if ($file === null) { + return [[Configuration::BASE_PHPUNIT_FILE, $workingDirectory, false]]; + } + + if (in_array(self::NO_CONFIGURATION_FLAG, $arguments, true)) { + return []; + } + + return [[$file, dirname($file), true]]; + } + + private static function configurationFileAt(string $path): ?string + { + if (is_dir($path)) { + return self::configurationFileIn($path); + } + + return is_file($path) ? $path : null; + } + + private static function configurationFileIn(string $directory): ?string + { + foreach (self::CONFIGURATION_NAMES as $name) { + $resolved = self::realpath($directory.DIRECTORY_SEPARATOR.$name); + + if ($resolved !== null && is_file($resolved)) { + return $resolved; + } + } + + return null; + } + + /** + * @param array $arguments + * @param list $flags + * @return array + */ + private static function argumentValues(array $arguments, array $flags): array + { + $values = []; + $count = count($arguments); + + for ($index = 0; $index < $count; $index++) { + $argument = $arguments[$index]; + + foreach ($flags as $flag) { + if (str_starts_with($argument, $flag.'=')) { + $values[] = substr($argument, strlen($flag) + 1); + + continue 2; + } + + if ($argument === $flag && isset($arguments[$index + 1])) { + $values[] = $arguments[$index + 1]; + + continue 2; + } + + if (self::isShortFlag($flag) && strlen($argument) > 2 && str_starts_with($argument, $flag)) { + $values[] = substr($argument, 2); + + continue 2; + } + } + } + + return array_values(array_filter($values, static fn (string $value): bool => $value !== '')); + } + + private static function isShortFlag(string $flag): bool + { + return strlen($flag) === 2 && $flag[0] === '-' && $flag[1] !== '-'; + } + + private static function commandLinePath(string $projectRoot, string $path): ?string + { + return self::absolutePath(self::workingDirectory($projectRoot), $path); + } + + /** + * @param array $configurations + * @param array $arguments + * @return array + */ + private static function declarations(string $projectRoot, array $configurations, array $arguments): array + { + $declarations = self::composerDeclarations($projectRoot); + + foreach ($configurations as [$configuration, $base, $isWatched]) { + $declarations = [...$declarations, ...self::phpunitDeclarations($projectRoot, $configuration, $base, $isWatched)]; + } + + return [...$declarations, ...self::argumentDeclarations($projectRoot, $arguments)]; + } + + /** + * @param array $arguments + * @return array + */ + private static function argumentDeclarations(string $projectRoot, array $arguments): array + { + $declarations = []; + + foreach (self::argumentValues($arguments, self::BOOTSTRAP_FLAGS) as $bootstrap) { + $resolved = self::commandLinePath($projectRoot, $bootstrap); + + if ($resolved !== null) { + $declarations[] = [$resolved, false]; + } + } + + foreach (self::includePathEntries($projectRoot, $arguments) as $resolved) { + $declarations[] = [$resolved, true]; + } + + return $declarations; + } + + /** + * @param array $arguments + * @return array + */ + private static function includePathEntries(string $projectRoot, array $arguments): array + { + $entries = []; + + foreach (self::includePathValues($arguments) as $path) { + $resolved = self::commandLinePath($projectRoot, $path); + + if ($resolved !== null) { + $entries[] = $resolved; + } + } + + return $entries; + } + + /** + * @param array $arguments + * @return array + */ + private static function includePathValues(array $arguments): array + { + $values = []; + + foreach (self::argumentValues($arguments, self::INCLUDE_PATH_FLAGS) as $list) { + foreach (explode(PATH_SEPARATOR, $list) as $path) { + if ($path !== '') { + $values[] = $path; + } + } + } + + return $values; + } + + /** + * @return array + */ + private static function composerDeclarations(string $projectRoot): array + { + $manifest = self::decodeJson(self::composerManifest($projectRoot)); + + if ($manifest === null) { + return []; + } + + $declarations = []; + + self::declareAutoload($declarations, $projectRoot, $manifest); + self::declarePathRepositories($declarations, $projectRoot, $manifest); + + foreach (self::installedPathUrls($projectRoot, $manifest) as $url) { + self::declareLiteral($declarations, $projectRoot, $url, true); + } + + return $declarations; + } + + /** + * @param array $declarations + * @param array $manifest + */ + private static function declareAutoload(array &$declarations, string $projectRoot, array $manifest): void + { + foreach (['autoload', 'autoload-dev'] as $section) { + $autoload = $manifest[$section] ?? null; + + if (! is_array($autoload)) { + continue; + } + + foreach (['psr-4' => true, 'psr-0' => true, 'classmap' => null, 'files' => false] as $kind => $isDirectory) { + $entries = $autoload[$kind] ?? null; + + if (! is_array($entries)) { + continue; + } + + foreach ($entries as $entry) { + foreach (is_array($entry) ? $entry : [$entry] as $path) { + if (! is_string($path) || $path === '') { + continue; + } + + if ($kind === 'classmap') { + self::declare($declarations, $projectRoot, $path, $isDirectory, self::braceFlag()); + } else { + self::declareLiteral($declarations, $projectRoot, $path, $isDirectory); + } + } + } + } + } + } + + /** + * @param array $declarations + * @param array $manifest + */ + private static function declarePathRepositories(array &$declarations, string $projectRoot, array $manifest): void + { + $repositories = $manifest['repositories'] ?? null; + + if (is_array($repositories)) { + foreach ($repositories as $repository) { + if (! is_array($repository) || ($repository['type'] ?? null) !== 'path') { + continue; + } + + $url = $repository['url'] ?? null; + + if (is_string($url) && $url !== '') { + self::declare($declarations, $projectRoot, $url, true, self::braceFlag() | GLOB_ONLYDIR); + } + } + } + } + + private static function composerManifest(string $projectRoot): string + { + $manifest = getenv('COMPOSER'); + $manifest = is_string($manifest) ? trim($manifest) : ''; + $manifest = $manifest !== '' ? $manifest : 'composer.json'; + + return self::isAbsolute($manifest) ? $manifest : $projectRoot.DIRECTORY_SEPARATOR.$manifest; + } + + private static function composerLock(string $projectRoot): string + { + $manifest = self::composerManifest($projectRoot); + + return str_ends_with($manifest, '.json') ? substr($manifest, 0, -5).'.lock' : $manifest.'.lock'; + } + + /** + * @param array $manifest + * @return array + */ + private static function installedPathUrls(string $projectRoot, array $manifest): array + { + $lock = self::decodeJson(self::composerLock($projectRoot)) ?? []; + + $packages = [ + ...self::listOf($lock['packages'] ?? null), + ...self::listOf($lock['packages-dev'] ?? null), + ]; + + foreach (self::vendorDirectories($projectRoot, $manifest) as $vendorDirectory) { + $installed = self::decodeJson($vendorDirectory.DIRECTORY_SEPARATOR.'composer'.DIRECTORY_SEPARATOR.'installed.json') ?? []; + + array_push($packages, ...self::listOf(array_key_exists('packages', $installed) ? $installed['packages'] : $installed)); + } + + $urls = []; + + foreach ($packages as $package) { + $dist = is_array($package) ? ($package['dist'] ?? null) : null; + + if (is_array($dist) && ($dist['type'] ?? null) === 'path' && is_string($dist['url'] ?? null) && $dist['url'] !== '') { + $urls[$dist['url']] = true; + } + } + + return Arr::stringKeys($urls); + } + + /** + * @param array $manifest + * @return array + */ + private static function vendorDirectories(string $projectRoot, array $manifest): array + { + $project = self::realpath($projectRoot); + $loaded = []; + + foreach (array_keys(ClassLoader::getRegisteredLoaders()) as $vendorDirectory) { + if ($project !== null && self::realpath(ComposerProject::rootPath($vendorDirectory.DIRECTORY_SEPARATOR.'autoload.php')) === $project) { + $loaded[] = $vendorDirectory; + } + } + + if ($loaded !== []) { + return $loaded; + } + + $config = $manifest['config'] ?? null; + $configured = is_array($config) ? ($config['vendor-dir'] ?? null) : null; + $directory = is_string($configured) && $configured !== '' ? $configured : 'vendor'; + + return [self::isAbsolute($directory) ? $directory : $projectRoot.DIRECTORY_SEPARATOR.$directory]; + } + + /** + * @return array + */ + private static function listOf(mixed $value): array + { + return is_array($value) ? array_values($value) : []; + } + + /** + * @return array + */ + private static function phpunitDeclarations(string $projectRoot, string $configuration, string $base, bool $isWatched): array + { + $xml = self::parseXml($configuration); + + if (! $xml instanceof SimpleXMLElement) { + return []; + } + + $declarations = $isWatched ? [[str_replace(DIRECTORY_SEPARATOR, '/', $configuration), false]] : []; + + $bootstrap = trim((string) ($xml['bootstrap'] ?? '')); + + if ($bootstrap !== '') { + self::declareLiteral($declarations, $base, $bootstrap, false); + } + + $sections = ['source/include', 'coverage/include', 'testsuites/testsuite']; + + foreach ($sections as $section) { + foreach (['directory' => true, 'file' => false] as $node => $isDirectory) { + foreach ($xml->xpath($section.'/'.$node) ?: [] as $element) { + $value = trim((string) $element); + + if ($value === '') { + continue; + } + + if ($isDirectory) { + self::declare($declarations, $base, $value, true, GLOB_ONLYDIR, true); + } else { + self::declareLiteral($declarations, $base, $value, false); + } + } + } + } + + foreach ($xml->xpath('testsuites/testsuite') ?: [] as $suite) { + $suiteBootstrap = trim((string) ($suite['bootstrap'] ?? '')); + + if ($suiteBootstrap !== '') { + self::declareLiteral($declarations, $base, $suiteBootstrap, false); + } + } + + foreach ($xml->xpath('php/includePath') ?: [] as $element) { + if ((string) $element !== '') { + self::declareIncludePath($declarations, $projectRoot, $base, trim((string) $element)); + } + } + + return $declarations; + } + + /** + * @param array $declarations + */ + private static function declareIncludePath(array &$declarations, string $projectRoot, string $base, string $includePath): void + { + foreach (explode(PATH_SEPARATOR, $includePath) as $index => $path) { + if ($index === 0) { + self::declareLiteral($declarations, $base, $path === '' ? '.' : $path, true); + + continue; + } + + if ($path === '') { + continue; + } + + $resolved = self::commandLinePath($projectRoot, $path); + + if ($resolved !== null) { + $declarations[] = [$resolved, true]; + } + } + } + + private static function braceFlag(): int + { + return defined('GLOB_BRACE') ? GLOB_BRACE : 0; + } + + /** + * @param array $declarations + */ + private static function declare(array &$declarations, string $base, string $path, ?bool $isDirectory, int $globFlags, bool $globstar = false): void + { + $literal = self::beforeWildcard($path, $globFlags); + + if ($literal === $path) { + self::declareLiteral($declarations, $base, $path, $isDirectory); + + return; + } + + $pattern = self::isAbsolute($path) ? $path : $base.DIRECTORY_SEPARATOR.$path; + $matches = $globstar ? self::globstar($pattern) : (glob($pattern, $globFlags) ?: []); + + if ($matches === [] && file_exists($pattern)) { + self::declareLiteral($declarations, $base, $path, $isDirectory); + + return; + } + + self::declareLiteral($declarations, $base, $literal, true); + + foreach ($matches as $match) { + self::declareLiteral($declarations, $base, $match, $isDirectory); + } + } + + /** + * @param array $declarations + */ + private static function declareLiteral(array &$declarations, string $base, string $path, ?bool $isDirectory): void + { + if ($path === '') { + return; + } + + $resolved = self::absolutePath($base, $path); + + if ($resolved === null) { + return; + } + + $isDirectory ??= file_exists($resolved) + ? is_dir($resolved) + : ! self::looksLikeFile($resolved); + + $declarations[] = [$resolved, $isDirectory]; + } + + private static function absolutePath(string $base, string $path): ?string + { + return self::realpath(self::isAbsolute($path) ? $path : $base.DIRECTORY_SEPARATOR.$path) + ?? self::lexicalPath(self::realpath($base) ?? $base, $path); + } + + /** + * @return array + */ + private static function globstar(string $pattern): array + { + $position = strpos($pattern, '**'); + + if ($position === false) { + return glob($pattern, GLOB_ONLYDIR) ?: []; + } + + $root = substr($pattern, 0, $position); + $rest = substr($pattern, $position + 2); + $patterns = [$root.ltrim($rest, '/'.DIRECTORY_SEPARATOR)]; + $root .= '*'; + + while (($directories = glob($root, GLOB_ONLYDIR)) !== false && $directories !== []) { + $root .= '/*'; + + foreach ($directories as $directory) { + $patterns[] = $directory.$rest; + } + } + + $matches = []; + + foreach ($patterns as $nested) { + array_push($matches, ...self::globstar($nested)); + } + + return array_values(array_unique($matches)); + } + + private static function isAbsolute(string $path): bool + { + if (str_starts_with($path, '/')) { + return true; + } + + return PHP_OS_FAMILY === 'Windows' + && (str_starts_with($path, '\\') || preg_match('/^[a-z]:[\\\\\/]/i', $path) === 1); + } + + private static function beforeWildcard(string $path, int $globFlags): string + { + $normalised = str_replace(DIRECTORY_SEPARATOR, '/', $path); + $wildcards = ($globFlags & self::braceFlag()) !== 0 ? '*?[\\{' : '*?[\\'; + + if (strpbrk($normalised, $wildcards) === false) { + return $path; + } + + $segments = []; + + foreach (explode('/', $normalised) as $segment) { + if (strpbrk($segment, $wildcards) !== false) { + break; + } + + $segments[] = $segment; + } + + return rtrim(implode('/', $segments), '/'); + } + + private static function looksLikeFile(string $path): bool + { + return pathinfo($path, PATHINFO_EXTENSION) !== ''; + } + + /** + * @return array|null + */ + private static function decodeJson(string $path): ?array + { + if (! is_file($path)) { + return null; + } + + $contents = @file_get_contents($path); + + if ($contents === false) { + return null; + } + + $decoded = json_decode($contents, true); + + return is_array($decoded) ? $decoded : null; + } + + private static function parseXml(string $path): ?SimpleXMLElement + { + if (! is_file($path)) { + return null; + } + + try { + $xml = @simplexml_load_file($path); + } catch (Throwable) { + return null; + } + + return $xml === false ? null : $xml; + } + + private static function lexicalPath(string $base, string $relative): ?string + { + $relative = str_replace(DIRECTORY_SEPARATOR, '/', $relative); + $joined = self::isAbsolute($relative) ? $relative : str_replace(DIRECTORY_SEPARATOR, '/', $base).'/'.$relative; + + if (PHP_OS_FAMILY === 'Windows' && preg_match('#^/(?!/)#', $joined) === 1 && preg_match('#^[a-z]:#i', (string) getcwd(), $drive) === 1) { + $joined = $drive[0].$joined; + } + + $prefix = PHP_OS_FAMILY === 'Windows' && preg_match('#^(?:[a-z]:|//[^/]+/[^/]+)#i', $joined, $root) === 1 ? $root[0] : ''; + $joined = substr($joined, strlen($prefix)); + + $segments = []; + + foreach (explode('/', $joined) as $segment) { + if ($segment === '' || $segment === '.') { + continue; + } + + if ($segment !== '..') { + $segments[] = $segment; + + continue; + } + + if ($segments === []) { + return null; + } + + array_pop($segments); + } + + return $prefix.'/'.implode('/', $segments); + } + + private static function realpath(string $path): ?string + { + $resolved = @realpath($path); + + return $resolved === false ? null : rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $resolved), '/'); + } +} diff --git a/src/Plugins/Tia/Fingerprint.php b/src/Plugins/Tia/Fingerprint.php index 149cf419..a51ffee1 100644 --- a/src/Plugins/Tia/Fingerprint.php +++ b/src/Plugins/Tia/Fingerprint.php @@ -23,12 +23,13 @@ final readonly class Fingerprint ]; /** + * @param array $arguments * @return array{ * structural: array, * environmental: array, * } */ - public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null): array + public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null, array $arguments = []): array { $configuration ??= ConfigurationFile::projectDefault(); @@ -48,6 +49,18 @@ final readonly class Fingerprint $structural['project_prefix'] = $prefix; } + $externalRoots = ExternalSources::rootsFor($projectRoot, $arguments); + + if ($externalRoots !== []) { + $structural['external_roots'] = hash('xxh128', serialize($externalRoots)); + } + + $includePaths = ExternalSources::includePaths($projectRoot, $arguments); + + if ($includePaths !== []) { + $structural['include_path'] = hash('xxh128', serialize($includePaths)); + } + return [ 'structural' => $structural, 'environmental' => [ @@ -302,10 +315,12 @@ final readonly class Fingerprint } try { - return $cache[$key] = ! new Git($projectRoot)->succeeds(['check-ignore', '-q', '--', $relativePath]); + $result = new Git($projectRoot)->checkIgnore([$relativePath]); } catch (ProcessException) { return $cache[$key] = true; } + + return $cache[$key] = $result['exitCode'] !== 0; } private static function projectPrefix(string $projectRoot): string diff --git a/src/Plugins/Tia/SourceScope.php b/src/Plugins/Tia/SourceScope.php index ab4f4234..2a47bf5c 100644 --- a/src/Plugins/Tia/SourceScope.php +++ b/src/Plugins/Tia/SourceScope.php @@ -33,6 +33,14 @@ final class SourceScope 'bootstrap/cache', ]; + /** + * @return list + */ + public static function noiseDirectories(): array + { + return [...self::TOP_LEVEL_NOISE, ...self::NESTED_NOISE]; + } + /** * @param list $includes Absolute, normalised directory paths. * @param list $excludes Absolute, normalised directory paths with the file name prefix and suffix they apply to. diff --git a/src/Restarters/XdebugRestarter.php b/src/Restarters/XdebugRestarter.php index af494049..57f287d8 100644 --- a/src/Restarters/XdebugRestarter.php +++ b/src/Restarters/XdebugRestarter.php @@ -115,7 +115,7 @@ final class XdebugRestarter implements Restarter return Fingerprint::structuralMatches( $graph->fingerprint(), - Fingerprint::compute($projectRoot, ConfigurationFile::fromArguments($arguments)), + Fingerprint::compute($projectRoot, ConfigurationFile::fromArguments($arguments), $arguments), ); } } diff --git a/src/Support/ComposerProject.php b/src/Support/ComposerProject.php index 598def43..6a166a8c 100644 --- a/src/Support/ComposerProject.php +++ b/src/Support/ComposerProject.php @@ -20,9 +20,14 @@ final class ComposerProject return $rootPath; } - /** @var array{root: array{install_path: string}} $installed */ $installed = require $metadataPath; + $root = is_array($installed) ? ($installed['root'] ?? null) : null; + $installPath = is_array($root) ? ($root['install_path'] ?? null) : null; - return realpath($installed['root']['install_path']) ?: $rootPath; + if (! is_string($installPath)) { + return $rootPath; + } + + return realpath($installPath) ?: $rootPath; } } diff --git a/src/Support/Git.php b/src/Support/Git.php index 863a193e..dbed0cc5 100644 --- a/src/Support/Git.php +++ b/src/Support/Git.php @@ -73,13 +73,35 @@ final readonly class Git return $this->result($arguments)['exitCode'] === 0; } + /** + * @param array $paths + * @return array{exitCode: int, ignored: array, errorOutput: string} + */ + public function checkIgnore(array $paths): array + { + $result = $this->result( + ['check-ignore', '-z', '--stdin'], + implode("\x00", array_map(static fn (string $path): string => './'.$path, $paths)), + ); + + $ignored = []; + + foreach (explode("\x00", rtrim($result['output'], "\x00")) as $path) { + if ($path !== '') { + $ignored[] = str_starts_with($path, './') ? substr($path, 2) : $path; + } + } + + return ['exitCode' => $result['exitCode'], 'ignored' => $ignored, 'errorOutput' => $result['errorOutput']]; + } + /** * @param array $arguments * @return array{exitCode: int, output: string, errorOutput: string} */ public function result(array $arguments, ?string $input = null): array { - $process = new Process(['git', ...$arguments], $this->directory, ['LC_ALL' => 'C', 'LANGUAGE' => '']); + $process = new Process(['git', ...$arguments], $this->directory, ['GIT_LITERAL_PATHSPECS' => '0', 'LC_ALL' => 'C', 'LANGUAGE' => '']); $process->setTimeout($this->timeout); if ($input !== null) { diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index f4563201..17a43140 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -2002,8 +2002,15 @@ ✓ it keeps a tracked outside change and drops an untracked ignored one ✓ it keeps a tracked project change that the ignore rules match ✓ it reads committed paths from the repository root even when git is told to be relative + ✓ it tells a working tree change outside the project from a committed one ✓ it keeps a changed file whose name is a number as a string ✓ it keeps a changed file outside the project whose name is a number as a string + ✓ it matches no external root for a changed file whose name is a number + ✓ it hashes an external input without reading it into memory + ✓ it sees a whitespace change inside an external input + ✓ it reports a changed file whose name looks like a pathspec + ✓ it reports an external input that the listing no longer names + ✓ it reports no change for an external input it cannot read ✓ it keeps a snapshotted file whose name is a number as a string ✓ it keeps a branch whose name is a number as a string @@ -2073,6 +2080,89 @@ WARN Tests\Unit\Plugins\Tia\DeletedTestCoverage - cached hits of a deleted test are dropped while a replayed test stays → Coverage is not available + WARN Tests\Unit\Plugins\Tia\ExternalSources + ✓ it finds a psr-4 root that escapes the project + ✓ it finds a path repository + ✓ it finds a phpunit source directory outside the project + ✓ it finds nothing when the project only loads its own code + ✓ it finds nothing for a project at the repository root + ✓ it reports a root that sits outside the repository as unverifiable + ✓ it reports nothing unverifiable when every declaration stays inside the repository + ✓ it reports a bootstrap outside the repository as unverifiable + ✓ it matches only the changes that fall under an external root + ✓ it finds an autoload file that escapes the project and matches it exactly + ✓ it finds a phpunit bootstrap that escapes the project + ✓ it keeps a declared root that no longer exists on disk + ✓ it treats a classmap entry as a file only when it names one + ✓ it finds a testsuite directory outside the project + ✓ it keeps the directory before a wildcard in a path repository + ✓ it keeps the directory before a single character wildcard + ✓ it matches a deleted package that a wildcard declared + ✓ it covers the whole repository when a declaration reaches its root + ✓ it reads the configuration that the command line selects + ✓ it accepts the configuration argument in its joined form + ✓ it resolves a configuration path against its own directory + ✓ it follows a symlink that leaves the project + ✓ it keeps a real directory inside the project out of the roots + ✓ it finds a bootstrap file that the command line names + ✓ it finds every directory that an include path names + ✓ it resolves a command line path against the directory the command ran in + ✓ it keeps a declaration that a commit deleted under the directory the command ran in + ✓ it watches the paths of the configuration Pest generates in the directory the command ran in + ✓ it treats a classmap directory that carries a dot as a directory + ✓ it accepts the configuration argument attached to its short flag + ✓ it reads no configuration when the run asks for none + ✓ it reads no default configuration when the command line names one + ✓ it finds an include path that the configuration names + ✓ it matches a submodule that a commit moved + ✓ it matches a submodule that holds a declared file + ✓ it reads the configuration of the directory the command ran in + ✓ it reads a configuration that a directory argument names + ✓ it reads the dist name that phpunit tries before the older one + ✓ it finds a bootstrap that a single test suite names + ✓ it watches the directory before a wildcard that a configuration names + ✓ it lists the files of a root that the repository ignores as ignored inputs + ✓ it lists the ignored files under a declared root as ignored inputs + ✓ it lists an ignored bootstrap file inside vendor as an ignored input + ✓ it lists the ignored files under a declared root inside a dot directory + ✓ it lists an ignored link to a file but no ignored link to a directory or to nothing + ✓ it watches the path that composer resolved for a path repository + ✓ it watches the path that composer installed when the project has no lock file + ✓ it watches the path that composer installed into a custom vendor directory + ✓ it watches the path that composer installed into the vendor directory the run loaded + ✓ it watches the installed path and the locked path when they differ + ✓ it reads a path that composer resolved as a literal path + ✓ it reads the manifest and the lock file that the COMPOSER variable names + ✓ it lists the ignored files when git is told to read every pathspec literally + - it treats a network path as absolute on Windows → Network paths only exist on Windows. + ✓ it reports an ignored repository under a declared root as unverifiable + ✓ it finds a root that the repository ignores next to a file whose name looks like a pathspec + ✓ it reports no repository that sits in a noise directory under a declared root as unverifiable + ✓ it reports a repository under an inner declared root even when an outer root counts it as noise + ✓ it reports a root inside an ignored repository as unverifiable + ✓ it reads a bootstrap whose name holds a wildcard character as a literal file + ✓ it reads a psr-4 directory whose name holds a wildcard character as a literal directory + ✓ it reads an include path whose name holds a wildcard character as a literal directory + ✓ it reads every path of an include path list + ✓ it watches the configuration directory when an include path list starts with a separator + ✓ it watches nothing for an empty include path, as PHPUnit adds nothing + ✓ it resolves every path of an include path list after the first one from the working directory + ✓ it watches the directory before a bracket and a brace path as it is + ✓ it watches the directory an escaped brace names + ✓ it watches every directory a double star pattern reaches like PHPUnit + ✓ it also watches a directory whose real name looks like a pattern + ✓ it keeps an existing absolute directory with brackets in its path as it is + ✓ it watches the directories a bracket pattern matches even when its literal name also exists + ✓ it cuts a path at a brace only when the glob of its reader expands braces + ✓ it lists no ignored file of the project itself as an ignored input + ✓ it keeps the roots of the run when a test changes the working directory + - it keeps the drive letter when it resolves a missing directory against a Windows base → Drive letters exist only on Windows. + ✓ it resolves a path that starts with a drive letter against its base outside Windows + - it treats a path from the root of the current drive as absolute on Windows → Paths from the root of the current drive exist only on Windows. + - it keeps the current drive when it resolves a missing path from the root of that drive → Paths from the root of the current drive exist only on Windows. + - it keeps the network share when it resolves a missing directory against a UNC base → UNC paths exist only on Windows. + ✓ it reads a leading double slash as the root outside Windows + PASS Tests\Unit\Plugins\Tia\FileState ✓ keysWithPrefix() → it lists keys matching the prefix ✓ keysWithPrefix() → it ignores in-flight temporary files from concurrent writes @@ -2083,6 +2173,9 @@ ✓ compute() → it excludes gitignored untracked files from the fingerprint ✓ compute() → it keeps the command line bootstrap and include path out of a run that sets neither ✓ compute() → it tells a bootstrap whose name looks like an include path apart from a bootstrap and an include path + ✓ compute() → it tells a relative include path from the absolute path it names + ✓ compute() → it stores an include path whose name is not utf-8 as text json can encode + ✓ compute() → it changes when the order of the include path changes and not when its spelling does PASS Tests\Unit\Plugins\Tia\Graph ✓ shouldRerunStatus() → it re-runs failures and errors, replays successes @@ -2441,6 +2534,10 @@ PASS Tests\Unit\Support\Backtrace ✓ it gets file name from called file + PASS Tests\Unit\Support\ComposerProject + ✓ it reads the project root that composer recorded + ✓ it falls back to the parent of the vendor directory when composer recorded no install path + PASS Tests\Unit\Support\Container ✓ it exists ✓ it gets an instance @@ -2742,4 +2839,4 @@ ✓ pass with dataset with ('my-datas-set-value') ✓ within describe → pass with dataset with ('my-datas-set-value') - Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 39 skipped, 2019 passed (4528 assertions) \ No newline at end of file + Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 44 skipped, 2107 passed (4644 assertions) diff --git a/tests/Features/Tia/GitStatusFailure.php b/tests/Features/Tia/GitStatusFailure.php new file mode 100644 index 00000000..6d587f3a --- /dev/null +++ b/tests/Features/Tia/GitStatusFailure.php @@ -0,0 +1,22 @@ +seed('master'); + + file_put_contents($project->path('.git/index'), 'not an index'); + + $result = $project->pest(); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->not->toContain('could not read the git repository') + ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed'); +})->skipOnWindows(); diff --git a/tests/Features/Tia/Monorepo.php b/tests/Features/Tia/Monorepo.php index dbb4ef20..fdb8e065 100644 --- a/tests/Features/Tia/Monorepo.php +++ b/tests/Features/Tia/Monorepo.php @@ -4,12 +4,32 @@ declare(strict_types=1); use Pest\Plugins\Tia; use Pest\Support\Coverage; +use Tests\Fixtures\Tia\GitRepo; use Tests\Fixtures\Tia\Project; afterEach(function (): void { Project::destroyAll(); }); +/** + * @return array{0: Project, 1: string} + */ +function tiaMonorepoWithIgnoredInput(): array +{ + [$project, $nested] = tiaMonorepo(); + + $project->write('.gitignore', file_get_contents($project->path('.gitignore'))."packages/shared/generated.php\npackages/shared/generated.json\npackages/shared/vendor/\n.DS_Store\n"); + $project->write('packages/shared/Shared.php', "write('packages/shared/generated.php', "write('packages/shared/generated.json', "{\"version\": 1}\n"); + $project->write('packages/shared/vendor/autoload.php', "write('packages/shared/.DS_Store', "finder\n"); + $project->git()->commit('add a sibling package with a generated file'); + $project->seedFor($nested, 'master', arguments: ['--include-path', '../packages/shared']); + + return [$project, $nested]; +} + /** * @return array{0: Project, 1: string} */ @@ -354,3 +374,987 @@ test('it says when changes outside the project were ignored', function (): void expect($result->exitCode)->toBe(0, $result->describe()) ->and($result->output)->toContain('1 changed file outside this project was ignored'); })->skipOnWindows(); + +test('a change in a sibling package the project autoloads runs the full suite', function (array $arguments): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master'); + + $project->write('packages/shared/src/Shared.php', "git()->commit('rework the sibling package'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia', ...$arguments); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()) + ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed'); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); + +test('a non-php change in a sibling package the project does not load still replays', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('packages/shared/resources/shared.json', "{\"shared\": 2}\n"); + $project->git()->commit('rework an unrelated sibling package'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->not->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe()); +})->skipOnWindows(); + +test('a change in an autoload file outside the project runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['files'][] = '../packages/shared/bootstrap.php'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/bootstrap.php', "git()->commit('let the project load a sibling bootstrap file'); + $project->seedFor($nested, 'master'); + + $project->write('packages/shared/bootstrap.php', "git()->commit('rework the sibling bootstrap file'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a change in the phpunit bootstrap outside the project runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('packages/shared/bootstrap.php', "write('nested/phpunit.xml', str_replace( + 'bootstrap="vendor/autoload.php"', + 'bootstrap="../packages/shared/bootstrap.php"', + (string) file_get_contents($nested.'/phpunit.xml'), + )); + $project->git()->commit('point the project at a sibling bootstrap file'); + $project->seedFor($nested, 'master'); + + $project->write('packages/shared/bootstrap.php', "git()->commit('rework the sibling bootstrap file'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('deleting a declared external package runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master'); + + $project->git()->run(['rm', '-r', '--quiet', 'packages/shared']); + $project->git()->commit('delete the sibling package'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a change in an external test suite runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('shared-tests/support.php', "write('nested/phpunit.xml', str_replace( + './tests', + './tests'."\n".' ../shared-tests', + (string) file_get_contents($nested.'/phpunit.xml'), + )); + $project->git()->commit('add an external test suite'); + $project->seedFor($nested, 'master'); + + $project->write('shared-tests/support.php', "git()->commit('rework the external test suite'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a change under a wildcard path repository runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['repositories'][] = ['type' => 'path', 'url' => '../packages/*/src']; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('declare a wildcard path repository'); + $project->seedFor($nested, 'master'); + + $project->write('packages/shared/src/Shared.php', "git()->commit('rework the wildcard package'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a change under a symlink that leaves the project runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = 'shared'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "path('packages/shared/src'), $nested.'/shared'); + $project->git()->commit('link a sibling package into the project'); + $project->seedFor($nested, 'master'); + + $project->write('packages/shared/src/Shared.php', "git()->commit('rework the linked package'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a change declared only by the configuration argument runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('packages/shared/bootstrap.php', "write('nested/phpunit.ci.xml', str_replace( + 'bootstrap="vendor/autoload.php"', + 'bootstrap="../packages/shared/bootstrap.php"', + (string) file_get_contents($nested.'/phpunit.xml'), + )); + $project->git()->commit('add a second configuration'); + $project->seedFor($nested, 'master', arguments: ['-c', 'phpunit.ci.xml']); + + $project->write('packages/shared/bootstrap.php', "git()->commit('rework the sibling bootstrap file'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia', '-c', 'phpunit.ci.xml'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a run under a different configuration does not reuse the baseline', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('nested/phpunit.ci.xml', str_replace( + 'failOnRisky="true"', + 'failOnRisky="false"', + (string) file_get_contents($nested.'/phpunit.xml'), + )); + $project->git()->commit('add a second configuration'); + $project->seedFor($nested, 'master'); + $project->snapshot(); + + $replayed = $project->pestIn($nested, '--tia'); + $selected = $project->pestIn($nested, '--tia', '-c', 'phpunit.ci.xml'); + + expect($replayed->replayed())->toBe(Project::TOTAL_TESTS, $replayed->describe()) + ->and($selected->replayed())->toBe(0, $selected->describe()) + ->and($selected->tally())->toContain(Project::TOTAL_TESTS.' passed'); +})->skipOnWindows(); + +test('removing an external declaration with its package does not replay', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master'); + + unset($manifest['autoload']['psr-4']['Shared\\']); + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + $project->git()->run(['rm', '-r', '--quiet', 'packages/shared']); + $project->git()->commit('drop the sibling package and its mapping'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->replayed())->toBe(0, $result->describe()) + ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed'); +})->skipOnWindows(); + +test('an external change runs the full suite once', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master'); + + $project->write('packages/shared/src/Shared.php', "git()->commit('rework the sibling package'); + + $first = $project->pestIn($nested, '--tia'); + $second = $project->pestIn($nested, '--tia'); + + expect($first->output)->toContain('this project loads from outside its root') + ->and($first->replayed())->toBe(0, $first->describe()) + ->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe()); +})->skipOnWindows(); + +test('a relative configuration path resolves against the directory the command ran in', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('packages/shared/bootstrap.php', "write('nested/phpunit.ci.xml', str_replace( + 'bootstrap="vendor/autoload.php"', + 'bootstrap="../packages/shared/bootstrap.php"', + (string) file_get_contents($nested.'/phpunit.xml'), + )); + $project->git()->commit('add a second configuration'); + $project->seedFor($nested, 'master', arguments: ['-c', $project->path('nested/phpunit.ci.xml')]); + + $project->write('packages/shared/bootstrap.php', "git()->commit('rework the sibling bootstrap file'); + $project->snapshot(); + + $result = $project->pestFrom($nested, $project->path(), '--tia', '-c', 'nested/phpunit.ci.xml'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a change in a bootstrap file that the command line names runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('packages/shared/bootstrap.php', "git()->commit('add a sibling bootstrap file'); + $project->seedFor($nested, 'master', arguments: ['--bootstrap', '../packages/shared/bootstrap.php']); + + $project->write('packages/shared/bootstrap.php', "git()->commit('rework the sibling bootstrap file'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia', '--bootstrap', '../packages/shared/bootstrap.php'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a change under an include path that the command line names runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('packages/shared/src/Shared.php', "git()->commit('add a sibling package'); + $project->seedFor($nested, 'master', arguments: ['--include-path', '../packages/shared/src']); + + $project->write('packages/shared/src/Shared.php', "git()->commit('rework the sibling package'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia', '--include-path', '../packages/shared/src'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a change to an ignored file under an include path that the command line names runs the full suite', function (): void { + [$project, $nested] = tiaMonorepoWithIgnoredInput(); + + $project->write('packages/shared/generated.php', "snapshot(); + + $result = $project->pestIn($nested, '--tia', '--include-path', '../packages/shared'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->output)->toContain('packages/shared/generated.php') + ->and($result->replayed())->toBe(0, $result->describe()) + ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed'); +})->skipOnWindows(); + +test('a change to an ignored data file under an include path runs the full suite', function (): void { + [$project, $nested] = tiaMonorepoWithIgnoredInput(); + + $project->write('packages/shared/generated.json', "{\"version\": 2}\n"); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia', '--include-path', '../packages/shared'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('packages/shared/generated.json') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('an ignored file under an include path that does not change keeps the replay', function (): void { + [$project, $nested] = tiaMonorepoWithIgnoredInput(); + + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia', '--include-path', '../packages/shared'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->not->toContain('packages/shared/generated.php') + ->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe()); +})->skipOnWindows(); + +test('deleting an ignored file under an include path runs the full suite', function (): void { + [$project, $nested] = tiaMonorepoWithIgnoredInput(); + + unlink($project->path('packages/shared/generated.php')); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia', '--include-path', '../packages/shared'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('packages/shared/generated.php') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a change under an include path that the configuration names runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('packages/shared/src/Shared.php', "write('nested/phpunit.xml', str_replace( + '', + " \n ../packages/shared/src\n \n", + (string) file_get_contents($nested.'/phpunit.xml'), + )); + $project->git()->commit('point the configuration at a sibling include path'); + $project->seedFor($nested, 'master'); + + $project->write('packages/shared/src/Shared.php', "git()->commit('rework the sibling package'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a submodule that a commit moves runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $library = $project->path().'-library'; + mkdir($library, 0755, true); + $libraryRepo = new GitRepo($library); + file_put_contents($library.'/Shared.php', "init('master'); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->git()->run(['-c', 'protocol.file.allow=always', 'submodule', 'add', '--quiet', $library, 'packages/shared']); + $project->git()->commit('add the library as a submodule'); + $project->seedFor($nested, 'master'); + + file_put_contents($library.'/Shared.php', "commit('rework the library'); + + new GitRepo($project->path('packages/shared'))->run(['-c', 'protocol.file.allow=always', 'pull', '--quiet', 'origin', 'master']); + $project->git()->commit('bump the submodule'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a run from the repository root reads the configuration it finds there', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('packages/shared/bootstrap.php', "write('phpunit.xml', str_replace( + 'bootstrap="vendor/autoload.php"', + 'bootstrap="packages/shared/bootstrap.php"', + (string) file_get_contents($nested.'/phpunit.xml'), + )); + $project->git()->commit('add a configuration at the repository root'); + $project->seedFor($nested, 'master', arguments: ['-c', $project->path('phpunit.xml')]); + + $project->write('packages/shared/bootstrap.php', "git()->commit('rework the sibling bootstrap file'); + $project->snapshot(); + + $result = $project->pestFrom($nested, $project->path(), '--tia'); + + expect($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a project that loads from outside its repository never replays', function (): void { + [$project, $nested] = tiaMonorepo(); + + $outside = $project->path().'-outside'; + mkdir($outside, 0755, true); + file_put_contents($outside.'/bootstrap.php', "write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + $project->git()->commit('load a file from outside the repository'); + $project->seedFor($nested, 'master'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('whose changes git cannot report') + ->and($result->output)->toContain('recording nothing') + ->and($result->replayed())->toBe(0, $result->describe()) + ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed') + ->and($project->delta()->baselineUntouched('master'))->toBeTrue($project->delta()->summary()); +})->skipOnWindows(); + +test('a run without tia records no result while the project loads from outside its repository', function (): void { + [$project, $nested] = tiaMonorepo(); + + $outside = $project->path().'-outside'; + mkdir($outside, 0755, true); + file_put_contents($outside.'/bootstrap.php', "write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + $project->git()->commit('load a file from outside the repository'); + $project->seedFor($nested, 'master'); + $project->snapshot(); + + $result = $project->pestIn($nested); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($project->delta()->baselineUntouched('master'))->toBeTrue($project->delta()->summary()); +})->skipOnWindows(); + +test('an uncommitted change outside the project records nothing', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master'); + + $project->write('packages/shared/src/Shared.php', "snapshot(); + + $dirty = $project->pestIn($nested, '--tia'); + $delta = $project->delta(); + + expect($dirty->output)->toContain('recording nothing') + ->and($dirty->replayed())->toBe(0, $dirty->describe()) + ->and($delta->writtenCount())->toBe(0, $delta->summary()); + + $project->write('packages/shared/src/Shared.php', "pestIn($nested, '--tia'); + + expect($restored->replayed())->toBe(Project::TOTAL_TESTS, $restored->describe()); +})->skipOnWindows(); + +test('a committed change under a wildcard source directory runs the full suite', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('nested/phpunit.xml', str_replace( + './app', + './app'."\n".' ../packages/*/src', + (string) file_get_contents($nested.'/phpunit.xml'), + )); + $project->write('packages/shared/src/Shared.php', "git()->commit('watch every package source directory'); + $project->seedFor($nested, 'master'); + + $project->write('packages/shared/src/Shared.php', "git()->commit('rework the package'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('this project loads from outside its root') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('an uncommitted change outside the project records nothing on a first run', function (array $arguments): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + + $project->detachGraph(); + + $project->write('packages/shared/src/Shared.php', "pestIn($nested, '--tia', ...$arguments); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('recording nothing') + ->and($project->graphExists())->toBeFalse(); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); + +test('an uncommitted change outside the project records nothing on a fresh run', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master'); + $project->snapshot(); + + $project->write('packages/shared/src/Shared.php', "pestIn($nested, '--tia', '--fresh'); + $delta = $project->delta(); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('recording nothing') + ->and($delta->writtenCount())->toBe(0, $delta->summary()); +})->skipOnWindows(); + +test('an uncommitted change outside the project records no result on a partial run', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master', failing: ['adds two numbers']); + + $project->write('packages/shared/src/Shared.php', "snapshot(); + + $dirty = $project->pestIn($nested, '--tia', '--filter=adds two numbers'); + $delta = $project->delta(); + + expect($dirty->tally())->toContain('1 passed') + ->and($delta->writtenCount())->toBe(0, $delta->summary()); + + $project->write('packages/shared/src/Shared.php', "snapshot(); + + $clean = $project->pestIn($nested, '--tia', '--filter=adds two numbers'); + $delta = $project->delta(); + + expect($clean->tally())->toContain('1 passed') + ->and($delta->writtenCount())->toBe(1, $delta->summary()); +})->skipOnWindows(); + +test('editing a configuration that git ignores stops the replay', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('nested/.gitignore', "phpunit.xml\n"); + $project->git()->run(['rm', '--cached', '--quiet', 'nested/phpunit.xml']); + $project->git()->commit('stop tracking the configuration'); + $project->seedFor($nested, 'master'); + $project->snapshot(); + + $replayed = $project->pestIn($nested, '--tia'); + + $project->write('nested/phpunit.xml', str_replace( + 'failOnRisky="true"', + 'failOnRisky="false"', + (string) file_get_contents($nested.'/phpunit.xml'), + )); + + $edited = $project->pestIn($nested, '--tia'); + + expect($replayed->replayed())->toBe(Project::TOTAL_TESTS, $replayed->describe()) + ->and($edited->replayed())->toBe(0, $edited->describe()) + ->and($edited->tally())->toContain(Project::TOTAL_TESTS.' passed'); +})->skipOnWindows(); + +test('a run with --no-configuration does not replay a graph recorded with one', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->seedFor($nested, 'master'); + $project->snapshot(); + + $replayed = $project->pestIn($nested, '--tia'); + $suppressed = $project->pestIn($nested, '--tia', '--no-configuration'); + + expect($replayed->replayed())->toBe(Project::TOTAL_TESTS, $replayed->describe()) + ->and($suppressed->replayed())->toBe(0, $suppressed->describe()); +})->skipOnWindows(); + +test('a run without tia finishes when git cannot read the working tree of a project that loads from outside its root', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master'); + + file_put_contents($project->path('.git/index'), 'not an index'); + + $result = $project->pestIn($nested); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->not->toContain('could not read the git repository') + ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed'); +})->skipOnWindows(); + +test('a committed change outside the project without a coverage driver stores the results of the full suite', function (array $arguments): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master', failing: ['adds two numbers']); + + $project->write('packages/shared/src/Shared.php', "git()->commit('rework the sibling package'); + + $result = $project->pestWithEnvironment($nested, ['XDEBUG_MODE' => 'off'], '--tia', ...$arguments); + + $testId = Project::testId('tests/Unit/CalculatorTest.php', 'adds two numbers'); + $stored = $project->graph()['baselines']['master']['results'][$testId]['status'] ?? null; + + expect($result->output)->toContain('this project loads from outside its root') + ->and($result->output)->toContain('so edges can be safely refreshed after changes outside the project root') + ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed') + ->and($stored)->toBe(0, $result->describe()); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); + +test('a run without tia stores no result when git cannot read the working tree of a project that loads from outside its root', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master', failing: ['adds two numbers']); + + $project->write('packages/shared/src/Shared.php', "path('.git/index'), 'not an index'); + $project->snapshot(); + + $result = $project->pestIn($nested); + $delta = $project->delta(); + + expect($result->tally())->toContain(Project::TOTAL_TESTS.' passed') + ->and($delta->writtenCount())->toBe(0, $delta->summary()); +})->skipOnWindows(); + +test('an edit outside the project during the run records no result', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "write('nested/tests/Unit/SharedEditTest.php', <<<'PHP_WRAP' +toBeTrue(); +}); +PHP_WRAP); + $project->git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master', failing: ['adds two numbers']); + $project->snapshot(); + + $result = $project->pestWithEnvironment($nested, ['XDEBUG_MODE' => 'off'], '--tia'); + $delta = $project->delta(); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and((string) file_get_contents($project->path('packages/shared/src/Shared.php')))->toContain('$shared = 2;') + ->and($delta->writtenCount())->toBe(0, $delta->summary()); +})->skipOnWindows(); + +test('an edit outside the project during the run keeps the recorded commit', function (): void { + [$project, $nested] = tiaMonorepo(); + + $manifest = json_decode((string) file_get_contents($nested.'/composer.json'), true); + $manifest['autoload']['psr-4']['Shared\\'] = '../packages/shared/src'; + $project->write('nested/composer.json', (string) json_encode($manifest, JSON_PRETTY_PRINT)); + + $project->write('packages/shared/src/Shared.php', "write('nested/tests/Unit/SharedEditTest.php', <<<'PHP_WRAP' +toBeTrue(); +}); +PHP_WRAP); + $project->git()->commit('let the project load a sibling package'); + $project->seedFor($nested, 'master'); + $recorded = $project->git()->sha(); + + $project->write('nested/app/Greeter.php', file_get_contents($nested.'/app/Greeter.php')."\n"); + $project->git()->commit('touch the greeter'); + + $result = $project->pestWithEnvironment($nested, ['XDEBUG_MODE' => 'off'], '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('changed during the run — keeping the baseline from before the run') + ->and($project->graph()['baselines']['master']['sha'] ?? null)->toBe($recorded); +})->skipOnWindows(); + +test('an edit to an ignored file outside the project during the run keeps the baseline from before the run', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('.gitignore', file_get_contents($project->path('.gitignore'))."packages/shared/generated.php\n"); + $project->write('packages/shared/Shared.php', "write('packages/shared/generated.php', "write('nested/tests/Unit/GeneratedEditTest.php', <<<'PHP_WRAP' +toBe(1); + + file_put_contents($generated, "git()->commit('add a sibling package with a generated file'); + $project->seedFor($nested, 'master', failing: ['adds two numbers'], arguments: ['--include-path', '../packages/shared']); + $recorded = $project->git()->sha(); + $project->snapshot(); + + $first = $project->pestWithEnvironment($nested, ['XDEBUG_MODE' => 'off'], '--tia', '--include-path', '../packages/shared'); + $afterFirst = $project->graph()['baselines']['master']['sha'] ?? null; + $delta = $project->delta(); + $second = $project->pestWithEnvironment($nested, ['XDEBUG_MODE' => 'off'], '--tia', '--include-path', '../packages/shared'); + + expect($first->output)->toContain('changed during the run — keeping the baseline from before the run') + ->and($first->output)->toContain('packages/shared/generated.php') + ->and($first->output)->toContain('Keep what the run writes out of the paths this project loads') + ->and($delta->writtenCount())->toBe(0, $delta->summary()) + ->and($afterFirst)->toBe($recorded) + ->and($second->output)->toContain('packages/shared/generated.php') + ->and($second->replayed())->toBe(0, $second->describe()); +})->skipOnWindows(); + +test('an edit to a tracked and an ignored file outside the project during the run names the ignored file', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('.gitignore', file_get_contents($project->path('.gitignore'))."packages/shared/generated.php\n"); + $project->write('packages/shared/Shared.php', "write('packages/shared/generated.php', "write('nested/tests/Unit/BothEditTest.php', <<<'PHP_WRAP' +toBeTrue(); +}); +PHP_WRAP); + $project->git()->commit('add a sibling package with a generated file'); + $project->seedFor($nested, 'master', arguments: ['--include-path', '../packages/shared']); + + $result = $project->pestWithEnvironment($nested, ['XDEBUG_MODE' => 'off'], '--tia', '--include-path', '../packages/shared'); + + expect($result->output)->toContain('changed during the run') + ->and($result->output)->toContain('packages/shared/generated.php') + ->and($result->output)->toContain('Keep what the run writes out of the paths this project loads') + ->and($result->output)->toContain('Re-run --tia after your edits settle'); +})->skipOnWindows(); + +test('an ignored repository created outside the project during the run keeps the baseline from before the run', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('.gitignore', file_get_contents($project->path('.gitignore'))."packages/shared/checkout/\n"); + $project->write('packages/shared/Shared.php', "write('nested/tests/Unit/CheckoutTest.php', <<<'PHP_WRAP' +toBeTrue(); +}); +PHP_WRAP); + $project->git()->commit('add a sibling package'); + $project->seedFor($nested, 'master', failing: ['adds two numbers'], arguments: ['--include-path', '../packages/shared']); + $recorded = $project->git()->sha(); + $project->snapshot(); + + $result = $project->pestWithEnvironment($nested, ['XDEBUG_MODE' => 'off'], '--tia', '--include-path', '../packages/shared'); + $delta = $project->delta(); + + expect($result->output)->toContain('changed during the run — keeping the baseline from before the run') + ->and($result->output)->toContain('packages/shared/checkout') + ->and($delta->writtenCount())->toBe(0, $delta->summary()) + ->and($project->graph()['baselines']['master']['sha'] ?? null)->toBe($recorded); +})->skipOnWindows(); + +test('an ignored file whose name is not utf-8 created outside the project during the run keeps the baseline from before the run', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('.gitignore', file_get_contents($project->path('.gitignore'))."packages/shared/*.txt\n"); + $project->write('packages/shared/Shared.php', "write('nested/tests/Unit/NameTest.php', <<<'PHP_WRAP' +toBeTrue(); +}); +PHP_WRAP); + $project->git()->commit('add a sibling package'); + $project->seedFor($nested, 'master', failing: ['adds two numbers'], arguments: ['--include-path', '../packages/shared']); + $recorded = $project->git()->sha(); + $project->snapshot(); + + $result = $project->pestWithEnvironment($nested, ['XDEBUG_MODE' => 'off'], '--tia', '--include-path', '../packages/shared'); + $delta = $project->delta(); + + expect($result->output)->toContain('changed during the run — keeping the baseline from before the run') + ->and($delta->writtenCount())->toBe(0, $delta->summary()) + ->and($project->graph()['baselines']['master']['sha'] ?? null)->toBe($recorded); +})->skip(PHP_OS_FAMILY !== 'Linux', 'Only Linux file systems accept names that are not utf-8.'); + +test('an ignored repository created around a declared path during the run keeps the baseline from before the run', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('.gitignore', file_get_contents($project->path('.gitignore'))."packages/shared/checkout/\n"); + mkdir($project->path('packages/shared/checkout/src'), 0755, true); + $project->write('nested/tests/Unit/CheckoutAroundTest.php', <<<'PHP_WRAP' +toBeTrue(); +}); +PHP_WRAP); + $project->git()->commit('add a sibling package'); + $project->seedFor($nested, 'master', failing: ['adds two numbers'], arguments: ['--include-path', '../packages/shared/checkout/src']); + $recorded = $project->git()->sha(); + $project->snapshot(); + + $result = $project->pestWithEnvironment($nested, ['XDEBUG_MODE' => 'off'], '--tia', '--include-path', '../packages/shared/checkout/src'); + $delta = $project->delta(); + + expect($result->output)->toContain('changed during the run — keeping the baseline from before the run') + ->and($delta->writtenCount())->toBe(0, $delta->summary()) + ->and($project->graph()['baselines']['master']['sha'] ?? null)->toBe($recorded); +})->skipOnWindows(); + +test('a run without tia stores no result when a hook leaves the configuration directory and the phpunit bootstrap outside the project is dirty', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('packages/shared/bootstrap.php', "write('nested/phpunit.xml', str_replace( + 'bootstrap="vendor/autoload.php"', + 'bootstrap="../packages/shared/bootstrap.php"', + (string) file_get_contents($nested.'/phpunit.xml'), + )); + $project->write('nested/tests/Unit/LeavesDirectoryTest.php', <<<'PHP_WRAP' +toBeTrue(); +}); +PHP_WRAP); + $project->git()->commit('point the project at a sibling bootstrap file'); + $project->seedFor($nested, 'master', failing: ['adds two numbers']); + + $project->write('packages/shared/bootstrap.php', "snapshot(); + + $result = $project->pestIn($nested); + $delta = $project->delta(); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($delta->writtenCount())->toBe(0, $delta->summary()); +})->skipOnWindows(); diff --git a/tests/Fixtures/Tia/Project.php b/tests/Fixtures/Tia/Project.php index bd559300..8dbdfce3 100644 --- a/tests/Fixtures/Tia/Project.php +++ b/tests/Fixtures/Tia/Project.php @@ -9,6 +9,7 @@ use Pest\Plugins\Tia; use Pest\Plugins\Tia\ByteSafeJson; use Pest\Plugins\Tia\ChangedFiles; use Pest\Plugins\Tia\ConfigurationFile; +use Pest\Plugins\Tia\ExternalSources; use Pest\Plugins\Tia\FileState; use Pest\Plugins\Tia\Fingerprint; use Pest\Plugins\Tia\Graph; @@ -161,14 +162,28 @@ final class Project return $this->pestWithEnvironment($directory, [], ...$arguments); } + public function pestFrom(string $directory, string $workingDirectory, string ...$arguments): PestResult + { + return $this->run($directory, $workingDirectory, [], array_values($arguments)); + } + /** * @param array $environment */ public function pestWithEnvironment(string $directory, array $environment, string ...$arguments): PestResult + { + return $this->run($directory, $directory, $environment, array_values($arguments)); + } + + /** + * @param array $environment + * @param array $arguments + */ + private function run(string $directory, string $workingDirectory, array $environment, array $arguments): PestResult { $process = new Process( [PHP_BINARY, $directory.'/vendor/pestphp/pest/bin/pest', ...$arguments], - $directory, + $workingDirectory, [ ...GitRepo::ENV, 'COLLISION_PRINTER' => 'DefaultPrinter', @@ -185,6 +200,7 @@ final class Project 'GITHUB_REF_NAME' => false, 'GITLAB_CI' => false, 'CIRCLECI' => false, + 'COMPOSER' => false, ...$environment, ], ); @@ -193,7 +209,7 @@ final class Project $process->run(); return new PestResult( - array_values($arguments), + $arguments, $process->getOutput().$process->getErrorOutput(), (int) $process->getExitCode(), ); @@ -204,24 +220,50 @@ final class Project */ public function seed(string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void { - $this->seedFor($this->path, $branch, $sentinel, $failing, $configuration); + $this->seedFor($this->path, $branch, $sentinel, $failing, $configuration === null ? [] : ['--configuration', $configuration]); } /** * @param array $failing + * @param array $arguments */ - public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void + public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = [], array $arguments = []): void { $this->graphRoot = $root; + ExternalSources::flush(); + + $previous = getcwd(); + + if ($previous !== false) { + chdir($root); + } + + try { + $this->seedGraphFor($root, $branch, $sentinel, $failing, $arguments); + } finally { + if ($previous !== false) { + chdir($previous); + } + } + } + + /** + * @param array $failing + * @param array $arguments + */ + private function seedGraphFor(string $root, string $branch, bool $sentinel, array $failing, array $arguments): void + { + putenv('COMPOSER'); + $changedFiles = new ChangedFiles($root); $sha = new GitRepo($root)->sha(); $graph = new Graph($root); - $graph->setFingerprint(Fingerprint::compute($root, $configuration === null ? null : ConfigurationFile::at($root.DIRECTORY_SEPARATOR.$configuration))); + $graph->setFingerprint(Fingerprint::compute($root, ConfigurationFile::fromArguments($arguments), $arguments)); $graph->setRecordedAtSha($branch, $sha); - $graph->setLastRunTree($branch, $changedFiles->snapshotTree($changedFiles->since($sha) ?? [])); + $graph->setLastRunTree($branch, $changedFiles->baselineTree($sha, ExternalSources::ignoredInputs($root, $arguments))); $graph->markKnownTestFiles(array_keys(self::EDGES)); diff --git a/tests/Unit/Plugins/Tia/ChangedFiles.php b/tests/Unit/Plugins/Tia/ChangedFiles.php index 7d329627..aa9d9765 100644 --- a/tests/Unit/Plugins/Tia/ChangedFiles.php +++ b/tests/Unit/Plugins/Tia/ChangedFiles.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Pest\Plugins\Tia\ChangedFiles; +use Pest\Plugins\Tia\ExternalSources; use Pest\Plugins\Tia\Fingerprint; use Symfony\Component\Process\Process; use Tests\Fixtures\Tia\GitRepo; @@ -289,6 +290,21 @@ it('reads committed paths from the repository root even when git is told to be r ->and($changedFiles->outsideProject())->toBe(['frontend/widget.php']); })->skipOnWindows(); +it('tells a working tree change outside the project from a committed one', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['root'].'/frontend/widget.php', "commit('rework the widget'); + + file_put_contents($monorepo['root'].'/frontend/other.php', "since($monorepo['sha']); + + expect($changedFiles->outsideProject())->toBe(['frontend/widget.php', 'frontend/other.php']) + ->and($changedFiles->outsideProjectDirty())->toBe(['frontend/other.php']); +})->skipOnWindows(); + it('keeps a changed file whose name is a number as a string', function (): void { $project = Project::make(); $sha = $project->git()->sha(); @@ -312,6 +328,106 @@ it('keeps a changed file outside the project whose name is a number as a string' ->and($changedFiles->outsideProject())->toBe(['123']); })->skipOnWindows(); +it('matches no external root for a changed file whose name is a number', function (): void { + $monorepo = tiaMonorepoRepository(); + $previous = (string) getcwd(); + + mkdir($monorepo['root'].'/packages/shared/src', 0755, true); + file_put_contents($monorepo['root'].'/packages/shared/src/Shared.php', " ['psr-4' => ['Shared\\' => '../packages/shared/src']], + ], JSON_PRETTY_PRINT)); + $monorepo['repo']->commit('let the project load a sibling package'); + $sha = $monorepo['repo']->sha(); + + file_put_contents($monorepo['root'].'/123', "changed\n"); + $monorepo['repo']->commit('add a file with a numeric name'); + + chdir($monorepo['project']); + ExternalSources::flush(); + + try { + $changedFiles = new ChangedFiles($monorepo['project']); + $changedFiles->since($sha); + + $matched = ExternalSources::matching($monorepo['project'], $changedFiles->outsideProject()); + } finally { + chdir($previous); + ExternalSources::flush(); + } + + expect($matched)->toBeEmpty(); +})->skipOnWindows(); + +it('hashes an external input without reading it into memory', function (): void { + $monorepo = tiaMonorepoRepository(); + + $handle = fopen($monorepo['root'].'/frontend/database.sqlite', 'wb'); + ftruncate($handle, 64 * 1024 * 1024); + fclose($handle); + + $changedFiles = new ChangedFiles($monorepo['project']); + + memory_reset_peak_usage(); + $before = memory_get_peak_usage(); + + $tree = $changedFiles->baselineTree($monorepo['sha'], ['frontend/database.sqlite']); + + expect(memory_get_peak_usage() - $before)->toBeLessThan(8 * 1024 * 1024) + ->and($tree)->toHaveKey('../frontend/database.sqlite'); +})->skipOnWindows(); + +it('sees a whitespace change inside an external input', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['root'].'/frontend/data.js', "export default \"a b\";\n"); + + $changedFiles = new ChangedFiles($monorepo['project']); + $tree = $changedFiles->baselineTree($monorepo['sha'], ['frontend/data.js']); + + file_put_contents($monorepo['root'].'/frontend/data.js', "export default \"a b\";\n"); + + expect($changedFiles->changedSinceLastRun([], ['frontend/data.js'], $tree))->toBe([[], ['frontend/data.js']]); +})->skipOnWindows(); + +it('reports a changed file whose name looks like a pathspec', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['project'].'/:(fixtures).php', "since($monorepo['sha']))->toContain(':(fixtures).php'); +})->skipOnWindows(); + +it('reports an external input that the listing no longer names', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['root'].'/frontend/generated.php', "externalInputHashes(['frontend/generated.php']); + + expect($changedFiles->changedExternalInputs($before, $changedFiles->externalInputHashes([])))->toBe(['frontend/generated.php']) + ->and($changedFiles->changedExternalInputs($before, $changedFiles->externalInputHashes(['frontend/generated.php'])))->toBeEmpty(); +})->skipOnWindows(); + +it('reports no change for an external input it cannot read', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['root'].'/frontend/secret.php', "changedExternalInputs( + $changedFiles->externalInputHashes(['frontend/secret.php']), + $changedFiles->externalInputHashes(['frontend/secret.php']), + ))->toBeEmpty(); + } finally { + chmod($monorepo['root'].'/frontend/secret.php', 0644); + } +})->skipOnWindows()->skip(function_exists('posix_geteuid') && posix_geteuid() === 0, 'root reads every file.'); + it('keeps a snapshotted file whose name is a number as a string', function (): void { $project = Project::make(); diff --git a/tests/Unit/Plugins/Tia/ExternalSources.php b/tests/Unit/Plugins/Tia/ExternalSources.php new file mode 100644 index 00000000..cbc1c56b --- /dev/null +++ b/tests/Unit/Plugins/Tia/ExternalSources.php @@ -0,0 +1,1243 @@ + + */ +function tiaExternalRoots(?string $created = null): array +{ + static $roots = []; + + if ($created !== null) { + $roots[] = $created; + + return $roots; + } + + $all = $roots; + $roots = []; + + return $all; +} + +/** + * @param array $manifest + * @return array{root: string, project: string} + */ +function tiaExternalRepository(array $manifest = [], ?string $phpunit = null): array +{ + $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-external-'.bin2hex(random_bytes(8)); + + mkdir($root.'/backend/app', 0755, true); + mkdir($root.'/packages/shared/src', 0755, true); + + file_put_contents($root.'/backend/app/Service.php', "init('master'); + + chdir($root.'/backend'); + ExternalSources::flush(); + + return ['root' => $root, 'project' => $root.'/backend']; +} + +/** + * @param array $arguments + * @return array + */ +function tiaRootsFrom(string $workingDirectory, string $projectRoot, array $arguments): array +{ + $previous = getcwd(); + + chdir($workingDirectory); + + try { + ExternalSources::flush(); + + return ExternalSources::rootsFor($projectRoot, $arguments); + } finally { + chdir((string) $previous); + } +} + +/** + * @param array $arguments + * @return array + */ +function tiaUnverifiableFrom(string $workingDirectory, string $projectRoot, array $arguments): array +{ + $previous = getcwd(); + + chdir($workingDirectory); + + try { + ExternalSources::flush(); + + return ExternalSources::unverifiable($projectRoot, $arguments); + } finally { + chdir((string) $previous); + } +} + +beforeEach(function (): void { + putenv('COMPOSER'); + ExternalSources::flush(); + tiaExternalCwd((string) getcwd()); +}); + +afterEach(function (): void { + chdir(tiaExternalCwd()); + + foreach (tiaExternalRoots() as $root) { + new Process(['rm', '-rf', $root])->run(); + } + + ExternalSources::flush(); +}); + +it('finds a psr-4 root that escapes the project', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['App\\' => 'app/', 'Shared\\' => '../packages/shared/src']], + ]); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/shared/src/']); +})->skipOnWindows(); + +it('finds a path repository', function (): void { + $repository = tiaExternalRepository([ + 'repositories' => [['type' => 'path', 'url' => '../packages/shared']], + ]); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/shared/']); +})->skipOnWindows(); + +it('finds a phpunit source directory outside the project', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + app + ../packages/shared/src + + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], []))->toBe(['packages/shared/src/']); +})->skipOnWindows(); + +it('finds nothing when the project only loads its own code', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['App\\' => 'app/'], 'files' => ['app/Service.php']], + ]); + + expect(ExternalSources::rootsFor($repository['project']))->toBeEmpty(); +})->skipOnWindows(); + +it('finds nothing for a project at the repository root', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['Shared\\' => '../packages/shared/src']], + ]); + + expect(ExternalSources::rootsFor($repository['root']))->toBeEmpty(); +})->skipOnWindows(); + +it('reports a root that sits outside the repository as unverifiable', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['Tmp\\' => '../../']], + ]); + + expect(ExternalSources::rootsFor($repository['project']))->toBeEmpty() + ->and(ExternalSources::unverifiable($repository['project']))->not->toBeEmpty(); +})->skipOnWindows(); + +it('reports nothing unverifiable when every declaration stays inside the repository', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['Shared\\' => '../packages/shared/src', 'App\\' => 'app']], + ]); + + expect(ExternalSources::unverifiable($repository['project']))->toBeEmpty(); +})->skipOnWindows(); + +it('reports a bootstrap outside the repository as unverifiable', function (): void { + $repository = tiaExternalRepository(); + + $outside = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-outside-'.bin2hex(random_bytes(8)).'.php'; + file_put_contents($outside, "toBe([str_replace(DIRECTORY_SEPARATOR, '/', (string) realpath(dirname($outside))).'/'.basename($outside)]); +})->skipOnWindows(); + +it('matches only the changes that fall under an external root', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['Shared\\' => '../packages/shared/src']], + ]); + + $matched = ExternalSources::matching($repository['project'], [ + 'packages/shared/src/Shared.php', + 'packages/other/src/Other.php', + 'frontend/widget.php', + ]); + + expect($matched)->toBe(['packages/shared/src/Shared.php']); +})->skipOnWindows(); + +it('finds an autoload file that escapes the project and matches it exactly', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['files' => ['../packages/shared/bootstrap.php']], + ]); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/shared/bootstrap.php']) + ->and(ExternalSources::matching($repository['project'], ['packages/shared/bootstrap.php'])) + ->toBe(['packages/shared/bootstrap.php']); +})->skipOnWindows(); + +it('finds a phpunit bootstrap that escapes the project', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + app + + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], []))->toBe(['packages/shared/bootstrap.php']); +})->skipOnWindows(); + +it('keeps a declared root that no longer exists on disk', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['Shared\\' => '../packages/shared/src']], + ]); + + new Process(['rm', '-rf', $repository['root'].'/packages/shared'])->mustRun(); + + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/shared/src/']) + ->and(ExternalSources::matching($repository['project'], ['packages/shared/src/Shared.php'])) + ->toBe(['packages/shared/src/Shared.php']); +})->skipOnWindows(); + +it('treats a classmap entry as a file only when it names one', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['classmap' => ['../packages/shared/src', '../packages/shared/bootstrap.php']], + ]); + + expect(ExternalSources::rootsFor($repository['project'])) + ->toBe(['packages/shared/bootstrap.php', 'packages/shared/src/']); +})->skipOnWindows(); + +it('finds a testsuite directory outside the project', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + ./tests + ../packages/shared/tests + ../packages/shared/tests/OneTest.php + + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], []))->toBe([ + 'packages/shared/tests/', + 'packages/shared/tests/OneTest.php', + ]); +})->skipOnWindows(); + +it('keeps the directory before a wildcard in a path repository', function (): void { + $repository = tiaExternalRepository([ + 'repositories' => [['type' => 'path', 'url' => '../packages/*/src']], + ]); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/', 'packages/shared/src/']) + ->and(ExternalSources::matching($repository['project'], ['packages/foo/src/Service.php'])) + ->toBe(['packages/foo/src/Service.php']); +})->skipOnWindows(); + +it('keeps the directory before a single character wildcard', function (): void { + $repository = tiaExternalRepository([ + 'repositories' => [['type' => 'path', 'url' => '../packages/lib-?/src']], + ]); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/']); +})->skipOnWindows(); + +it('matches a deleted package that a wildcard declared', function (): void { + $repository = tiaExternalRepository([ + 'repositories' => [['type' => 'path', 'url' => '../packages/*']], + ]); + + new Process(['rm', '-rf', $repository['root'].'/packages/shared'])->mustRun(); + + ExternalSources::flush(); + + expect(ExternalSources::matching($repository['project'], ['packages/shared/src/Shared.php'])) + ->toBe(['packages/shared/src/Shared.php']); +})->skipOnWindows(); + +it('covers the whole repository when a declaration reaches its root', function (): void { + $repository = tiaExternalRepository([ + 'repositories' => [['type' => 'path', 'url' => '../*']], + ]); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['', 'packages/']) + ->and(ExternalSources::matching($repository['project'], ['packages/shared/src/Shared.php'])) + ->toBe(['packages/shared/src/Shared.php']); +})->skipOnWindows(); + +it('reads the configuration that the command line selects', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['project'].'/phpunit.ci.xml', <<<'XML_WRAP' + + + + + ../packages/shared/tests + + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['--tia', '-c', 'phpunit.ci.xml']))->toBe([ + 'packages/shared/bootstrap.php', + 'packages/shared/tests/', + ])->and(tiaRootsFrom($repository['project'], $repository['project'], []))->toBeEmpty(); +})->skipOnWindows(); + +it('accepts the configuration argument in its joined form', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['project'].'/phpunit.ci.xml', <<<'XML_WRAP' + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['--configuration=phpunit.ci.xml'])) + ->toBe(['packages/shared/bootstrap.php']); +})->skipOnWindows(); + +it('resolves a configuration path against its own directory', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['root'].'/config', 0755, true); + file_put_contents($repository['root'].'/config/phpunit.xml', <<<'XML_WRAP' + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['-c', '../config/phpunit.xml']))->toBe([ + 'config/phpunit.xml', + 'packages/shared/bootstrap.php', + ]); +})->skipOnWindows(); + +it('follows a symlink that leaves the project', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['Shared\\' => 'shared']], + ]); + + symlink($repository['root'].'/packages/shared/src', $repository['project'].'/shared'); + + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/shared/src/']) + ->and(ExternalSources::matching($repository['project'], ['packages/shared/src/Shared.php'])) + ->toBe(['packages/shared/src/Shared.php']); +})->skipOnWindows(); + +it('keeps a real directory inside the project out of the roots', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['App\\' => 'app']], + ]); + + expect(ExternalSources::rootsFor($repository['project']))->toBeEmpty(); +})->skipOnWindows(); + +it('finds a bootstrap file that the command line names', function (): void { + $repository = tiaExternalRepository(); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['--bootstrap', '../packages/shared/bootstrap.php'])) + ->toBe(['packages/shared/bootstrap.php']); +})->skipOnWindows(); + +it('finds every directory that an include path names', function (): void { + $repository = tiaExternalRepository(); + + $list = '../packages/shared/src'.PATH_SEPARATOR.'app'.PATH_SEPARATOR.'../packages/shared/tests'; + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['--include-path', $list])) + ->toBe(['packages/shared/src/', 'packages/shared/tests/']); +})->skipOnWindows(); + +it('resolves a command line path against the directory the command ran in', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['root'].'/phpunit.ci.xml', <<<'XML_WRAP' + + +XML_WRAP); + + $previous = getcwd(); + chdir($repository['root']); + + try { + $roots = ExternalSources::rootsFor($repository['project'], ['-c', 'phpunit.ci.xml']); + } finally { + chdir((string) $previous); + } + + expect($roots)->toBe(['packages/shared/bootstrap.php', 'phpunit.ci.xml']); +})->skipOnWindows(); + +it('keeps a declaration that a commit deleted under the directory the command ran in', function (): void { + $repository = tiaExternalRepository(); + + new Process(['rm', '-rf', $repository['root'].'/packages'])->mustRun(); + + expect(tiaRootsFrom($repository['root'], $repository['project'], ['--bootstrap', 'packages/shared/bootstrap.php'])) + ->toBe(['app/', 'packages/shared/bootstrap.php', 'src/', 'tests/', 'vendor/autoload.php']); +})->skipOnWindows(); + +it('watches the paths of the configuration Pest generates in the directory the command ran in', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['root'].'/vendor', 0755, true); + file_put_contents($repository['root'].'/.gitignore', "/vendor/\n"); + file_put_contents($repository['root'].'/vendor/autoload.php', "toBe(['vendor/autoload.php']); +})->skipOnWindows(); + +it('treats a classmap directory that carries a dot as a directory', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['classmap' => ['../packages/shared.core']], + ]); + + mkdir($repository['root'].'/packages/shared.core', 0755, true); + + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/shared.core/']) + ->and(ExternalSources::matching($repository['project'], ['packages/shared.core/Service.php'])) + ->toBe(['packages/shared.core/Service.php']); +})->skipOnWindows(); + +it('accepts the configuration argument attached to its short flag', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['project'].'/phpunit.ci.xml', <<<'XML_WRAP' + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['-cphpunit.ci.xml'])) + ->toBe(['packages/shared/bootstrap.php']); +})->skipOnWindows(); + +it('reads no configuration when the run asks for none', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], [])) + ->toBe(['packages/shared/bootstrap.php']) + ->and(tiaRootsFrom($repository['project'], $repository['project'], ['--no-configuration'])) + ->toBeEmpty(); +})->skipOnWindows(); + +it('reads no default configuration when the command line names one', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + +XML_WRAP); + + file_put_contents($repository['project'].'/phpunit.ci.xml', <<<'XML_WRAP' + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['-c', 'phpunit.ci.xml'])) + ->toBeEmpty(); +})->skipOnWindows(); + +it('finds an include path that the configuration names', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + ../packages/shared/src + app + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], [])) + ->toBe(['packages/shared/src/']); +})->skipOnWindows(); + +it('matches a submodule that a commit moved', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['Shared\\' => '../packages/shared/src']], + ]); + + expect(ExternalSources::matching($repository['project'], ['packages/shared'])) + ->toBe(['packages/shared']) + ->and(ExternalSources::matching($repository['project'], ['packages'])) + ->toBe(['packages']) + ->and(ExternalSources::matching($repository['project'], ['packages/other'])) + ->toBeEmpty(); +})->skipOnWindows(); + +it('matches a submodule that holds a declared file', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['files' => ['../packages/shared/bootstrap.php']], + ]); + + expect(ExternalSources::matching($repository['project'], ['packages/shared'])) + ->toBe(['packages/shared']); +})->skipOnWindows(); + +it('reads the configuration of the directory the command ran in', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + +XML_WRAP); + + file_put_contents($repository['root'].'/phpunit.xml', <<<'XML_WRAP' + + +XML_WRAP); + + expect(tiaRootsFrom($repository['root'], $repository['project'], [])) + ->toBe(['packages/shared/src/Shared.php', 'phpunit.xml']); +})->skipOnWindows(); + +it('reads a configuration that a directory argument names', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['root'].'/config', 0755, true); + file_put_contents($repository['root'].'/config/phpunit.xml', <<<'XML_WRAP' + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['-c', '../config'])) + ->toBe(['config/phpunit.xml', 'packages/shared/bootstrap.php']); +})->skipOnWindows(); + +it('reads the dist name that phpunit tries before the older one', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['project'].'/phpunit.dist.xml', <<<'XML_WRAP' + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], [])) + ->toBe(['packages/shared/bootstrap.php']); +})->skipOnWindows(); + +it('finds a bootstrap that a single test suite names', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + ./tests + + + ./tests + + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], [])) + ->toBe(['packages/shared/bootstrap.php']); +})->skipOnWindows(); + +it('watches the directory before a wildcard that a configuration names', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + ../packages/*/src + + + +XML_WRAP); + + $roots = tiaRootsFrom($repository['project'], $repository['project'], []); + + expect($roots)->toBe(['packages/', 'packages/shared/src/']) + ->and(ExternalSources::matching($repository['project'], ['packages/shared/src/Service.php'])) + ->toBe(['packages/shared/src/Service.php']); +})->skipOnWindows(); + +it('lists the files of a root that the repository ignores as ignored inputs', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['Generated\\' => '../packages/generated']], + ]); + + mkdir($repository['root'].'/packages/generated', 0755, true); + file_put_contents($repository['root'].'/.gitignore', "packages/generated/\n"); + file_put_contents($repository['root'].'/packages/generated/Model.php', "toBeEmpty() + ->and(ExternalSources::unverifiable($repository['project']))->toBeEmpty() + ->and(ExternalSources::ignoredInputs($repository['project']))->toBe(['packages/generated/Model.php']); +})->skipOnWindows(); + +it('lists the ignored files under a declared root as ignored inputs', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['root'].'/.gitignore', "packages/shared/generated.php\npackages/shared/notes.txt\npackages/shared/vendor/\npackages/shared/node_modules/\npackages/shared/storage/\n"); + file_put_contents($repository['root'].'/packages/shared/generated.php', "toBe(['packages/shared/generated.php', 'packages/shared/notes.txt']) + ->and(ExternalSources::unverifiable($repository['project'], ['--include-path', '../packages/shared']))->toBeEmpty(); +})->skipOnWindows(); + +it('lists an ignored bootstrap file inside vendor as an ignored input', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + +XML_WRAP); + + mkdir($repository['root'].'/vendor', 0755, true); + file_put_contents($repository['root'].'/.gitignore', "vendor/\n"); + file_put_contents($repository['root'].'/vendor/autoload.php', "toBe(['vendor/autoload.php']); +})->skipOnWindows(); + +it('lists the ignored files under a declared root inside a dot directory', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['root'].'/.shared/.cache', 0755, true); + file_put_contents($repository['root'].'/.gitignore', ".shared/\n"); + file_put_contents($repository['root'].'/.shared/Shared.php', "toBe(['.shared/Shared.php']); +})->skipOnWindows(); + +it('lists an ignored link to a file but no ignored link to a directory or to nothing', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['root'].'/packages/shared/storage', 0755, true); + file_put_contents($repository['root'].'/.gitignore', "packages/shared/public/\n"); + mkdir($repository['root'].'/packages/shared/public', 0755, true); + symlink('../storage', $repository['root'].'/packages/shared/public/storage'); + symlink('../missing', $repository['root'].'/packages/shared/public/dangling'); + symlink('../src/Shared.php', $repository['root'].'/packages/shared/public/shared.php'); + + ExternalSources::flush(); + + expect(ExternalSources::ignoredInputs($repository['project'], ['--include-path', '../packages/shared']))->toBe(['packages/shared/public/shared.php']); +})->skipOnWindows(); + +it('watches the path that composer resolved for a path repository', function (): void { + $repository = tiaExternalRepository([ + 'repositories' => [['type' => 'path', 'url' => '$PEST_TIA_SHARED']], + ]); + + file_put_contents($repository['project'].'/composer.lock', (string) json_encode([ + 'packages' => [['name' => 'acme/shared', 'dist' => ['type' => 'path', 'url' => '../packages/shared']]], + 'packages-dev' => [], + ])); + + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/shared/']); +})->skipOnWindows(); + +it('watches the path that composer installed when the project has no lock file', function (): void { + $repository = tiaExternalRepository([ + 'repositories' => [['type' => 'path', 'url' => '../packages/{shared,other}']], + ]); + + mkdir($repository['project'].'/vendor/composer', 0755, true); + file_put_contents($repository['project'].'/vendor/composer/installed.json', (string) json_encode([ + 'packages' => [['name' => 'acme/shared', 'dist' => ['type' => 'path', 'url' => '../packages/shared']]], + ])); + + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toContain('packages/shared/'); +})->skipOnWindows(); + +it('watches the path that composer installed into a custom vendor directory', function (): void { + $repository = tiaExternalRepository([ + 'config' => ['vendor-dir' => 'deps'], + 'repositories' => [['type' => 'path', 'url' => '$PEST_TIA_SHARED']], + ]); + + mkdir($repository['project'].'/deps/composer', 0755, true); + file_put_contents($repository['project'].'/deps/composer/installed.json', (string) json_encode([ + 'packages' => [['name' => 'acme/shared', 'dist' => ['type' => 'path', 'url' => '../packages/shared']]], + ])); + + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/shared/']); +})->skipOnWindows(); + +it('watches the path that composer installed into the vendor directory the run loaded', function (): void { + $repository = tiaExternalRepository(); + + $vendor = $repository['project'].'/lib/deps'; + mkdir($vendor.'/composer', 0755, true); + file_put_contents($vendor.'/composer/installed.php', " ['install_path' => ".var_export($repository['project'], true)."]];\n"); + file_put_contents($vendor.'/composer/installed.json', (string) json_encode([ + 'packages' => [['name' => 'acme/shared', 'dist' => ['type' => 'path', 'url' => '../packages/shared']]], + ])); + + $loader = new ClassLoader($vendor); + $loader->register(); + + try { + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/shared/']); + } finally { + $loader->unregister(); + } +})->skipOnWindows(); + +it('watches the installed path and the locked path when they differ', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['root'].'/packages/old', 0755, true); + mkdir($repository['project'].'/vendor/composer', 0755, true); + file_put_contents($repository['project'].'/composer.lock', (string) json_encode([ + 'packages' => [['name' => 'acme/shared', 'dist' => ['type' => 'path', 'url' => '../packages/shared']]], + ])); + file_put_contents($repository['project'].'/vendor/composer/installed.json', (string) json_encode([ + 'packages' => [['name' => 'acme/shared', 'dist' => ['type' => 'path', 'url' => '../packages/old']]], + ])); + + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/old/', 'packages/shared/']); +})->skipOnWindows(); + +it('reads a path that composer resolved as a literal path', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['root'].'/packages/odd?', 0755, true); + file_put_contents($repository['project'].'/composer.lock', (string) json_encode([ + 'packages' => [['name' => 'acme/odd', 'dist' => ['type' => 'path', 'url' => '../packages/odd?']]], + ])); + + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/odd?/']); +})->skipOnWindows(); + +it('reads the manifest and the lock file that the COMPOSER variable names', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['project'].'/composer.app.json', (string) json_encode([ + 'autoload' => ['psr-4' => ['Shared\\' => '../packages/shared/src']], + ])); + file_put_contents($repository['project'].'/composer.app.lock', (string) json_encode([ + 'packages' => [['name' => 'acme/odd', 'dist' => ['type' => 'path', 'url' => '../packages/odd']]], + ])); + mkdir($repository['root'].'/packages/odd', 0755, true); + + putenv('COMPOSER= composer.app.json '); + + try { + ExternalSources::flush(); + + expect(ExternalSources::rootsFor($repository['project']))->toBe(['packages/odd/', 'packages/shared/src/']); + } finally { + putenv('COMPOSER'); + } +})->skipOnWindows(); + +it('lists the ignored files when git is told to read every pathspec literally', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['root'].'/.gitignore', "packages/shared/generated.php\n"); + file_put_contents($repository['root'].'/packages/shared/generated.php', "toBe(['packages/shared/generated.php']); + } finally { + putenv('GIT_LITERAL_PATHSPECS'); + unset($_SERVER['GIT_LITERAL_PATHSPECS']); + } +})->skipOnWindows(); + +it('treats a network path as absolute on Windows', function (): void { + $isAbsolute = new ReflectionMethod(ExternalSources::class, 'isAbsolute'); + + expect($isAbsolute->invoke(null, '\\\\server\\share\\composer.app.json'))->toBeTrue(); +})->skip(PHP_OS_FAMILY !== 'Windows', 'Network paths only exist on Windows.'); + +it('reports an ignored repository under a declared root as unverifiable', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['root'].'/.gitignore', "packages/shared/checkout/\n"); + mkdir($repository['root'].'/packages/shared/checkout', 0755, true); + new GitRepo($repository['root'].'/packages/shared/checkout')->init('master'); + + ExternalSources::flush(); + + $root = str_replace(DIRECTORY_SEPARATOR, '/', (string) realpath($repository['root'])); + + expect(ExternalSources::unverifiable($repository['project'], ['--include-path', '../packages/shared']))->toBe([$root.'/packages/shared/checkout']); +})->skipOnWindows(); + +it('reports an ignored file under a declared root whose name is not utf-8 as unverifiable', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['root'].'/.gitignore', "packages/shared/*.txt\n"); + + file_put_contents($repository['root']."/packages/shared/caf\xe9.txt", "x\n"); + file_put_contents($repository['root'].'/packages/shared/notes.txt', "x\n"); + + ExternalSources::flush(); + + $root = str_replace(DIRECTORY_SEPARATOR, '/', (string) realpath($repository['root'])); + + expect(ExternalSources::ignoredInputs($repository['project'], ['--include-path', '../packages/shared']))->toBe(['packages/shared/notes.txt']) + ->and(ExternalSources::unverifiable($repository['project'], ['--include-path', '../packages/shared']))->toBe([$root."/packages/shared/caf\xe9.txt"]); +})->group('integration', 'tia')->skip(PHP_OS_FAMILY !== 'Linux', 'Only Linux file systems accept names that are not utf-8.'); + +it('finds a root that the repository ignores next to a file whose name looks like a pathspec', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['files' => ['../:(fixtures).php', '../packages/generated.php']], + ]); + + file_put_contents($repository['root'].'/.gitignore', "packages/generated.php\n"); + file_put_contents($repository['root'].'/:(fixtures).php', "toBe(['packages/generated.php']); +})->skipOnWindows(); + +it('reports no repository that sits in a noise directory under a declared root as unverifiable', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['root'].'/.gitignore', "vendor/\n.tools/\n"); + mkdir($repository['root'].'/packages/shared/vendor/acme/pkg', 0755, true); + mkdir($repository['root'].'/packages/shared/.tools/tool', 0755, true); + new GitRepo($repository['root'].'/packages/shared/vendor/acme/pkg')->init('master'); + new GitRepo($repository['root'].'/packages/shared/.tools/tool')->init('master'); + + ExternalSources::flush(); + + expect(ExternalSources::unverifiable($repository['project'], ['--include-path', '../packages/shared']))->toBeEmpty(); +})->skipOnWindows(); + +it('reports a repository under an inner declared root even when an outer root counts it as noise', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['root'].'/.gitignore', "vendor/\n"); + mkdir($repository['root'].'/packages/shared/vendor/acme/pkg', 0755, true); + new GitRepo($repository['root'].'/packages/shared/vendor/acme/pkg')->init('master'); + + ExternalSources::flush(); + + $root = str_replace(DIRECTORY_SEPARATOR, '/', (string) realpath($repository['root'])); + + expect(ExternalSources::unverifiable($repository['project'], ['--include-path', '../packages/shared'.PATH_SEPARATOR.'../packages/shared/vendor'])) + ->toBe([$root.'/packages/shared/vendor/acme/pkg']); +})->skipOnWindows(); + +it('reports a root inside an ignored repository as unverifiable', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['root'].'/.gitignore', "packages/shared/checkout/\n"); + mkdir($repository['root'].'/packages/shared/checkout/src', 0755, true); + file_put_contents($repository['root'].'/packages/shared/checkout/src/Shared.php', "init('master'); + + ExternalSources::flush(); + + $root = str_replace(DIRECTORY_SEPARATOR, '/', (string) realpath($repository['root'])); + + expect(ExternalSources::unverifiable($repository['project'], ['--include-path', '../packages/shared/checkout/src']))->toBe([$root.'/packages/shared/checkout/src']); +})->skipOnWindows(); + +it('reads a bootstrap whose name holds a wildcard character as a literal file', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + +XML_WRAP); + + file_put_contents($repository['root'].'/.gitignore', "packages/shared/.bootstrap?.php\n"); + file_put_contents($repository['root'].'/packages/shared/.bootstrap?.php', "toBe(['packages/shared/.bootstrap?.php']); +})->skipOnWindows(); + +it('reads a psr-4 directory whose name holds a wildcard character as a literal directory', function (): void { + $repository = tiaExternalRepository([ + 'autoload' => ['psr-4' => ['Shared\\' => '../packages/shared/.lib?/']], + ]); + + mkdir($repository['root'].'/packages/shared/.lib?', 0755, true); + file_put_contents($repository['root'].'/.gitignore', "packages/shared/.lib?/Generated.php\n"); + file_put_contents($repository['root'].'/packages/shared/.lib?/Generated.php', "toBe(['packages/shared/.lib?/']) + ->and(ExternalSources::ignoredInputs($repository['project']))->toBe(['packages/shared/.lib?/Generated.php']); +})->skipOnWindows(); + +it('reads an include path whose name holds a wildcard character as a literal directory', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + ../packages/shared/lib? + + +XML_WRAP); + + mkdir($repository['root'].'/packages/shared/lib?', 0755, true); + file_put_contents($repository['root'].'/packages/shared/lib?/Helper.php', "toBe(['packages/shared/lib?/']); +})->skipOnWindows(); + +it('reads every path of an include path list', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + ../packages/shared/lib?:../packages/fallback + + +XML_WRAP); + + mkdir($repository['root'].'/packages/shared/lib?', 0755, true); + mkdir($repository['root'].'/packages/fallback', 0755, true); + + expect(tiaRootsFrom($repository['project'], $repository['project'], []))->toBe(['packages/fallback/', 'packages/shared/lib?/']); +})->skipOnWindows(); + +it('watches the configuration directory when an include path list starts with a separator', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['root'].'/config', 0755, true); + file_put_contents($repository['root'].'/config/phpunit.xml', <<<'XML_WRAP' + + + + :../packages/fallback + + +XML_WRAP); + mkdir($repository['root'].'/packages/fallback', 0755, true); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['--configuration', '../config/phpunit.xml']))->toContain('config/'); +})->skipOnWindows(); + +it('watches nothing for an empty include path, as PHPUnit adds nothing', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['root'].'/config', 0755, true); + file_put_contents($repository['root'].'/config/phpunit.xml', <<<'XML_WRAP' + + + + + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['--configuration', '../config/phpunit.xml']))->toBe(['config/phpunit.xml']); +})->skipOnWindows(); + +it('resolves every path of an include path list after the first one from the working directory', function (): void { + $repository = tiaExternalRepository(); + + mkdir($repository['project'].'/config', 0755, true); + file_put_contents($repository['project'].'/config/phpunit.xml', <<<'XML_WRAP' + + + + ../../packages/shared:../packages/fallback + + +XML_WRAP); + mkdir($repository['root'].'/packages/fallback', 0755, true); + + expect(tiaRootsFrom($repository['project'], $repository['project'], ['--configuration', 'config/phpunit.xml']))->toBe(['packages/fallback/', 'packages/shared/']); +})->skipOnWindows(); + +it('watches the directory before a bracket and a brace path as it is', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + ../packages/[st]hared/src + ../libraries/{a,b} + + + +XML_WRAP); + + mkdir($repository['root'].'/libraries', 0755, true); + + expect(tiaRootsFrom($repository['project'], $repository['project'], []))->toBe(['libraries/{a,b}/', 'packages/', 'packages/shared/src/']); +})->skipOnWindows(); + +it('watches the directory an escaped brace names', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + ../packages/\{local}/src + + + +XML_WRAP); + + mkdir($repository['root'].'/packages/{local}/src', 0755, true); + + expect(tiaRootsFrom($repository['project'], $repository['project'], []))->toBe(['packages/', 'packages/{local}/src/']); +})->skipOnWindows(); + +it('watches every directory a double star pattern reaches like PHPUnit', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + ../packages/**/.generated/src + + + +XML_WRAP); + + mkdir($repository['root'].'/packages/one/.generated/src', 0755, true); + mkdir($repository['root'].'/packages/team/lib/.generated/src', 0755, true); + file_put_contents($repository['root'].'/.gitignore', ".generated/\n"); + file_put_contents($repository['root'].'/packages/one/.generated/src/One.php', "toBe([ + 'packages/one/.generated/src/One.php', + 'packages/team/lib/.generated/src/Helper.php', + ]); +})->skipOnWindows(); + +it('also watches a directory whose real name looks like a pattern', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + ../packages/.generated{local}/src + + + +XML_WRAP); + + mkdir($repository['root'].'/packages/.generated{local}/src', 0755, true); + file_put_contents($repository['root'].'/.gitignore', "packages/.generated{local}/src/Helper.php\n"); + file_put_contents($repository['root'].'/packages/.generated{local}/src/Helper.php', "toBe(['packages/.generated{local}/src/']); + + ExternalSources::flush(); + + expect(ExternalSources::ignoredInputs($repository['project']))->toBe(['packages/.generated{local}/src/Helper.php']); +})->skipOnWindows(); + +it('keeps an existing absolute directory with brackets in its path as it is', function (): void { + $repository = tiaExternalRepository(); + + $shared = str_replace(DIRECTORY_SEPARATOR, '/', (string) realpath($repository['root'])).'/mono[dev]/shared'; + mkdir($shared, 0755, true); + file_put_contents($repository['project'].'/phpunit.xml', << + + + + {$shared} + + + +XML_WRAP); + + expect(tiaRootsFrom($repository['project'], $repository['project'], []))->toBe(['mono[dev]/shared/']) + ->and(ExternalSources::unverifiable($repository['project']))->toBeEmpty(); +})->skipOnWindows(); + +it('watches the directories a bracket pattern matches even when its literal name also exists', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + + + + ../packages/[st]hared/src + + + +XML_WRAP); + + mkdir($repository['root'].'/packages/[st]hared/src', 0755, true); + + expect(tiaRootsFrom($repository['project'], $repository['project'], []))->toBe(['packages/', 'packages/shared/src/']); +})->skipOnWindows(); + +it('cuts a path at a brace only when the glob of its reader expands braces', function (): void { + $beforeWildcard = new ReflectionMethod(ExternalSources::class, 'beforeWildcard'); + + expect($beforeWildcard->invoke(null, '../repo{dev,ci}/shared/Helper.php', 0))->toBe('../repo{dev,ci}/shared/Helper.php') + ->and($beforeWildcard->invoke(null, '../repo{dev,ci}/shared/Helper.php', GLOB_BRACE))->toBe('..') + ->and($beforeWildcard->invoke(null, '../packages/[st]hared/src', 0))->toBe('../packages'); +})->skip(! defined('GLOB_BRACE'), 'This platform has no brace expansion.'); + +it('lists no ignored file of the project itself as an ignored input', function (): void { + $repository = tiaExternalRepository(); + + file_put_contents($repository['root'].'/.gitignore', "backend/cache.php\n"); + file_put_contents($repository['root'].'/backend/cache.php', "toBeEmpty(); +})->skipOnWindows(); + +it('keeps the roots of the run when a test changes the working directory', function (): void { + $repository = tiaExternalRepository([], <<<'XML_WRAP' + + +XML_WRAP); + + $atStart = ExternalSources::rootsFor($repository['project']); + + chdir($repository['project'].'/app'); + + expect($atStart)->toBe(['packages/shared/bootstrap.php']) + ->and(ExternalSources::rootsFor($repository['project']))->toBe($atStart); +})->skipOnWindows(); + +it('keeps the drive letter when it resolves a missing directory against a Windows base', function (): void { + $lexicalPath = new ReflectionMethod(ExternalSources::class, 'lexicalPath'); + + expect($lexicalPath->invoke(null, 'C:/mono/backend', '../shared/src'))->toBe('C:/mono/shared/src'); +})->skip(PHP_OS_FAMILY !== 'Windows', 'Drive letters exist only on Windows.'); + +it('resolves a path that starts with a drive letter against its base outside Windows', function (): void { + $isAbsolute = new ReflectionMethod(ExternalSources::class, 'isAbsolute'); + $lexicalPath = new ReflectionMethod(ExternalSources::class, 'lexicalPath'); + + expect($isAbsolute->invoke(null, 'C:/fixture/bootstrap.php'))->toBeFalse() + ->and($lexicalPath->invoke(null, '/repo/backend/config', 'C:/fixture/bootstrap.php'))->toBe('/repo/backend/config/C:/fixture/bootstrap.php'); +})->skipOnWindows(); + +it('treats a path from the root of the current drive as absolute on Windows', function (): void { + $isAbsolute = new ReflectionMethod(ExternalSources::class, 'isAbsolute'); + + expect($isAbsolute->invoke(null, '\\mono\\shared\\src'))->toBeTrue(); +})->skip(PHP_OS_FAMILY !== 'Windows', 'Paths from the root of the current drive exist only on Windows.'); + +it('keeps the current drive when it resolves a missing path from the root of that drive', function (): void { + $lexicalPath = new ReflectionMethod(ExternalSources::class, 'lexicalPath'); + $drive = substr((string) getcwd(), 0, 2); + + expect($lexicalPath->invoke(null, $drive.'/mono/backend', '\\mono\\shared\\src'))->toBe($drive.'/mono/shared/src'); +})->skip(PHP_OS_FAMILY !== 'Windows', 'Paths from the root of the current drive exist only on Windows.'); + +it('keeps the network share when it resolves a missing directory against a UNC base', function (): void { + $lexicalPath = new ReflectionMethod(ExternalSources::class, 'lexicalPath'); + + expect($lexicalPath->invoke(null, '//server/share/mono/backend', '../shared/src'))->toBe('//server/share/mono/shared/src'); +})->skip(PHP_OS_FAMILY !== 'Windows', 'UNC paths exist only on Windows.'); + +it('reads a leading double slash as the root outside Windows', function (): void { + $lexicalPath = new ReflectionMethod(ExternalSources::class, 'lexicalPath'); + + expect($lexicalPath->invoke(null, '/usr/local/backend', '//usr/local/missing/src'))->toBe('/usr/local/missing/src'); +})->skipOnWindows(); diff --git a/tests/Unit/Plugins/Tia/Fingerprint.php b/tests/Unit/Plugins/Tia/Fingerprint.php index 4a66b9d3..ab05ad86 100644 --- a/tests/Unit/Plugins/Tia/Fingerprint.php +++ b/tests/Unit/Plugins/Tia/Fingerprint.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Pest\Plugins\Tia\ConfigurationFile; +use Pest\Plugins\Tia\ExternalSources; use Pest\Plugins\Tia\Fingerprint; use Symfony\Component\Process\Process; @@ -107,6 +108,7 @@ describe('compute()', function (): void { fingerprintRemoveDirectory($clone); } }); + it('keeps the command line bootstrap and include path out of a run that sets neither', function (): void { $root = fingerprintRepository(); @@ -133,4 +135,59 @@ describe('compute()', function (): void { fingerprintRemoveDirectory($root); } }); + + it('tells a relative include path from the absolute path it names', function (): void { + $root = (string) realpath(fingerprintRepository()); + $previous = getcwd(); + chdir($root); + + try { + $relativeFirst = Fingerprint::compute($root, null, ['--include-path', '.'.PATH_SEPARATOR.$root]); + $absoluteFirst = Fingerprint::compute($root, null, ['--include-path', $root.PATH_SEPARATOR.'.']); + + expect(Fingerprint::structuralMatches($relativeFirst, $absoluteFirst))->toBeFalse(); + } finally { + chdir((string) $previous); + fingerprintRemoveDirectory($root); + } + }); + + it('stores an include path whose name is not utf-8 as text json can encode', function (): void { + $root = (string) realpath(fingerprintRepository()); + mkdir($root.'/app'); + file_put_contents($root.'/app/composer.json', '{}'); + fingerprintGit($root, 'add', '-A'); + fingerprintGit($root, 'commit', '-q', '-m', 'init'); + $previous = getcwd(); + chdir($root.'/app'); + ExternalSources::flush(); + + try { + $fingerprint = Fingerprint::compute($root.'/app', null, ['--include-path', "../optional-\xff"]); + + expect($fingerprint['structural'])->toHaveKeys(['external_roots', 'include_path']) + ->and(json_encode($fingerprint))->toBeString(); + } finally { + chdir((string) $previous); + ExternalSources::flush(); + fingerprintRemoveDirectory($root); + } + }); + + it('changes when the order of the include path changes and not when its spelling does', function (): void { + $root = (string) realpath(fingerprintRepository()); + mkdir($root.'/a'); + mkdir($root.'/b'); + + try { + $forward = Fingerprint::compute($root, null, ['--include-path', $root.'/a'.PATH_SEPARATOR.$root.'/b']); + $respelled = Fingerprint::compute($root, null, ['--include-path', $root.'/./a/'.PATH_SEPARATOR.$root.'/b']); + $reversed = Fingerprint::compute($root, null, ['--include-path', $root.'/b'.PATH_SEPARATOR.$root.'/a']); + + expect(Fingerprint::structuralMatches($forward, $respelled))->toBeTrue() + ->and(Fingerprint::structuralMatches($forward, $reversed))->toBeFalse(); + } finally { + fingerprintRemoveDirectory($root); + } + }); }); diff --git a/tests/Unit/Support/ComposerProject.php b/tests/Unit/Support/ComposerProject.php new file mode 100644 index 00000000..53edec73 --- /dev/null +++ b/tests/Unit/Support/ComposerProject.php @@ -0,0 +1,30 @@ + ['install_path' => ".var_export($root.'/app', true)."]];\n"); + + try { + expect(ComposerProject::rootPath($root.'/app/lib/deps/autoload.php'))->toBe(realpath($root.'/app')); + } finally { + new Process(['rm', '-rf', $root])->run(); + } +})->skipOnWindows(); + +it('falls back to the parent of the vendor directory when composer recorded no install path', function (): void { + $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-composer-project-'.bin2hex(random_bytes(8)); + mkdir($root.'/vendor/composer', 0755, true); + file_put_contents($root.'/vendor/composer/installed.php', " ['name' => '__root__'], 'versions' => []];\n"); + + try { + expect(ComposerProject::rootPath($root.'/vendor/autoload.php'))->toBe(realpath($root)); + } finally { + new Process(['rm', '-rf', $root])->run(); + } +})->skipOnWindows(); diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index 36361423..555ef25b 100644 --- a/tests/Visual/Parallel.php +++ b/tests/Visual/Parallel.php @@ -21,7 +21,7 @@ test('parallel', function () use ($run): void { $output = implode("\n", array_slice(explode("\n", (string) $output), -10)); $profileOutput = $run('tests/Fixtures/Suites/SuccessOnly.php', '--profile'); - $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 31 skipped, 1888 passed (3998 assertions)'; + $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 36 skipped, 1976 passed (4114 assertions)'; expect($output) ->toContain("Tests: {$expected}")