From a2d3e6baddd4c4ea5c5b3a4e3746e506b1efe29d Mon Sep 17 00:00:00 2001 From: Jhon Farias Date: Sun, 22 Nov 2026 16:11:58 +0100 Subject: [PATCH] fix(tia): support a Pest project nested in a git repository (#1914) * fix(tia): support a Pest project nested in a git repository Tia refused to run whenever the Pest project was not the git repository root, because git prints and addresses paths relative to the repository root while the dependency graph is keyed on project-relative paths. Translate at every git boundary instead of guarding against the mismatch. `Git::pathPrefix()` resolves the directory of the project inside the repository, and `ChangedFiles` strips that prefix off the paths git prints, drops the paths of sibling packages, and prepends it to `git show`. Both diffs read `-z` records, because `core.quotePath` C-quotes a path outside ASCII, and `--no-relative` holds the frame when a user sets `diff.relative`. Three places read `/.git` directly, which is absent in a nested project and in a worktree, and now ask git: `BaseRemote`, `Storage` and `Fingerprint::isTrackedByGit()`. `Storage` folds the prefix into the state key so two projects in one repository do not share a graph, and the fingerprint carries the prefix so a baseline published by a sibling project is rejected. A project at the repository root keeps the key and the fingerprint it had. `git check-ignore` runs without `--no-index`, so a tracked file that an ignore rule matches counts as part of the project on both sides of the boundary. Changes outside the project are dropped and reported by count in the run summary, so a nested project does not look idle when the repository around it moved. Co-Authored-By: Claude Opus 5 * fix(tia): keep whitespace at the edge of the paths git returns * fix(tia): run the full suite when a PHP file outside a nested project changes --------- Co-authored-by: Claude Opus 5 Co-authored-by: Punyapal Shah --- src/Exceptions/TiaRequiresRepositoryRoot.php | 44 --- src/Plugins/Tia.php | 165 +++++++-- src/Plugins/Tia/Baselines/BaseRemote.php | 19 +- src/Plugins/Tia/ChangedFiles.php | 133 ++++++- src/Plugins/Tia/Fingerprint.php | 41 ++- src/Plugins/Tia/Storage.php | 34 +- src/Support/Git.php | 38 +- tests/.snapshots/success.txt | 22 +- tests/Features/Tia/BranchShapes.php | 12 - tests/Features/Tia/Monorepo.php | 356 +++++++++++++++++++ tests/Fixtures/Tia/Project.php | 10 +- tests/Unit/Plugins/Tia/ChangedFiles.php | 287 +++++++++++++++ tests/Unit/Plugins/Tia/Storage.php | 31 ++ tests/Visual/Parallel.php | 2 +- 14 files changed, 1052 insertions(+), 142 deletions(-) delete mode 100644 src/Exceptions/TiaRequiresRepositoryRoot.php create mode 100644 tests/Features/Tia/Monorepo.php create mode 100644 tests/Unit/Plugins/Tia/ChangedFiles.php diff --git a/src/Exceptions/TiaRequiresRepositoryRoot.php b/src/Exceptions/TiaRequiresRepositoryRoot.php deleted file mode 100644 index 8ded003f..00000000 --- a/src/Exceptions/TiaRequiresRepositoryRoot.php +++ /dev/null @@ -1,44 +0,0 @@ -subdirectoryPrefix, - )); - } - - public function render(OutputInterface $output): void - { - $output->writeln([ - '', - ' ERROR Tia mode requires the git repository root.', - '', - sprintf(' This project sits in a subdirectory of a larger repo %s.', $this->subdirectoryPrefix), - '', - ' Give the project its own git repository to use Tia.', - '', - ]); - } - - public function exitCode(): int - { - return 1; - } -} diff --git a/src/Plugins/Tia.php b/src/Plugins/Tia.php index 3c6abd84..8e343b5f 100644 --- a/src/Plugins/Tia.php +++ b/src/Plugins/Tia.php @@ -17,7 +17,6 @@ use Pest\Exceptions\TiaGitFailed; use Pest\Exceptions\TiaRequiresCommit; use Pest\Exceptions\TiaRequiresDefaultBranch; use Pest\Exceptions\TiaRequiresRemote; -use Pest\Exceptions\TiaRequiresRepositoryRoot; use Pest\Panic; use Pest\Plugins\Concerns\HandleArguments; use Pest\Plugins\Tia\BaselineSync; @@ -382,8 +381,6 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument } /** - * Mirrors {@see HandleArguments::hasArgument()} for - * * @param array $arguments */ private static function argumentPresent(string $argument, array $arguments): bool @@ -465,17 +462,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return $this->cachedAssertionsByTestId[$testId] ?? 0; } - /** - * {@inheritDoc} - */ public function handleOriginalArguments(array $arguments): void { $this->originalArguments = $arguments; } - /** - * {@inheritDoc} - */ public function handleArguments(array $arguments): array { if ($this->hasArgument(self::BASELINE_PATH_OPTION, $arguments)) { @@ -865,12 +856,6 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument { $this->watchPatterns->useDefaults($projectRoot); - $subdirectoryPrefix = $this->gitSubdirectoryPrefix($projectRoot); - - if ($subdirectoryPrefix !== null) { - Panic::with(new TiaRequiresRepositoryRoot($subdirectoryPrefix)); - } - try { $this->resolveBranch($projectRoot); } catch (MissingDependency|TiaGitFailed $missingGit) { @@ -927,6 +912,14 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument } } + $uncommittedPhpChanges = $this->uncommittedPhpChangesOutsideProject($projectRoot); + + if ($uncommittedPhpChanges !== []) { + $this->recordNothingForUncommittedPhpChangesOutsideProject($uncommittedPhpChanges); + + return $arguments; + } + $coverageCacheOwned = $this->piggybackCoverage && $this->pestCoverageActive(); if ($coverageCacheOwned) { @@ -1106,6 +1099,14 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument Panic::with(new TiaBaselineCommitMissing((string) $branchSha)); } + $outsideProject = $changedFiles->outsideProject(); + + $phpChangesOutsideProject = $this->phpFiles($outsideProject); + + if ($phpChangesOutsideProject !== []) { + return $this->runFullSuiteForPhpChangesOutsideProject($phpChangesOutsideProject, $arguments); + } + $changed = $changedFiles->filterUnchangedSinceLastRun( $changed, $graph->lastRunTree($this->branch), @@ -1143,7 +1144,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument ...$rerunFromCache, ])); - $this->reportAffectedSummary($changed, $affectedFromChanges, $rerunFromCache, $affected); + $this->reportAffectedSummary($changed, $affectedFromChanges, $rerunFromCache, $affected, $outsideProject); $affectedSet = array_fill_keys($affected, true); $canRefreshReplayEdges = $affected !== [] && $coverageAvailable; @@ -1208,13 +1209,15 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument * @param array $affectedFromChanges * @param array $rerunFromCache * @param array $affected + * @param array $outsideProject */ - private function reportAffectedSummary(array $changedFiles, array $affectedFromChanges, array $rerunFromCache, array $affected): void + private function reportAffectedSummary(array $changedFiles, array $affectedFromChanges, array $rerunFromCache, array $affected, array $outsideProject = []): void { $this->output->writeln(''); if ($affected === []) { $this->renderChild('Experimental TIA mode enabled.'); + $this->reportChangesOutsideProject($outsideProject); return; } @@ -1277,6 +1280,124 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument if ($remainder > 0) { $this->output->writeln(sprintf(' … +%d more', $remainder)); } + + $this->reportChangesOutsideProject($outsideProject); + } + + /** + * @return array + */ + private function uncommittedPhpChangesOutsideProject(string $projectRoot): array + { + $changedFiles = new ChangedFiles($projectRoot); + + if ($changedFiles->gitPrefix() === '') { + return []; + } + + try { + $changedFiles->since(null); + } catch (MissingDependency|TiaGitFailed) { + return []; + } + + return $this->phpFiles($changedFiles->outsideProjectDirty()); + } + + /** + * @param array $uncommittedPhpChanges + */ + private function recordNothingForUncommittedPhpChangesOutsideProject(array $uncommittedPhpChanges): void + { + $this->writesSuppressed = true; + + $this->renderPhpChangesOutsideProject($uncommittedPhpChanges); + $this->renderChild('Running the full suite, and recording nothing — the project may load that code, and git stops reporting an uncommitted edit once it is undone.'); + $this->renderChild('Commit what you changed there to let a run leave a baseline behind.'); + } + + /** + * @param array $phpChanges + * @param array $arguments + * @return array + */ + private function runFullSuiteForPhpChangesOutsideProject(array $phpChanges, array $arguments): array + { + $this->renderPhpChangesOutsideProject($phpChanges); + + if ($this->canRebuildGraph()) { + $this->deleteState(self::KEY_GRAPH); + $this->deleteState(self::KEY_COVERAGE_CACHE); + + $this->freshGraphReason = 'a PHP file outside the project changed'; + + return $this->enterRecordMode($arguments); + } + + $this->requestWorkerResults(); + + if ($this->piggybackCoverage) { + $this->renderChild('Running the full suite — the project may load that code, and a coverage run cannot refresh the dependency graph.'); + $this->renderChild('Run --tia without --coverage to record a fresh dependency graph.'); + + return $arguments; + } + + $this->fullSuiteFallbackRan = true; + + $this->renderChild('Running the full suite — the project may load that code, and the dependency graph only reaches files under the project root.'); + $this->renderChild('Install / enable pcov or xdebug (mode: coverage) so edges can be safely refreshed after changes outside the project root.'); + + return $arguments; + } + + /** + * @param array $files + * @return array + */ + private function phpFiles(array $files): array + { + return array_values(array_filter( + $files, + static fn (string $file): bool => str_ends_with($file, '.php'), + )); + } + + /** + * @param array $phpChanges + */ + private function renderPhpChangesOutsideProject(array $phpChanges): void + { + $count = count($phpChanges); + + $this->renderBadge('WARN', sprintf( + 'Detected %d changed PHP file%s outside this project.', + $count, + $count === 1 ? '' : 's', + )); + + foreach (array_slice($phpChanges, 0, $this->output->isVerbose() ? $count : 5) as $file) { + $this->output->writeln(sprintf(' %s', $file)); + } + } + + /** + * @param array $outsideProject Repository-relative paths. + */ + private function reportChangesOutsideProject(array $outsideProject): void + { + if ($outsideProject === []) { + return; + } + + $count = count($outsideProject); + + $this->renderChild(sprintf( + '%d changed file%s outside this project %s ignored — TIA only tracks files under the project root.', + $count, + $count === 1 ? '' : 's', + $count === 1 ? 'was' : 'were', + )); } /** @@ -2246,6 +2367,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument 'js_config' => 'JS/TS config', 'pest_factory' => 'Pest internals', 'pest_method_factory' => 'Pest internals', + 'project_prefix' => 'project location in the repository', ]; $seen = []; @@ -2260,11 +2382,6 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return implode(', ', array_keys($seen)); } - private function gitSubdirectoryPrefix(string $projectRoot): ?string - { - return new Git($projectRoot)->subdirectoryPrefix(); - } - private function composerLockDelta(string $projectRoot, string $sha): string { $current = @file_get_contents($projectRoot.'/composer.lock'); @@ -2272,7 +2389,9 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return ''; } - $baseline = new Git($projectRoot)->show($sha, 'composer.lock'); + $git = new Git($projectRoot); + + $baseline = $git->show($sha, $git->pathPrefix().'composer.lock'); if ($baseline === null) { return ''; diff --git a/src/Plugins/Tia/Baselines/BaseRemote.php b/src/Plugins/Tia/Baselines/BaseRemote.php index 107adf90..5e90b13d 100644 --- a/src/Plugins/Tia/Baselines/BaseRemote.php +++ b/src/Plugins/Tia/Baselines/BaseRemote.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Pest\Plugins\Tia\Baselines; use Pest\Plugins\Tia\WatchPatterns; +use Pest\Support\Git; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; @@ -73,23 +74,7 @@ abstract readonly class BaseRemote // @pest-arch-ignore-line protected function readOriginUrl(string $projectRoot): ?string // @pest-arch-ignore-line { - $gitConfig = $projectRoot.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config'; - - if (! is_file($gitConfig)) { - return null; - } - - $content = @file_get_contents($gitConfig); - - if ($content === false) { - return null; - } - - if (preg_match('/\[remote "origin"\][^\[]*?url\s*=\s*(\S+)/s', $content, $match) !== 1) { - return null; - } - - return $match[1]; + return new Git($projectRoot)->originUrl(); } /** diff --git a/src/Plugins/Tia/ChangedFiles.php b/src/Plugins/Tia/ChangedFiles.php index 16d833c5..30cc4e2e 100644 --- a/src/Plugins/Tia/ChangedFiles.php +++ b/src/Plugins/Tia/ChangedFiles.php @@ -12,15 +12,83 @@ use Symfony\Component\Process\ExecutableFinder; /** * @internal */ -final readonly class ChangedFiles +final class ChangedFiles { - private Git $git; + private readonly Git $git; - public function __construct(private string $projectRoot) + private ?string $gitPrefix = null; + + /** + * @var array + */ + private array $outsideProject = []; + + /** + * @var array + */ + private array $outsideProjectDirty = []; + + public function __construct(private readonly string $projectRoot) { $this->git = new Git($projectRoot); } + public function gitPrefix(): string + { + return $this->gitPrefix ??= $this->git->pathPrefix(); + } + + /** + * @param array $files repository-relative paths, as printed by git. + * @return array project-relative paths; paths outside the project are dropped. + */ + private function toProjectRelative(array $files, bool $fromWorkingTree = false): array + { + $prefix = $this->gitPrefix(); + + if ($prefix === '') { + return $files; + } + + $projectFiles = []; + + foreach ($files as $file) { + if (str_starts_with($file, $prefix)) { + $projectFiles[] = substr($file, strlen($prefix)); + + continue; + } + + if ($file === '') { + continue; + } + + $this->outsideProject[$file] = true; + + if ($fromWorkingTree) { + $this->outsideProjectDirty[$file] = true; + } + } + + return $projectFiles; + } + + /** + * @return array + */ + public function outsideProject(): array + { + return array_map(strval(...), array_keys($this->outsideProject)); + } + + /** + * @return array + */ + public function outsideProjectDirty(): array + { + return array_map(strval(...), array_keys($this->outsideProjectDirty)); + } + /** * @param array $files project-relative paths. * @param array $lastRunTree path → content hash from last run. @@ -97,6 +165,9 @@ final readonly class ChangedFiles */ public function since(?string $sha): ?array { + $this->outsideProject = []; + $this->outsideProjectDirty = []; + $files = []; if ($sha !== null && $sha !== '') { @@ -120,6 +191,8 @@ final readonly class ChangedFiles $candidates = array_keys($this->filterIgnored($unique)); + $this->filterIgnoredOutsideProject(); + if ($sha !== null && $sha !== '') { return $this->filterBehaviourallyUnchanged($candidates, $sha); } @@ -162,7 +235,25 @@ final readonly class ChangedFiles private function contentAtSha(string $sha, string $path): ?string { - return $this->git->show($sha, $path); + return $this->git->show($sha, $this->gitPrefix().$path); + } + + private function filterIgnoredOutsideProject(): void + { + if ($this->outsideProject === []) { + return; + } + + $repositoryRoot = $this->git->repositoryRoot(); + + if ($repositoryRoot === null) { + return; + } + + $git = new Git($repositoryRoot); + + $this->outsideProject = $this->filterIgnoredWith($git, $this->outsideProject); + $this->outsideProjectDirty = array_intersect_key($this->outsideProjectDirty, $this->outsideProject); } /** @@ -170,13 +261,22 @@ final readonly class ChangedFiles * @return array */ private function filterIgnored(array $candidates): array + { + return $this->filterIgnoredWith($this->git, $candidates); + } + + /** + * @param array $candidates + * @return array + */ + private function filterIgnoredWith(Git $git, array $candidates): array { if ($candidates === []) { return $candidates; } - $result = $this->git->result( - ['check-ignore', '--no-index', '-z', '--stdin'], + $result = $git->result( + ['check-ignore', '-z', '--stdin'], implode("\x00", array_keys($candidates)), ); @@ -323,13 +423,13 @@ final readonly class ChangedFiles */ private function diffSinceSha(string $sha): array { - $result = $this->scan()->result(['diff', '--name-only', '--no-renames', $sha.'..HEAD']); + $result = $this->scan()->result(['diff', '--name-only', '--no-renames', '--no-relative', '-z', $sha.'..HEAD']); if ($result['exitCode'] !== 0) { throw $this->gitFailure($result); } - return $this->splitLines($result['output']); + return $this->toProjectRelative($this->splitRecords($result['output'])); } /** @@ -377,7 +477,7 @@ final readonly class ChangedFiles $files[] = $path; } - return $files; + return $this->toProjectRelative($files, fromWorkingTree: true); } public function currentSha(): ?string @@ -407,6 +507,21 @@ final readonly class ChangedFiles return new TiaGitFailed($error !== '' ? $error : sprintf('Git exited with code %d.', $result['exitCode'])); } + /** + * @return array + */ + private function splitRecords(string $output): array + { + if ($output === '') { + return []; + } + + return array_values(array_filter( + explode("\x00", rtrim($output, "\x00")), + static fn (string $record): bool => $record !== '', + )); + } + /** * @return array */ diff --git a/src/Plugins/Tia/Fingerprint.php b/src/Plugins/Tia/Fingerprint.php index a8b87af4..89dc43da 100644 --- a/src/Plugins/Tia/Fingerprint.php +++ b/src/Plugins/Tia/Fingerprint.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Pest\Plugins\Tia; use Pest\Plugins\Tia\Contracts\Lockfile; +use Pest\Support\Git; use Symfony\Component\Process\Exception\ExceptionInterface as ProcessException; use Symfony\Component\Process\Process; @@ -30,15 +31,23 @@ final readonly class Fingerprint */ public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null): array { + $structural = [ + 'schema' => self::SCHEMA_VERSION, + 'composer_lock' => self::composerLockHash($projectRoot), + 'phpunit_configuration' => ($configuration ?? ConfigurationFile::projectDefault())->fingerprint($projectRoot), + 'vite_config' => self::viteConfigHash($projectRoot), + 'package_lock' => self::packageLockHash($projectRoot), + 'js_config' => self::jsConfigHash($projectRoot), + ]; + + $prefix = self::projectPrefix($projectRoot); + + if ($prefix !== '') { + $structural['project_prefix'] = $prefix; + } + return [ - 'structural' => [ - 'schema' => self::SCHEMA_VERSION, - 'composer_lock' => self::composerLockHash($projectRoot), - 'phpunit_configuration' => ($configuration ?? ConfigurationFile::projectDefault())->fingerprint($projectRoot), - 'vite_config' => self::viteConfigHash($projectRoot), - 'package_lock' => self::packageLockHash($projectRoot), - 'js_config' => self::jsConfigHash($projectRoot), - ], + 'structural' => $structural, 'environmental' => [ 'php_minor' => PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION, @@ -275,7 +284,7 @@ final readonly class Fingerprint return $cache[$key]; } - if (! is_dir($projectRoot.'/.git') && ! is_file($projectRoot.'/.git')) { + if (! self::isGitRepository($projectRoot)) { return $cache[$key] = true; } @@ -291,6 +300,20 @@ final readonly class Fingerprint return $cache[$key] = $process->getExitCode() !== 0; } + private static function projectPrefix(string $projectRoot): string + { + static $cache = []; + + return $cache[$projectRoot] ??= new Git($projectRoot)->pathPrefix(); + } + + private static function isGitRepository(string $projectRoot): bool + { + static $cache = []; + + return $cache[$projectRoot] ??= new Git($projectRoot)->isRepository(); + } + private static function contentHashOrNull(string $path): ?string { if (! is_file($path)) { diff --git a/src/Plugins/Tia/Storage.php b/src/Plugins/Tia/Storage.php index e0674314..7bdc635c 100644 --- a/src/Plugins/Tia/Storage.php +++ b/src/Plugins/Tia/Storage.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace Pest\Plugins\Tia; +use Pest\Support\Git; + /** * @internal */ @@ -92,9 +94,6 @@ final class Storage return null; } - /** - * `git@github.com:foo/bar.git`, `ssh://git@github.com/foo/bar` - */ private static function projectKey(string $projectRoot): string { $origin = self::originIdentity($projectRoot); @@ -102,6 +101,12 @@ final class Storage $realpath = @realpath($projectRoot); $input = $origin ?? ($realpath === false ? $projectRoot : $realpath); + $prefix = $origin === null ? '' : self::gitPrefix($projectRoot); + + if ($prefix !== '') { + $input .= '/'.$prefix; + } + $hash = substr(hash('sha256', $input), 0, 16); $slug = self::slug(basename($projectRoot)); @@ -116,12 +121,10 @@ final class Storage return null; } - // git@host:org/repo(.git) if (preg_match('#^[\w.-]+@([\w.-]+):([\w./-]+?)(?:\.git)?/?$#', $url, $m) === 1) { return strtolower($m[1].'/'.$m[2]); } - // scheme://[user@]host[:port]/org/repo(.git) — https, ssh, git, file if (preg_match('#^[a-z]+://(?:[^@/]+@)?([^/:]+)(?::\d+)?/([\w./-]+?)(?:\.git)?/?$#i', $url, $m) === 1) { return strtolower($m[1].'/'.$m[2]); } @@ -131,23 +134,12 @@ final class Storage private static function rawOriginUrl(string $projectRoot): ?string { - $config = $projectRoot.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config'; + return new Git($projectRoot)->originUrl(); + } - if (! is_file($config)) { - return null; - } - - $raw = @file_get_contents($config); - - if ($raw === false) { - return null; - } - - if (preg_match('/\[remote "origin"\][^\[]*?url\s*=\s*(\S+)/s', $raw, $match) === 1) { - return trim($match[1]); - } - - return null; + private static function gitPrefix(string $projectRoot): string + { + return new Git($projectRoot)->pathPrefix(); } private static function slug(string $name): string diff --git a/src/Support/Git.php b/src/Support/Git.php index 36af5986..a139be1d 100644 --- a/src/Support/Git.php +++ b/src/Support/Git.php @@ -49,6 +49,22 @@ final readonly class Git return $output === '' ? null : $output; } + /** + * @param array $arguments + */ + private function outputLine(array $arguments): ?string + { + $output = $this->raw($arguments); + + if ($output === null) { + return null; + } + + $line = str_ends_with($output, "\n") ? substr($output, 0, -1) : $output; + + return $line === '' ? null : $line; + } + /** * @param array $arguments */ @@ -104,14 +120,28 @@ final readonly class Git return $this->raw(['show', $sha.':'.$path]); } - public function subdirectoryPrefix(): ?string + public function repositoryRoot(): ?string { - $prefix = $this->output(['rev-parse', '--show-prefix']); + $root = $this->outputLine(['rev-parse', '--show-toplevel']); + + return $root === null ? null : rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $root), '/'); + } + + public function pathPrefix(): string + { + $prefix = $this->outputLine(['rev-parse', '--show-prefix']); if ($prefix === null) { - return null; + return ''; } - return rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $prefix), '/'); + $prefix = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $prefix), '/'); + + return $prefix === '' ? '' : $prefix.'/'; + } + + public function originUrl(): ?string + { + return $this->output(['config', '--get', 'remote.origin.url']); } } diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index e2e8487d..05fab6ae 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -1963,6 +1963,25 @@ ✓ units → it collects every test class the given units bundle ✓ units → it writes bundled units, and reads back both shapes + PASS Tests\Unit\Plugins\Tia\ChangedFiles + ✓ it resolves the project prefix inside the repository + ✓ it keeps a space that begins the name of the project directory + ✓ it keeps the character that ends the name of the repository root with dataset "a space" + ✓ it keeps the character that ends the name of the repository root with dataset "a carriage return" + ✓ it reports working tree changes relative to the project, dropping siblings + ✓ it reports committed changes relative to the project, dropping siblings + ✓ it drops a file whose content came back to its baseline across the prefix boundary + ✓ it honours a gitignore inside the project + ✓ it leaves a project at the repository root untouched + ✓ it reports the changes it left outside the project + ✓ it reports nothing outside the project for a project at the repository root + ✓ it ties a fingerprint to the project location inside the repository + ✓ it sees a committed non-ascii path that git would otherwise quote + ✓ it sees a committed non-ascii path at the repository root too + ✓ 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 + PASS Tests\Unit\Plugins\Tia\ConfigurationFile ✓ it fingerprints the path and the content of the configuration file ✓ it tells an identical copy under another name apart from the original @@ -2140,6 +2159,7 @@ PASS Tests\Unit\Plugins\Tia\Storage ✓ it uses a project-relative configured directory ✓ it uses an absolute configured directory + ✓ it keeps the state directory of a project at the repository root PASS Tests\Unit\Plugins\Tia\TableExtractor ✓ fromSql() → it extracts tables from plain DML @@ -2627,4 +2647,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, 38 skipped, 1919 passed (4374 assertions) \ No newline at end of file + Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1937 passed (4405 assertions) \ No newline at end of file diff --git a/tests/Features/Tia/BranchShapes.php b/tests/Features/Tia/BranchShapes.php index 52c5aeb3..0c51a616 100644 --- a/tests/Features/Tia/BranchShapes.php +++ b/tests/Features/Tia/BranchShapes.php @@ -158,18 +158,6 @@ test('the default branch baseline survives every branch that comes and goes', fu ->and($project->graph()['baselines']['master']['results'])->toHaveCount(Project::TOTAL_TESTS); })->skipOnWindows(); -test('a project below the git repository root refuses to run and writes nothing', function (array $arguments): void { - $project = Project::make('master'); - $nested = $project->nested(); - - $result = $project->pestIn($nested, '--tia', ...$arguments); - - expect($result->exitCode)->toBe(1, $result->describe()) - ->and($result->output)->toContain('Tia mode requires the git repository root') - ->and($project->path('.home/.pest'))->not->toBeDirectory() - ->and($nested.DIRECTORY_SEPARATOR.'.pest')->not->toBeDirectory(); -})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); - test('a repository with no commits says so, and leaves plain runs alone', function (): void { $project = Project::withoutGit(); $project->git()->run(['init', '--quiet']); diff --git a/tests/Features/Tia/Monorepo.php b/tests/Features/Tia/Monorepo.php new file mode 100644 index 00000000..dbb4ef20 --- /dev/null +++ b/tests/Features/Tia/Monorepo.php @@ -0,0 +1,356 @@ +nested($directory); + + $project->write($directory.'/resources/views/greeting.blade.php', "

Hello

\n"); + $project->write('frontend/widget.php', "git()->commit('add the nested project and a sibling'); + + $project->seedFor($nested, 'master'); + + $project->mutateGraph(function (array $graph): array { + $id = count($graph['files']); + $graph['files'][$id] = 'resources/views/greeting.blade.php'; + $graph['edges']['tests/Unit/GreeterTest.php'][] = $id; + + return $graph; + }); + + return [$project, $nested]; +} + +/** + * @return array{0: Project, 1: string} + */ +function tiaMonorepoWithSharedDependency(): array +{ + [$project, $nested] = tiaMonorepo(); + + $project->write('shared/greeting.php', tiaSharedGreeting('Hello, %s!')); + $project->write('nested/tests/Pest.php', implode("\n", [ + 'write('nested/app/Greeter.php', implode("\n", [ + 'git()->commit('let the project load a shared PHP dependency'); + + $project->seedFor($nested, 'master'); + + return [$project, $nested]; +} + +function tiaSharedGreeting(string $format, string $wrapper = ''): string +{ + return implode("\n", [ + 'pestIn($nested, '--tia', ...$arguments); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe()) + ->and($result->affected())->toBe(0, $result->describe()); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); + +test('a working tree change inside the subdirectory selects the tests that depend on it', function (array $arguments): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('nested/resources/views/greeting.blade.php', "

Hi

\n"); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia', ...$arguments); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->affected())->toBe(2, $result->describe()) + ->and($result->replayed())->toBe(4, $result->describe()); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); + +test('a committed change inside the subdirectory selects the tests that depend on it', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('nested/resources/views/greeting.blade.php', "

Hi

\n"); + $project->git()->commit('reword the greeting'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->affected())->toBe(2, $result->describe()) + ->and($result->replayed())->toBe(4, $result->describe()); +})->skipOnWindows(); + +test('a project in a directory whose name begins with a space sees its own changes', function (): void { + [$project, $nested] = tiaMonorepo(' backend'); + + $project->write(' backend/resources/views/greeting.blade.php', "

Hi

\n"); + $project->git()->commit('reword the greeting'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->affected())->toBe(2, $result->describe()) + ->and($result->replayed())->toBe(4, $result->describe()); +})->skipOnWindows(); + +test('a change in a sibling package that holds no PHP leaves the subdirectory project untouched', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('frontend/app.js', "export const widget = 2;\n"); + $project->write('frontend/README.md', "# Frontend\n"); + $project->git()->commit('rework the sibling'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe()) + ->and($result->affected())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('a committed change in a shared PHP dependency outside the project runs the full suite', function (array $arguments): void { + [$project, $nested] = tiaMonorepoWithSharedDependency(); + + $project->write('shared/greeting.php', tiaSharedGreeting('Goodbye, %s!')); + $project->git()->commit('reword the shared greeting'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia', ...$arguments); + + expect($result->exitCode)->not->toBe(0, $result->describe()) + ->and($result->output)->toContain('Detected 1 changed PHP file outside this project.') + ->and($result->replayed())->toBe(0, $result->describe()) + ->and($result->tally())->toContain('2 failed') + ->and($result->tally())->toContain('4 passed'); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); + +test('a committed change in a shared PHP dependency outside the project runs the full suite once', function (array $arguments): void { + [$project, $nested] = tiaMonorepoWithSharedDependency(); + + $project->write('shared/greeting.php', tiaSharedGreeting('Hello, %s!', 'trim')); + $project->git()->commit('route the shared greeting through trim'); + + $first = $project->pestIn($nested, '--tia', ...$arguments); + $second = $project->pestIn($nested, '--tia', ...$arguments); + + expect($first->exitCode)->toBe(0, $first->describe()) + ->and($first->replayed())->toBe(0, $first->describe()) + ->and($first->tally())->toContain(Project::TOTAL_TESTS.' passed') + ->and($second->exitCode)->toBe(0, $second->describe()) + ->and($second->output)->not->toContain('changed PHP file outside this project') + ->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe()); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); + +test('a committed change in a shared PHP dependency outside the project records the edges of the project again', function (array $arguments): void { + [$project, $nested] = tiaMonorepoWithSharedDependency(); + + $project->write('shared/greeting.php', tiaSharedGreeting('Hello, %s!', 'trim')); + $project->write('nested/app/Greeter.php', <<<'PHP' + add(1, 1); + + return \shared_greeting($name); + } + } + PHP); + $project->git()->commit('let the greeter use the calculator'); + + $result = $project->pestIn($nested, '--tia', ...$arguments); + + $graph = $project->graph(); + $edges = array_map(fn (int $id): string => $graph['files'][$id], $graph['edges']['tests/Unit/GreeterTest.php']); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('Detected 1 changed PHP file outside this project.') + ->and($edges)->toContain('app/Calculator.php'); +})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); + +test('an uncommitted change in a shared PHP dependency outside the project runs the full suite and records nothing', function (): void { + [$project, $nested] = tiaMonorepoWithSharedDependency(); + + $recorded = $project->graph()['baselines']['master'] ?? null; + + $project->write('shared/greeting.php', tiaSharedGreeting('Goodbye, %s!')); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->not->toBe(0, $result->describe()) + ->and($result->output)->toContain('Detected 1 changed PHP file outside this project.') + ->and($result->output)->toContain('recording nothing') + ->and($result->replayed())->toBe(0, $result->describe()) + ->and($result->tally())->toContain('2 failed') + ->and($project->graph()['baselines']['master'] ?? null)->toBe($recorded); +})->skipOnWindows(); + +test('an uncommitted change in a shared PHP dependency outside the project leaves the coverage cache alone', function (): void { + [$project, $nested] = tiaMonorepoWithSharedDependency(); + + $recording = $project->pestIn($nested, '--tia', '--coverage'); + + $cache = $project->graphDir().DIRECTORY_SEPARATOR.'coverage.bin.gz'; + $recorded = file_get_contents($cache); + + $project->write('shared/greeting.php', implode("\n", [ + 'add(1, 1);', + '', + ' return sprintf(\'Hello, %s!\', $name);', + '}', + '', + ])); + + $result = $project->pestIn($nested, '--tia', '--coverage'); + + expect($recording->exitCode)->toBe(0, $recording->describe()) + ->and($recorded)->toBeString() + ->and($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('recording nothing') + ->and(file_get_contents($cache))->toBe($recorded); +})->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); + +test('an uncommitted change in a shared PHP dependency outside the project records no first graph', function (): void { + [$project, $nested] = tiaMonorepoWithSharedDependency(); + + unlink($project->graphDir().DIRECTORY_SEPARATOR.Tia::KEY_GRAPH); + + $project->write('shared/greeting.php', tiaSharedGreeting('Hello, %s!', 'trim')); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('recording nothing') + ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed') + ->and($project->graphExists())->toBeFalse($result->describe()); +})->skipOnWindows(); + +test('a committed change inside the subdirectory that is undone again selects nothing', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('nested/resources/views/greeting.blade.php', "

Hi

\n"); + $project->git()->commit('reword the greeting'); + + $project->write('nested/resources/views/greeting.blade.php', "

Hello

\n"); + $project->git()->commit('put the greeting back'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe()) + ->and($result->affected())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('two projects in the same repository keep their state apart', function (): void { + $project = Project::make('master'); + + $api = $project->nested('services/api'); + $admin = $project->nested('services/admin'); + + $project->git()->commit('add both projects'); + + expect($project->stateDirFor($api))->not->toBe($project->stateDirFor($admin)); +})->skipOnWindows(); + +test('a nested project fetches the baseline published for it', function (): void { + [$project, $nested] = tiaMonorepo(); + + $environment = $project->gh('ok', $project->detachGraph()); + + $result = $project->pestWithEnvironment($nested, $environment, '--tia', '--baselined'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('Downloading TIA baseline') + ->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe()); +})->skipOnWindows(); + +test('a nested project refuses a baseline published by a sibling project', function (): void { + [$project, $nested] = tiaMonorepo(); + + /** @var array $graph */ + $graph = json_decode($project->detachGraph(), true); + $graph['fingerprint']['structural']['project_prefix'] = 'services/admin/'; + + $environment = $project->gh('ok', (string) json_encode($graph, JSON_UNESCAPED_SLASHES)); + + $result = $project->pestWithEnvironment($nested, $environment, '--tia', '--baselined'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed') + ->and($result->replayed())->toBe(0, $result->describe()); +})->skipOnWindows(); + +test('it says when changes outside the project were ignored', function (): void { + [$project, $nested] = tiaMonorepo(); + + $project->write('frontend/app.js', "export const widget = 2;\n"); + $project->git()->commit('rework the sibling'); + $project->snapshot(); + + $result = $project->pestIn($nested, '--tia'); + + expect($result->exitCode)->toBe(0, $result->describe()) + ->and($result->output)->toContain('1 changed file outside this project was ignored'); +})->skipOnWindows(); diff --git a/tests/Fixtures/Tia/Project.php b/tests/Fixtures/Tia/Project.php index bb491098..ba65d6e6 100644 --- a/tests/Fixtures/Tia/Project.php +++ b/tests/Fixtures/Tia/Project.php @@ -131,6 +131,9 @@ final class Project } self::copy(__DIR__.'/app', $path); + + $this->write($directory.DIRECTORY_SEPARATOR.'.gitignore', implode("\n", ['/vendor/', '/.phpunit.cache/', ''])); + $this->scaffoldVendor($path); return $path; @@ -395,7 +398,12 @@ final class Project public function graphDir(): string { - return $this->withHome(fn (): string => Storage::tempDir($this->graphRoot)); + return $this->stateDirFor($this->graphRoot); + } + + public function stateDirFor(string $root): string + { + return $this->withHome(fn (): string => Storage::tempDir($root)); } public function graphExists(): bool diff --git a/tests/Unit/Plugins/Tia/ChangedFiles.php b/tests/Unit/Plugins/Tia/ChangedFiles.php new file mode 100644 index 00000000..0016a9f6 --- /dev/null +++ b/tests/Unit/Plugins/Tia/ChangedFiles.php @@ -0,0 +1,287 @@ + + */ +function tiaMonorepoRoots(?string $created = null): array +{ + static $roots = []; + + if ($created !== null) { + $roots[] = $created; + + return $roots; + } + + $all = $roots; + $roots = []; + + return $all; +} + +/** + * @return array{root: string, project: string, repo: GitRepo, sha: string} + */ +function tiaMonorepoRepository(): array +{ + $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-monorepo-'.bin2hex(random_bytes(8)); + + mkdir($root.'/backend/app', 0755, true); + mkdir($root.'/frontend', 0755, true); + + file_put_contents($root.'/backend/app/Service.php', "init('master'); + + return ['root' => $root, 'project' => $root.'/backend', 'repo' => $repo, 'sha' => $repo->sha()]; +} + +afterEach(function (): void { + foreach (tiaMonorepoRoots() as $root) { + new Process(['rm', '-rf', $root])->run(); + } +}); + +it('resolves the project prefix inside the repository', function (): void { + $monorepo = tiaMonorepoRepository(); + + expect(new ChangedFiles($monorepo['project'])->gitPrefix())->toBe('backend/') + ->and(new ChangedFiles($monorepo['root'])->gitPrefix())->toBeEmpty(); +})->skipOnWindows(); + +it('keeps a space that begins the name of the project directory', function (): void { + $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-monorepo-'.bin2hex(random_bytes(8)); + + mkdir($root.'/ backend/app', 0755, true); + file_put_contents($root.'/ backend/app/Service.php', "init('master'); + + file_put_contents($root.'/ backend/app/Service.php', "gitPrefix())->toBe(' backend/') + ->and($project->since($repo->sha()))->toBe(['app/Service.php']); +})->skipOnWindows(); + +it('keeps the character that ends the name of the repository root', function (string $lastCharacter): void { + $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-monorepo-'.bin2hex(random_bytes(8)).$lastCharacter; + + mkdir($root.'/backend/app', 0755, true); + mkdir($root.'/frontend', 0755, true); + file_put_contents($root.'/backend/app/Service.php', "init('master'); + + file_put_contents($root.'/backend/app/Service.php', "since($repo->sha()))->toBe(['app/Service.php']) + ->and($project->outsideProject())->toBe(['frontend/widget.php']); +})->with(['a space' => ' ', 'a carriage return' => "\r"])->skipOnWindows(); + +it('reports working tree changes relative to the project, dropping siblings', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['project'].'/app/Service.php', "since($monorepo['sha'])) + ->toBe(['app/Service.php']); +})->skipOnWindows(); + +it('reports committed changes relative to the project, dropping siblings', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['project'].'/app/Service.php', "commit('Second commit'); + + expect(new ChangedFiles($monorepo['project'])->since($monorepo['sha'])) + ->toBe(['app/Service.php']); +})->skipOnWindows(); + +it('drops a file whose content came back to its baseline across the prefix boundary', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['project'].'/app/Service.php', "commit('Change the service'); + + file_put_contents($monorepo['project'].'/app/Service.php', "commit('Put the service back'); + + expect(new ChangedFiles($monorepo['project'])->since($monorepo['sha']))->toBe([]); +})->skipOnWindows(); + +it('honours a gitignore inside the project', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['project'].'/.gitignore', "/ignored.php\n"); + file_put_contents($monorepo['project'].'/ignored.php', "since($monorepo['sha'])) + ->toContain('app/Service.php') + ->not->toContain('ignored.php'); +})->skipOnWindows(); + +it('leaves a project at the repository root untouched', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['root'].'/frontend/widget.php', "since($monorepo['sha'])) + ->toBe(['frontend/widget.php']); +})->skipOnWindows(); + +it('reports the changes it left outside the project', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['project'].'/app/Service.php', "since($monorepo['sha']); + + expect($changedFiles->outsideProject())->toBe(['frontend/widget.php']); +})->skipOnWindows(); + +it('reports nothing outside the project for a project at the repository root', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['root'].'/frontend/widget.php', "since($monorepo['sha']); + + expect($changedFiles->outsideProject())->toBeEmpty(); +})->skipOnWindows(); + +it('ties a fingerprint to the project location inside the repository', function (): void { + $monorepo = tiaMonorepoRepository(); + + mkdir($monorepo['root'].'/admin/app', 0755, true); + file_put_contents($monorepo['root'].'/admin/app/Service.php', "commit('add a second project'); + + $nested = Fingerprint::compute($monorepo['project']); + $sibling = Fingerprint::compute($monorepo['root'].'/admin'); + $root = Fingerprint::compute($monorepo['root']); + + expect($nested['structural']['project_prefix'])->toBe('backend/') + ->and($sibling['structural']['project_prefix'])->toBe('admin/') + ->and($root['structural'])->not->toHaveKey('project_prefix') + ->and(Fingerprint::structuralMatches($nested, $sibling))->toBeFalse() + ->and(Fingerprint::structuralMatches($nested, $root))->toBeFalse() + ->and(Fingerprint::structuralDrift($sibling, $nested))->toContain('project_prefix'); +})->skipOnWindows(); + +it('sees a committed non-ascii path that git would otherwise quote', function (): void { + $monorepo = tiaMonorepoRepository(); + + mkdir($monorepo['project'].'/resources/views', 0755, true); + file_put_contents($monorepo['project'].'/resources/views/\u{26a1}orders.blade.php', "
a
\n"); + $monorepo['repo']->commit('add a lightning view'); + + $sha = $monorepo['repo']->sha(); + + file_put_contents($monorepo['project'].'/resources/views/\u{26a1}orders.blade.php', "
b
\n"); + $monorepo['repo']->commit('reword the lightning view'); + + $changedFiles = new ChangedFiles($monorepo['project']); + + expect($changedFiles->since($sha))->toBe(['resources/views/\u{26a1}orders.blade.php']) + ->and($changedFiles->outsideProject())->toBeEmpty(); +})->skipOnWindows(); + +it('sees a committed non-ascii path at the repository root too', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['root'].'/frontend/\u{26a1}widget.php', "commit('add a lightning widget'); + + $sha = $monorepo['repo']->sha(); + + file_put_contents($monorepo['root'].'/frontend/\u{26a1}widget.php', "commit('rework the lightning widget'); + + expect(new ChangedFiles($monorepo['root'])->since($sha)) + ->toBe(['frontend/\u{26a1}widget.php']); +})->skipOnWindows(); + +it('keeps a tracked outside change and drops an untracked ignored one', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['root'].'/.gitignore', "dist/\n"); + mkdir($monorepo['root'].'/frontend/dist', 0755, true); + file_put_contents($monorepo['root'].'/frontend/dist/bundle.js', "var a = 1;\n"); + $monorepo['repo']->run(['add', '-f', 'frontend/dist/bundle.js']); + $monorepo['repo']->commit('track a built bundle that the ignore rules match'); + + $sha = $monorepo['repo']->sha(); + + file_put_contents($monorepo['root'].'/frontend/dist/bundle.js', "var a = 2;\n"); + file_put_contents($monorepo['root'].'/frontend/dist/untracked.js', "var b = 1;\n"); + $monorepo['repo']->commit('rebuild the bundle'); + + $changedFiles = new ChangedFiles($monorepo['project']); + $changedFiles->since($sha); + + expect($changedFiles->outsideProject())->toBe(['frontend/dist/bundle.js']); +})->skipOnWindows(); + +it('keeps a tracked project change that the ignore rules match', function (): void { + $monorepo = tiaMonorepoRepository(); + + file_put_contents($monorepo['root'].'/.gitignore', "build/\n"); + mkdir($monorepo['project'].'/build', 0755, true); + file_put_contents($monorepo['project'].'/build/Generated.php', "run(['add', '-f', 'backend/build/Generated.php']); + $monorepo['repo']->commit('track a generated file that the ignore rules match'); + + $sha = $monorepo['repo']->sha(); + + file_put_contents($monorepo['project'].'/build/Generated.php', "commit('regenerate the file'); + + expect(new ChangedFiles($monorepo['project'])->since($sha)) + ->toBe(['build/Generated.php']); +})->skipOnWindows(); + +it('reads committed paths from the repository root even when git is told to be relative', function (): void { + $monorepo = tiaMonorepoRepository(); + + $monorepo['repo']->run(['config', 'diff.relative', 'true']); + + file_put_contents($monorepo['project'].'/app/Service.php', "commit('rework both sides'); + + $changedFiles = new ChangedFiles($monorepo['project']); + + expect($changedFiles->since($monorepo['sha']))->toBe(['app/Service.php']) + ->and($changedFiles->outsideProject())->toBe(['frontend/widget.php']); +})->skipOnWindows(); diff --git a/tests/Unit/Plugins/Tia/Storage.php b/tests/Unit/Plugins/Tia/Storage.php index 0f164348..a5199767 100644 --- a/tests/Unit/Plugins/Tia/Storage.php +++ b/tests/Unit/Plugins/Tia/Storage.php @@ -9,6 +9,8 @@ use Pest\Plugins\Tia\FileState; use Pest\Plugins\Tia\Storage; use Pest\Support\Container; use Pest\TestSuite; +use Symfony\Component\Process\Process; +use Tests\Fixtures\Tia\GitRepo; afterEach(function (): void { Storage::useDirectory(null); @@ -37,3 +39,32 @@ it('uses an absolute configured directory', function (): void { expect(Storage::tempDir('/project'))->toBe('/tmp/pest-tia'); }); + +it('keeps the state directory of a project at the repository root', function (): void { + $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-storage-'.bin2hex(random_bytes(8)); + + mkdir($root.'/backend', 0755, true); + + $repo = new GitRepo($root); + $repo->init('master'); + $repo->addOrigin('git@github.com:pestphp/tia-fixture.git'); + + $home = $root.DIRECTORY_SEPARATOR.'.home'; + mkdir($home, 0755, true); + + $original = getenv('HOME'); + putenv('HOME='.$home); + + try { + $rootDir = Storage::tempDir($root); + $nestedDir = Storage::tempDir($root.'/backend'); + } finally { + putenv($original === false ? 'HOME' : 'HOME='.$original); + new Process(['rm', '-rf', $root])->run(); + } + + $identity = substr(hash('sha256', 'github.com/pestphp/tia-fixture'), 0, 16); + + expect(basename($rootDir))->toEndWith('-'.$identity) + ->and(basename($nestedDir))->not->toEndWith('-'.$identity); +})->skipOnWindows(); diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index 507b1dde..d97a8025 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, 30 skipped, 1792 passed (3849 assertions)'; + $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1810 passed (3880 assertions)'; expect($output) ->toContain("Tests: {$expected}")