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 `<projectRoot>/.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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
This commit is contained in:
Jhon Farias
2026-11-22 16:11:58 +01:00
committed by GitHub
parent 66e585081a
commit a2d3e6badd
14 changed files with 1052 additions and 142 deletions
@@ -1,44 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Pest\Contracts\Panicable;
use RuntimeException;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class TiaRequiresRepositoryRoot extends RuntimeException implements ExceptionInterface, Panicable, RenderlessEditor, RenderlessTrace
{
public function __construct(private readonly string $subdirectoryPrefix)
{
parent::__construct(sprintf(
'Tia mode requires the project root to be the git repository root, but this project sits in the subdirectory [%s] of a larger repository. Please give it its own repository to use Tia.',
$this->subdirectoryPrefix,
));
}
public function render(OutputInterface $output): void
{
$output->writeln([
'',
' <fg=white;options=bold;bg=red> ERROR </> Tia mode requires the git repository root.',
'',
sprintf(' This project sits in a subdirectory of a larger repo <fg=yellow>%s</>.', $this->subdirectoryPrefix),
'',
' Give the project its own git repository to use Tia.',
'',
]);
}
public function exitCode(): int
{
return 1;
}
}
+142 -23
View File
@@ -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<int, string> $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<int, string> $affectedFromChanges
* @param array<int, string> $rerunFromCache
* @param array<int, string> $affected
* @param array<int, string> $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(' <fg=gray>… +%d more</>', $remainder));
}
$this->reportChangesOutsideProject($outsideProject);
}
/**
* @return array<int, string>
*/
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<int, string> $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<int, string> $phpChanges
* @param array<int, string> $arguments
* @return array<int, string>
*/
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<int, string> $files
* @return array<int, string>
*/
private function phpFiles(array $files): array
{
return array_values(array_filter(
$files,
static fn (string $file): bool => str_ends_with($file, '.php'),
));
}
/**
* @param array<int, string> $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(' <fg=gray>%s</>', $file));
}
}
/**
* @param array<int, string> $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 '';
+2 -17
View File
@@ -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();
}
/**
+124 -9
View File
@@ -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<string, true>
*/
private array $outsideProject = [];
/**
* @var array<string, true>
*/
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<int, string> $files repository-relative paths, as printed by git.
* @return array<int, string> 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<int, string>
*/
public function outsideProject(): array
{
return array_map(strval(...), array_keys($this->outsideProject));
}
/**
* @return array<int, string>
*/
public function outsideProjectDirty(): array
{
return array_map(strval(...), array_keys($this->outsideProjectDirty));
}
/**
* @param array<int, string> $files project-relative paths.
* @param array<string, string> $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<string, true>
*/
private function filterIgnored(array $candidates): array
{
return $this->filterIgnoredWith($this->git, $candidates);
}
/**
* @param array<string, true> $candidates
* @return array<string, true>
*/
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<int, string>
*/
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<int, string>
*/
+32 -9
View File
@@ -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)) {
+13 -21
View File
@@ -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
+34 -4
View File
@@ -49,6 +49,22 @@ final readonly class Git
return $output === '' ? null : $output;
}
/**
* @param array<int, string> $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<int, string> $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']);
}
}