From b37e0906740d7f619ae600b8e7d2c3ae0759900a Mon Sep 17 00:00:00 2001 From: Einar Hansen Date: Fri, 31 Jul 2026 09:39:45 +0200 Subject: [PATCH 1/3] feat(tia): support projects in git repository subdirectories (monorepos) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tia previously refused to run when the project root was not the git repository root, telling monorepo users to "give the project its own git repository". The underlying problem was a path-space mismatch: git's plumbing (status --porcelain, diff --name-only, show SHA:path) speaks repository-root-relative paths, while the dependency graph, watch patterns and coverage edges all speak project-root-relative paths. ChangedFiles now detects the project's location inside the repository once (git rev-parse --show-prefix) and translates at every git boundary: - status/diff output is mapped to project-relative paths, and paths outside the project subtree are dropped — they are as invisible to the project's graph as files outside the repository are for a root-level project, and leaking them through would hit the unknown-file catch-all and force a full rerun on every sibling-project change; - the diff listing runs with -z (git C-quotes non-ASCII paths, which would silently fail the prefix match and drop a real change — a stale replay) and --no-renames (rename detection reports only the NEW path, so a project file renamed to a path outside the subtree would vanish from the listing; as delete+add both sides surface); - git show SHA:path (behavioural-change filtering, composer.lock drift summaries) resolves project-relative paths through the prefix. A new GitRepository helper locates the governing repository by walking ancestors, fixing three more root==project assumptions: Fingerprint's tracked-lockfile check, BaselineSync's GitHub-repo detection (baseline fetching silently never activated for subdirectory projects), and Storage's origin-based project key — which now also carries the subdirectory prefix, so `apps/api` and `services/api` in one repository never share a graph store. Root-level projects keep their exact existing behaviour: the prefix is empty and every translation is the identity. The TiaRequiresRepositoryRoot exception is removed along with the guard. --- src/Exceptions/TiaRequiresRepositoryRoot.php | 44 ----- src/Plugins/Tia.php | 30 +--- src/Plugins/Tia/BaselineSync.php | 4 +- src/Plugins/Tia/ChangedFiles.php | 81 ++++++++- src/Plugins/Tia/Fingerprint.php | 2 +- src/Plugins/Tia/GitRepository.php | 85 ++++++++++ src/Plugins/Tia/Storage.php | 12 +- tests/.snapshots/success.txt | 28 +++- tests/Unit/Plugins/Tia/ChangedFiles.php | 167 +++++++++++++++++++ tests/Unit/Plugins/Tia/GitRepository.php | 85 ++++++++++ tests/Visual/Parallel.php | 4 +- 11 files changed, 454 insertions(+), 88 deletions(-) delete mode 100644 src/Exceptions/TiaRequiresRepositoryRoot.php create mode 100644 src/Plugins/Tia/GitRepository.php create mode 100644 tests/Unit/Plugins/Tia/ChangedFiles.php create mode 100644 tests/Unit/Plugins/Tia/GitRepository.php diff --git a/src/Exceptions/TiaRequiresRepositoryRoot.php b/src/Exceptions/TiaRequiresRepositoryRoot.php deleted file mode 100644 index 5a122197f..000000000 --- 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 401d6f0ce..a808b64ce 100644 --- a/src/Plugins/Tia.php +++ b/src/Plugins/Tia.php @@ -9,7 +9,6 @@ use Pest\Contracts\Plugins\HandlesArguments; use Pest\Contracts\Plugins\Terminable; use Pest\Exceptions\NoAffectedTestsFound; -use Pest\Exceptions\TiaRequiresRepositoryRoot; use Pest\Panic; use Pest\Plugins\Concerns\HandleArguments; use Pest\Plugins\Tia\BaselineSync; @@ -31,7 +30,6 @@ use Pest\TestSuite; use PHPUnit\Framework\TestStatus\TestStatus; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Process\Process; /** * @internal @@ -629,12 +627,6 @@ private function handleParent(array $arguments, string $projectRoot, bool $force { $this->watchPatterns->useDefaults($projectRoot); - $subdirectoryPrefix = $this->gitSubdirectoryPrefix($projectRoot); - - if ($subdirectoryPrefix !== null) { - Panic::with(new TiaRequiresRepositoryRoot($subdirectoryPrefix)); - } - $this->branch = new ChangedFiles($projectRoot)->currentBranch() ?? 'main'; $fingerprint = Fingerprint::compute($projectRoot); @@ -1699,20 +1691,6 @@ private function formatStructuralDrift(array $drift): string * TIA requires the two to coincide: git reports and addresses paths * relative to the repo root, while the dependency graph is project-relative. */ - private function gitSubdirectoryPrefix(string $projectRoot): ?string - { - $process = new Process(['git', 'rev-parse', '--show-prefix'], $projectRoot); - $process->run(); - - if (! $process->isSuccessful()) { - return null; - } - - $prefix = trim($process->getOutput()); - - return $prefix === '' ? null : rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $prefix), '/'); - } - private function composerLockDelta(string $projectRoot, string $sha): string { $current = @file_get_contents($projectRoot.'/composer.lock'); @@ -1720,15 +1698,13 @@ private function composerLockDelta(string $projectRoot, string $sha): string return ''; } - $process = new Process(['git', 'show', $sha.':composer.lock'], $projectRoot); - $process->setTimeout(5.0); - $process->run(); + $baseline = new ChangedFiles($projectRoot)->contentAtSha($sha, 'composer.lock'); - if (! $process->isSuccessful()) { + if ($baseline === null) { return ''; } - $oldVersions = $this->lockVersions($process->getOutput()); + $oldVersions = $this->lockVersions($baseline); $newVersions = $this->lockVersions($current); if ($oldVersions === [] && $newVersions === []) { diff --git a/src/Plugins/Tia/BaselineSync.php b/src/Plugins/Tia/BaselineSync.php index 5b147883a..f4a90e59b 100644 --- a/src/Plugins/Tia/BaselineSync.php +++ b/src/Plugins/Tia/BaselineSync.php @@ -177,9 +177,9 @@ private function isCi(): bool private function detectGitHubRepo(string $projectRoot): ?string { - $gitConfig = $projectRoot.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config'; + $gitConfig = GitRepository::configPath($projectRoot); - if (! is_file($gitConfig)) { + if ($gitConfig === null) { return null; } diff --git a/src/Plugins/Tia/ChangedFiles.php b/src/Plugins/Tia/ChangedFiles.php index 9ffb680ea..ca35d5af2 100644 --- a/src/Plugins/Tia/ChangedFiles.php +++ b/src/Plugins/Tia/ChangedFiles.php @@ -12,7 +12,26 @@ */ final readonly class ChangedFiles { - public function __construct(private string $projectRoot) {} + /** + * The project root's path relative to the git repository root, with a + * trailing slash (e.g. `apps/api/`), or an empty string when the project + * root is the repository root. + */ + private string $repoPrefix; + + public function __construct(private string $projectRoot) + { + $this->repoPrefix = $this->detectRepoPrefix(); + } + + /** + * The project root's location inside the repository (`apps/api/`), or an + * empty string when the project root is the repository root. + */ + public function repoPrefix(): string + { + return $this->repoPrefix; + } /** * @param array $files project-relative paths. @@ -153,9 +172,13 @@ private function filterBehaviourallyUnchanged(array $files, string $sha): array return $remaining; } - private function contentAtSha(string $sha, string $path): ?string + /** + * The content of a project-relative path at the given commit, or `null` + * when the path did not exist there. + */ + public function contentAtSha(string $sha, string $path): ?string { - $process = new Process(['git', 'show', $sha.':'.$path], $this->projectRoot); + $process = new Process(['git', 'show', $sha.':'.$this->repoPrefix.$path], $this->projectRoot); $process->setTimeout(5.0); $process->run(); @@ -236,7 +259,7 @@ private function shaIsReachable(string $sha): bool private function diffSinceSha(string $sha): array { $process = new Process( - ['git', 'diff', '--name-only', $sha.'..HEAD'], + ['git', 'diff', '--name-only', '-z', '--no-renames', $sha.'..HEAD'], $this->projectRoot, ); $process->run(); @@ -245,7 +268,9 @@ private function diffSinceSha(string $sha): array throw new MissingDependency('Tia mode', 'git'); } - return $this->splitLines($process->getOutput()); + $paths = explode("\x00", rtrim($process->getOutput(), "\x00")); + + return $this->toProjectRelative(array_values(array_filter($paths, static fn (string $path): bool => $path !== ''))); } /** @@ -297,7 +322,7 @@ private function workingTreeChanges(): array $files[] = $path; } - return $files; + return $this->toProjectRelative($files); } public function currentSha(): ?string @@ -315,12 +340,50 @@ public function currentSha(): ?string } /** + * Translates git's repository-root-relative paths into project-relative + * ones, dropping paths outside the project subtree. + * + * @param array $repoRelativePaths * @return array */ - private function splitLines(string $output): array + private function toProjectRelative(array $repoRelativePaths): array + { + if ($this->repoPrefix === '') { + return $repoRelativePaths; + } + + $projectRelative = []; + + foreach ($repoRelativePaths as $path) { + if (str_starts_with($path, $this->repoPrefix)) { + $projectRelative[] = substr($path, strlen($this->repoPrefix)); + } + } + + return $projectRelative; + } + + private function detectRepoPrefix(): string { - $lines = preg_split('/\R+/', trim($output), flags: PREG_SPLIT_NO_EMPTY); + static $cache = []; + + if (isset($cache[$this->projectRoot])) { + return $cache[$this->projectRoot]; + } + + $process = new Process(['git', 'rev-parse', '--show-prefix'], $this->projectRoot); + $process->run(); + + if (! $process->isSuccessful()) { + return $cache[$this->projectRoot] = ''; + } + + $prefix = trim($process->getOutput()); + + if ($prefix === '') { + return $cache[$this->projectRoot] = ''; + } - return $lines === false ? [] : $lines; + return $cache[$this->projectRoot] = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $prefix), '/').'/'; } } diff --git a/src/Plugins/Tia/Fingerprint.php b/src/Plugins/Tia/Fingerprint.php index 0f4823a23..e8a63860c 100644 --- a/src/Plugins/Tia/Fingerprint.php +++ b/src/Plugins/Tia/Fingerprint.php @@ -288,7 +288,7 @@ private static function isTrackedByGit(string $projectRoot, string $relativePath return $cache[$key]; } - if (! is_dir($projectRoot.'/.git') && ! is_file($projectRoot.'/.git')) { + if (GitRepository::locate($projectRoot) === null) { return $cache[$key] = true; } diff --git a/src/Plugins/Tia/GitRepository.php b/src/Plugins/Tia/GitRepository.php new file mode 100644 index 000000000..3acbdfaf1 --- /dev/null +++ b/src/Plugins/Tia/GitRepository.php @@ -0,0 +1,85 @@ +repoRoot = sys_get_temp_dir().'/pest-tia-changed-files-'.bin2hex(random_bytes(4)); + mkdir($this->repoRoot.'/apps/api/app', 0755, true); + mkdir($this->repoRoot.'/apps/web', 0755, true); + + $this->git = function (string ...$command): string { + $process = new Process(['git', ...$command], $this->repoRoot); + $process->mustRun(); + + return trim($process->getOutput()); + }; + + ($this->git)('init', '-q', '-b', 'main'); + ($this->git)('config', 'user.email', 'pest@example.com'); + ($this->git)('config', 'user.name', 'Pest'); + ($this->git)('config', 'commit.gpgsign', 'false'); + + file_put_contents($this->repoRoot.'/README.md', 'root'); + file_put_contents($this->repoRoot.'/apps/api/composer.lock', 'lock-v1'); + file_put_contents($this->repoRoot.'/apps/api/app/Service.php', "repoRoot.'/apps/web/page.tsx', 'web-v1'); + + ($this->git)('add', '-A'); + ($this->git)('commit', '-q', '-m', 'baseline'); + + $this->baselineSha = ($this->git)('rev-parse', 'HEAD'); +}); + +afterEach(function (): void { + $remove = function (string $dir) use (&$remove): void { + foreach (array_diff((array) scandir($dir), ['.', '..']) as $entry) { + $path = $dir.DIRECTORY_SEPARATOR.$entry; + + is_dir($path) && ! is_link($path) ? $remove($path) : @unlink($path); + } + + @rmdir($dir); + }; + + $remove($this->repoRoot); +}); + +describe('repoPrefix()', function (): void { + it('is empty at the repository root', function (): void { + expect(new ChangedFiles($this->repoRoot)->repoPrefix())->toBeEmpty(); + }); + + it('is the slash-terminated subdirectory path for a monorepo project', function (): void { + expect(new ChangedFiles($this->repoRoot.'/apps/api')->repoPrefix())->toBe('apps/api/'); + }); + + it('is empty outside a git repository', function (): void { + $outside = sys_get_temp_dir().'/pest-tia-no-repo-'.bin2hex(random_bytes(4)); + mkdir($outside); + + try { + expect(new ChangedFiles($outside)->repoPrefix())->toBeEmpty(); + } finally { + @rmdir($outside); + } + }); +}); + +describe('since() in a monorepo subdirectory', function (): void { + it('reports project files as project-relative paths', function (): void { + file_put_contents($this->repoRoot.'/apps/api/app/Service.php', "repoRoot.'/apps/api')->since($this->baselineSha); + + expect($changed)->toBe(['app/Service.php']); + }); + + it('includes untracked project files', function (): void { + file_put_contents($this->repoRoot.'/apps/api/app/Fresh.php', "repoRoot.'/apps/api')->since($this->baselineSha); + + expect($changed)->toBe(['app/Fresh.php']); + }); + + it('ignores changes in sibling projects and at the repository root', function (): void { + file_put_contents($this->repoRoot.'/README.md', 'root-changed'); + file_put_contents($this->repoRoot.'/apps/web/page.tsx', 'web-v2'); + + $changed = new ChangedFiles($this->repoRoot.'/apps/api')->since($this->baselineSha); + + expect($changed)->toBe([]); + }); + + it('detects committed changes to files git would C-quote (non-ASCII names)', function (): void { + file_put_contents($this->repoRoot.'/apps/api/app/Ærlig.php', "git)('add', '-A'); + ($this->git)('commit', '-q', '-m', 'add utf-8 named file'); + file_put_contents($this->repoRoot.'/apps/api/app/Ærlig.php', "git)('add', '-A'); + ($this->git)('commit', '-q', '-m', 'change utf-8 named file'); + + $changed = new ChangedFiles($this->repoRoot.'/apps/api')->since($this->baselineSha); + + expect($changed)->toBe(['app/Ærlig.php']); + }); + + it('sees committed changes since the baseline sha', function (): void { + file_put_contents($this->repoRoot.'/apps/api/app/Service.php', "git)('add', '-A'); + ($this->git)('commit', '-q', '-m', 'change service'); + + $changed = new ChangedFiles($this->repoRoot.'/apps/api')->since($this->baselineSha); + + expect($changed)->toBe(['app/Service.php']); + }); + + it('reports a file renamed OUT of the project subtree as a change to the old path', function (): void { + ($this->git)('mv', 'apps/api/app/Service.php', 'apps/web/Service.php'); + ($this->git)('commit', '-q', '-m', 'move service out of the api project'); + + $changed = new ChangedFiles($this->repoRoot.'/apps/api')->since($this->baselineSha); + + expect($changed)->toBe(['app/Service.php']); + }); + + it('drops cosmetic-only changes, comparing against the baseline blob through the prefix', function (): void { + file_put_contents($this->repoRoot.'/apps/api/app/Service.php', "git)('add', '-A'); + ($this->git)('commit', '-q', '-m', 'cosmetic'); + + $changed = new ChangedFiles($this->repoRoot.'/apps/api')->since($this->baselineSha); + + expect($changed)->toBe([]); + }); +}); + +describe('since() at the repository root', function (): void { + it('keeps the existing root-level behaviour', function (): void { + file_put_contents($this->repoRoot.'/README.md', 'root-changed'); + file_put_contents($this->repoRoot.'/apps/api/app/Service.php', "repoRoot)->since($this->baselineSha); + + sort($changed); + + expect($changed)->toBe(['README.md', 'apps/api/app/Service.php']); + }); +}); + +describe('contentAtSha()', function (): void { + it('resolves project-relative paths through the subdirectory prefix', function (): void { + $content = new ChangedFiles($this->repoRoot.'/apps/api') + ->contentAtSha($this->baselineSha, 'composer.lock'); + + expect($content)->toBe('lock-v1'); + }); + + it('returns null for paths missing from the commit', function (): void { + $content = new ChangedFiles($this->repoRoot.'/apps/api') + ->contentAtSha($this->baselineSha, 'nope.txt'); + + expect($content)->toBeNull(); + }); +}); diff --git a/tests/Unit/Plugins/Tia/GitRepository.php b/tests/Unit/Plugins/Tia/GitRepository.php new file mode 100644 index 000000000..19e35f7bd --- /dev/null +++ b/tests/Unit/Plugins/Tia/GitRepository.php @@ -0,0 +1,85 @@ +root = sys_get_temp_dir().'/pest-tia-git-repository-'.bin2hex(random_bytes(4)); + mkdir($this->root.'/apps/api', 0755, true); + mkdir($this->root.'/services/api', 0755, true); + mkdir($this->root.'/.git', 0755); + file_put_contents($this->root.'/.git/config', "[remote \"origin\"]\n\turl = git@github.com:acme/mono.git\n"); +}); + +afterEach(function (): void { + $remove = function (string $dir) use (&$remove): void { + foreach (array_diff((array) scandir($dir), ['.', '..']) as $entry) { + $path = $dir.DIRECTORY_SEPARATOR.$entry; + + is_dir($path) && ! is_link($path) ? $remove($path) : @unlink($path); + } + + @rmdir($dir); + }; + + $remove($this->root); +}); + +describe('locate()', function (): void { + it('finds .git in the path itself', function (): void { + expect(GitRepository::locate($this->root))->toBe($this->root.DIRECTORY_SEPARATOR.'.git'); + }); + + it('walks up to an ancestor .git for subdirectory projects', function (): void { + expect(GitRepository::locate($this->root.'/apps/api')) + ->toBe($this->root.DIRECTORY_SEPARATOR.'.git'); + }); + + it('stops at a nested repository boundary', function (): void { + mkdir($this->root.'/apps/api/.git'); + + expect(GitRepository::locate($this->root.'/apps/api')) + ->toBe($this->root.'/apps/api'.DIRECTORY_SEPARATOR.'.git'); + }); + + it('treats a .git FILE (worktree, submodule) as the governing entry', function (): void { + file_put_contents($this->root.'/apps/api/.git', "gitdir: /elsewhere\n"); + + expect(GitRepository::locate($this->root.'/apps/api')) + ->toBe($this->root.'/apps/api'.DIRECTORY_SEPARATOR.'.git'); + }); +}); + +describe('configPath()', function (): void { + it('resolves the governing repository config for subdirectory projects', function (): void { + expect(GitRepository::configPath($this->root.'/apps/api')) + ->toBe($this->root.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config'); + }); + + it('returns null for a .git FILE, matching the previous degradation', function (): void { + file_put_contents($this->root.'/apps/api/.git', "gitdir: /elsewhere\n"); + + expect(GitRepository::configPath($this->root.'/apps/api'))->toBeNull(); + }); +}); + +describe('subdirectoryPrefix()', function (): void { + it('is empty at the repository root', function (): void { + expect(GitRepository::subdirectoryPrefix($this->root))->toBeEmpty(); + }); + + it('is the slash-terminated project location inside the repository', function (): void { + expect(GitRepository::subdirectoryPrefix($this->root.'/apps/api'))->toBe('apps/api/'); + }); +}); + +describe('storage keys', function (): void { + it('gives same-basename sibling projects distinct stores', function (): void { + $api = Storage::tempDir($this->root.'/apps/api'); + $siblingApi = Storage::tempDir($this->root.'/services/api'); + + expect($api)->not->toBe($siblingApi); + }); +}); diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index b5623e706..801eb3043 100644 --- a/tests/Visual/Parallel.php +++ b/tests/Visual/Parallel.php @@ -24,13 +24,13 @@ $file = file_get_contents(__FILE__); $file = preg_replace( '/\$expected = \'.*?\';/', - "\$expected = '1 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1525 passed (3322 assertions)';", + "\$expected = '1 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1547 passed (3344 assertions)';", $file, ); file_put_contents(__FILE__, $file); } - $expected = '1 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1525 passed (3322 assertions)'; + $expected = '1 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1547 passed (3344 assertions)'; expect($output) ->toContain("Tests: {$expected}") From 3d2c39d165f58663ed1f4dba83518f52aac0c35c Mon Sep 17 00:00:00 2001 From: Einar Hansen Date: Thu, 6 Aug 2026 09:15:19 +0200 Subject: [PATCH 2/3] chore: leave visual snapshots to post-merge regeneration --- tests/.snapshots/success.txt | 28 +--------------------------- tests/Visual/Parallel.php | 4 ++-- 2 files changed, 3 insertions(+), 29 deletions(-) diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index f9a26c198..f6f24f941 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -1834,21 +1834,6 @@ ✓ addOutput → it uses singular form for single test file ✓ addOutput → it returns original exit code when shard is not set - PASS Tests\Unit\Plugins\Tia\ChangedFiles - ✓ repoPrefix() → it is empty at the repository root - ✓ repoPrefix() → it is the slash-terminated subdirectory path for a monorepo project - ✓ repoPrefix() → it is empty outside a git repository - ✓ since() in a monorepo subdirectory → it reports project files as project-relative paths - ✓ since() in a monorepo subdirectory → it includes untracked project files - ✓ since() in a monorepo subdirectory → it ignores changes in sibling projects and at the repository root - ✓ since() in a monorepo subdirectory → it detects committed changes to files git would C-quote (non-ASCII names) - ✓ since() in a monorepo subdirectory → it sees committed changes since the baseline sha - ✓ since() in a monorepo subdirectory → it reports a file renamed OUT of the project subtree as a change to the old path - ✓ since() in a monorepo subdirectory → it drops cosmetic-only changes, comparing against the baseline blob through the prefix - ✓ since() at the repository root → it keeps the existing root-level behaviour - ✓ contentAtSha() → it resolves project-relative paths through the subdirectory prefix - ✓ contentAtSha() → it returns null for paths missing from the commit - PASS Tests\Unit\Plugins\Tia\ContentHash ✓ of() → it returns false when file does not exist ✓ of() → it hashes an existing file @@ -1890,17 +1875,6 @@ ✓ keysWithPrefix() → it lists keys matching the prefix ✓ keysWithPrefix() → it ignores in-flight temporary files from concurrent writes - PASS Tests\Unit\Plugins\Tia\GitRepository - ✓ locate() → it finds .git in the path itself - ✓ locate() → it walks up to an ancestor .git for subdirectory projects - ✓ locate() → it stops at a nested repository boundary - ✓ locate() → it treats a .git FILE (worktree, submodule) as the governing entry - ✓ configPath() → it resolves the governing repository config for subdirectory projects - ✓ configPath() → it returns null for a .git FILE, matching the previous degradation - ✓ subdirectoryPrefix() → it is empty at the repository root - ✓ subdirectoryPrefix() → it is the slash-terminated project location inside the repository - ✓ storage keys → it gives same-basename sibling projects distinct stores - PASS Tests\Unit\Plugins\Tia\Graph ✓ shouldRerunStatus() → it re-runs failures and errors, replays successes ✓ applyMigrationChanges() → it selects tests whose recorded tables intersect the changed migration @@ -2212,4 +2186,4 @@ ✓ pass with dataset with ('my-datas-set-value') ✓ within describe → pass with dataset with ('my-datas-set-value') - Tests: 1 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 35 skipped, 1564 passed (3397 assertions) \ No newline at end of file + Tests: 1 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 35 skipped, 1542 passed (3375 assertions) \ No newline at end of file diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index 801eb3043..b5623e706 100644 --- a/tests/Visual/Parallel.php +++ b/tests/Visual/Parallel.php @@ -24,13 +24,13 @@ $file = file_get_contents(__FILE__); $file = preg_replace( '/\$expected = \'.*?\';/', - "\$expected = '1 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1547 passed (3344 assertions)';", + "\$expected = '1 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1525 passed (3322 assertions)';", $file, ); file_put_contents(__FILE__, $file); } - $expected = '1 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1547 passed (3344 assertions)'; + $expected = '1 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1525 passed (3322 assertions)'; expect($output) ->toContain("Tests: {$expected}") From e933e7f40704f72efcbc5b1b98d9fd93a15d2f56 Mon Sep 17 00:00:00 2001 From: Einar Hansen Date: Fri, 18 Sep 2026 17:26:44 +0200 Subject: [PATCH 3/3] fix(tia): resolve baseline config in worktrees and submodules Follow gitdir files and commondir pointers to locate the governing repository config. Cover GitHub and GitLab baseline detection with real worktrees and submodules, and refresh the suite output snapshots. Co-Authored-By: Claude Opus 5 --- src/Plugins/Tia/GitRepository.php | 50 ++++++++++++++++-- tests/.snapshots/success.txt | 49 ++++++++++++++++- tests/Unit/Plugins/Tia/Baselines.php | 32 +++++++++++ tests/Unit/Plugins/Tia/GitRepository.php | 67 +++++++++++++++++++++++- tests/Visual/Parallel.php | 2 +- 5 files changed, 192 insertions(+), 8 deletions(-) diff --git a/src/Plugins/Tia/GitRepository.php b/src/Plugins/Tia/GitRepository.php index dc16afc01..1d206a71f 100644 --- a/src/Plugins/Tia/GitRepository.php +++ b/src/Plugins/Tia/GitRepository.php @@ -4,9 +4,6 @@ namespace Pest\Plugins\Tia; -/** - * @internal - */ final class GitRepository { public static function locate(string $path): ?string @@ -34,11 +31,17 @@ public static function configPath(string $path): ?string { $dotGit = self::locate($path); - if ($dotGit === null || ! is_dir($dotGit)) { + if ($dotGit === null) { + return null; + } + + $gitDir = is_dir($dotGit) ? $dotGit : self::resolveGitDirFile($dotGit); + + if ($gitDir === null) { return null; } - $config = $dotGit.DIRECTORY_SEPARATOR.'config'; + $config = $gitDir.DIRECTORY_SEPARATOR.'config'; return is_file($config) ? $config : null; } @@ -63,4 +66,41 @@ public static function subdirectoryPrefix(string $projectRoot): string return str_replace(DIRECTORY_SEPARATOR, '/', rtrim($prefix, DIRECTORY_SEPARATOR)).'/'; } + + private static function resolveGitDirFile(string $dotGitFile): ?string + { + $content = @file_get_contents($dotGitFile); + + if ($content === false || preg_match('/^gitdir:\s*(.+)$/m', $content, $match) !== 1) { + return null; + } + + $gitDir = trim($match[1]); + + if (! self::isAbsolutePath($gitDir)) { + $gitDir = dirname($dotGitFile).DIRECTORY_SEPARATOR.$gitDir; + } + + $commonDir = $gitDir.DIRECTORY_SEPARATOR.'commondir'; + + if (is_file($commonDir)) { + $common = trim((string) @file_get_contents($commonDir)); + + if ($common !== '') { + $gitDir = self::isAbsolutePath($common) + ? $common + : $gitDir.DIRECTORY_SEPARATOR.$common; + } + } + + $resolved = @realpath($gitDir); + + return $resolved === false ? null : $resolved; + } + + private static function isAbsolutePath(string $path): bool + { + return str_starts_with($path, DIRECTORY_SEPARATOR) + || preg_match('#^[A-Za-z]:[\\\\/]#', $path) === 1; + } } diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index ce595932b..b70c92bc1 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -1861,6 +1861,30 @@ ✓ addOutput → it uses singular form for single test file ✓ addOutput → it returns original exit code when shard is not set + PASS Tests\Unit\Plugins\Tia\Baselines + ✓ it detects a baseline repository from a project subdirectory with ('github.com') + ✓ it detects a baseline repository from a project subdirectory with ('gitlab.com') + ✓ it uses the nearest repository for baseline detection + ✓ it detects a baseline repository from a project in a worktree with ('github.com') + ✓ it detects a baseline repository from a project in a worktree with ('gitlab.com') + ✓ it detects a submodule baseline repository without using its parent remote with ('github.com') + ✓ it detects a submodule baseline repository without using its parent remote with ('gitlab.com') + + PASS Tests\Unit\Plugins\Tia\ChangedFiles + ✓ repoPrefix() → it is empty at the repository root + ✓ repoPrefix() → it is the slash-terminated subdirectory path for a monorepo project + ✓ repoPrefix() → it is empty outside a git repository + ✓ since() in a monorepo subdirectory → it reports project files as project-relative paths + ✓ since() in a monorepo subdirectory → it includes untracked project files + ✓ since() in a monorepo subdirectory → it ignores changes in sibling projects and at the repository root + ✓ since() in a monorepo subdirectory → it detects committed changes to files git would C-quote (non-ASCII names) + ✓ since() in a monorepo subdirectory → it sees committed changes since the baseline sha + ✓ since() in a monorepo subdirectory → it reports a file renamed OUT of the project subtree as a change to the old path + ✓ since() in a monorepo subdirectory → it drops cosmetic-only changes, comparing against the baseline blob through the prefix + ✓ since() at the repository root → it keeps the existing root-level behaviour + ✓ contentAtSha() → it resolves project-relative paths through the subdirectory prefix + ✓ contentAtSha() → it returns null for paths missing from the commit + PASS Tests\Unit\Plugins\Tia\ContentHash ✓ of() → it returns false when file does not exist ✓ of() → it hashes an existing file @@ -1902,6 +1926,29 @@ ✓ keysWithPrefix() → it lists keys matching the prefix ✓ keysWithPrefix() → it ignores in-flight temporary files from concurrent writes + PASS Tests\Unit\Plugins\Tia\GitRepository + ✓ locate() → it finds .git in the path itself + ✓ locate() → it walks up to an ancestor .git for subdirectory projects + ✓ locate() → it stops at a nested repository boundary + ✓ locate() → it treats a .git FILE (worktree, submodule) as the governing entry + ✓ configPath() → it resolves the governing repository config for subdirectory projects + ✓ configPath() → it resolves the shared config from a worktree with dataset "relative gitdir and commondir" + ✓ configPath() → it resolves the shared config from a worktree with dataset "relative gitdir and absolute commondir" + ✓ configPath() → it resolves the shared config from a worktree with dataset "absolute gitdir and relative commondir" + ✓ configPath() → it resolves the shared config from a worktree with dataset "absolute gitdir and commondir" + ✓ configPath() → it resolves a submodule config without a commondir with dataset "relative gitdir" + ✓ configPath() → it resolves a submodule config without a commondir with dataset "absolute gitdir" + ✓ configPath() → it returns null when the .git file points to a missing directory + ✓ configPath() → it returns null for malformed .git files without using the parent config with dataset "empty file" + ✓ configPath() → it returns null for malformed .git files without using the parent config with dataset "missing gitdir prefix" + ✓ configPath() → it returns null for malformed .git files without using the parent config with dataset "empty gitdir" + ✓ configPath() → it returns null when a repository has no config + ✓ configPath() → it returns null when the referenced git directory has no config + ✓ configPath() → it returns null when the common directory is missing + ✓ subdirectoryPrefix() → it is empty at the repository root + ✓ subdirectoryPrefix() → it is the slash-terminated project location inside the repository + ✓ storage keys → it gives same-basename sibling projects distinct stores + PASS Tests\Unit\Plugins\Tia\Graph ✓ shouldRerunStatus() → it re-runs failures and errors, replays successes ✓ applyMigrationChanges() → it selects tests whose recorded tables intersect the changed migration @@ -2256,4 +2303,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, 35 skipped, 1599 passed (3486 assertions) \ No newline at end of file + Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 35 skipped, 1640 passed (3531 assertions) \ No newline at end of file diff --git a/tests/Unit/Plugins/Tia/Baselines.php b/tests/Unit/Plugins/Tia/Baselines.php index daae1bccb..eb421e990 100644 --- a/tests/Unit/Plugins/Tia/Baselines.php +++ b/tests/Unit/Plugins/Tia/Baselines.php @@ -45,3 +45,35 @@ expect(new GitHubRemote(new WatchPatterns)->detect($nested->path))->toBe('acme/nested'); }); + +it('detects a baseline repository from a project in a worktree', function (string $host): void { + $this->repo->addOrigin('git@'.$host.':acme/mono.git'); + file_put_contents($this->root.'/apps/api/composer.json', '{}'); + $this->repo->commit('Add project'); + $worktree = $this->repo->worktree($this->root.'/worktree', 'feature'); + + $remote = $host === 'github.com' + ? new GitHubRemote(new WatchPatterns) + : new GitLabRemote(new WatchPatterns); + + expect($remote->detect($worktree.'/apps/api'))->toBe('acme/mono'); +})->with(['github.com', 'gitlab.com']); + +it('detects a submodule baseline repository without using its parent remote', function (string $host): void { + $this->repo->addOrigin('git@'.$host.':acme/mono.git'); + mkdir($this->root.'/source'); + $source = new GitRepo($this->root.'/source'); + $source->init(); + mkdir($source->path.'/apps/api', 0755, true); + file_put_contents($source->path.'/apps/api/composer.json', '{}'); + $source->commit('Add project'); + $this->repo->run(['-c', 'protocol.file.allow=always', 'submodule', 'add', $source->path, 'packages/module']); + $submodule = new GitRepo($this->root.'/packages/module'); + $submodule->setOriginUrl('git@'.$host.':acme/module.git'); + + $remote = $host === 'github.com' + ? new GitHubRemote(new WatchPatterns) + : new GitLabRemote(new WatchPatterns); + + expect($remote->detect($submodule->path.'/apps/api'))->toBe('acme/module'); +})->with(['github.com', 'gitlab.com']); diff --git a/tests/Unit/Plugins/Tia/GitRepository.php b/tests/Unit/Plugins/Tia/GitRepository.php index 19e35f7bd..6cc3271fa 100644 --- a/tests/Unit/Plugins/Tia/GitRepository.php +++ b/tests/Unit/Plugins/Tia/GitRepository.php @@ -58,11 +58,76 @@ ->toBe($this->root.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config'); }); - it('returns null for a .git FILE, matching the previous degradation', function (): void { + it('resolves the shared config from a worktree', function (bool $absoluteGitDir, bool $absoluteCommonDir): void { + $worktree = $this->root.'/worktree'; + $gitDir = $this->root.'/.git/worktrees/feature'; + mkdir($worktree.'/apps/api', 0755, true); + mkdir($gitDir, 0755, true); + file_put_contents($worktree.'/.git', 'gitdir: '.($absoluteGitDir ? $gitDir : '../.git/worktrees/feature')."\n"); + file_put_contents($gitDir.'/commondir', ($absoluteCommonDir ? $this->root.'/.git' : '../..')."\n"); + file_put_contents($gitDir.'/config', "[remote \"origin\"]\n\turl = git@github.com:acme/wrong.git\n"); + + expect(GitRepository::configPath($worktree.'/apps/api')) + ->toBe(realpath($this->root.'/.git').DIRECTORY_SEPARATOR.'config') + ->and(GitRepository::subdirectoryPrefix($worktree.'/apps/api'))->toBe('apps/api/'); + })->with([ + 'relative gitdir and commondir' => [false, false], + 'relative gitdir and absolute commondir' => [false, true], + 'absolute gitdir and relative commondir' => [true, false], + 'absolute gitdir and commondir' => [true, true], + ]); + + it('resolves a submodule config without a commondir', function (bool $absoluteGitDir): void { + $gitDir = $this->root.'/.git/modules/api'; + mkdir($gitDir, 0755, true); + file_put_contents($gitDir.'/config', "[remote \"origin\"]\n\turl = git@github.com:acme/api.git\n"); + file_put_contents($this->root.'/apps/api/.git', 'gitdir: '.($absoluteGitDir ? $gitDir : '../../.git/modules/api')."\n"); + + expect(GitRepository::configPath($this->root.'/apps/api')) + ->toBe(realpath($gitDir).DIRECTORY_SEPARATOR.'config'); + })->with([ + 'relative gitdir' => [false], + 'absolute gitdir' => [true], + ]); + + it('returns null when the .git file points to a missing directory', function (): void { file_put_contents($this->root.'/apps/api/.git', "gitdir: /elsewhere\n"); expect(GitRepository::configPath($this->root.'/apps/api'))->toBeNull(); }); + + it('returns null for malformed .git files without using the parent config', function (string $content): void { + file_put_contents($this->root.'/apps/api/.git', $content); + + expect(GitRepository::configPath($this->root.'/apps/api'))->toBeNull(); + })->with([ + 'empty file' => [''], + 'missing gitdir prefix' => ["../../.git\n"], + 'empty gitdir' => ["gitdir:\n"], + ]); + + it('returns null when a repository has no config', function (): void { + unlink($this->root.'/.git/config'); + + expect(GitRepository::configPath($this->root.'/apps/api'))->toBeNull(); + }); + + it('returns null when the referenced git directory has no config', function (): void { + mkdir($this->root.'/.git/modules/api', 0755, true); + file_put_contents($this->root.'/apps/api/.git', "gitdir: ../../.git/modules/api\n"); + + expect(GitRepository::configPath($this->root.'/apps/api'))->toBeNull(); + }); + + it('returns null when the common directory is missing', function (): void { + $gitDir = $this->root.'/.git/worktrees/feature'; + mkdir($gitDir, 0755, true); + file_put_contents($this->root.'/apps/api/.git', 'gitdir: '.$gitDir."\n"); + file_put_contents($gitDir.'/commondir', "../../../missing\n"); + file_put_contents($gitDir.'/config', "[remote \"origin\"]\n\turl = git@github.com:acme/wrong.git\n"); + + expect(GitRepository::configPath($this->root.'/apps/api'))->toBeNull(); + }); }); describe('subdirectoryPrefix()', function (): void { diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index 3837686fc..91c24300c 100644 --- a/tests/Visual/Parallel.php +++ b/tests/Visual/Parallel.php @@ -20,7 +20,7 @@ $output = $run('--exclude-group=integration'); $output = implode("\n", array_slice(explode("\n", (string) $output), -10)); - $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1581 passed (3431 assertions)'; + $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1622 passed (3476 assertions)'; expect($output) ->toContain("Tests: {$expected}")