*/ 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(); } Project::destroyAll(); }); 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(); it('tells a working tree change outside the project from a committed one', function (): void { $monorepo = tiaMonorepoRepository(); file_put_contents($monorepo['root'].'/frontend/widget.php', "commit('rework the widget'); file_put_contents($monorepo['root'].'/frontend/other.php', "since($monorepo['sha']); expect($changedFiles->outsideProject())->toBe(['frontend/widget.php', 'frontend/other.php']) ->and($changedFiles->outsideProjectDirty())->toBe(['frontend/other.php']); })->skipOnWindows(); it('keeps a changed file whose name is a number as a string', function (): void { $project = Project::make(); $sha = $project->git()->sha(); file_put_contents($project->path('123'), "changed\n"); $project->git()->commit('add a file with a numeric name'); expect(new ChangedFiles($project->path())->since($sha))->toBe(['123']); })->skipOnWindows(); it('keeps a changed file outside the project whose name is a number as a string', function (): void { $monorepo = tiaMonorepoRepository(); file_put_contents($monorepo['root'].'/123', "outside\n"); file_put_contents($monorepo['project'].'/123', "inside\n"); $monorepo['repo']->commit('add files with a numeric name'); $changedFiles = new ChangedFiles($monorepo['project']); expect($changedFiles->since($monorepo['sha']))->toBe(['123']) ->and($changedFiles->outsideProject())->toBe(['123']); })->skipOnWindows(); it('matches no external root for a changed file whose name is a number', function (): void { $monorepo = tiaMonorepoRepository(); $previous = (string) getcwd(); mkdir($monorepo['root'].'/packages/shared/src', 0755, true); file_put_contents($monorepo['root'].'/packages/shared/src/Shared.php', " ['psr-4' => ['Shared\\' => '../packages/shared/src']], ], JSON_PRETTY_PRINT)); $monorepo['repo']->commit('let the project load a sibling package'); $sha = $monorepo['repo']->sha(); file_put_contents($monorepo['root'].'/123', "changed\n"); $monorepo['repo']->commit('add a file with a numeric name'); chdir($monorepo['project']); ExternalSources::flush(); try { $changedFiles = new ChangedFiles($monorepo['project']); $changedFiles->since($sha); $matched = ExternalSources::matching($monorepo['project'], $changedFiles->outsideProject()); } finally { chdir($previous); ExternalSources::flush(); } expect($matched)->toBeEmpty(); })->skipOnWindows(); it('hashes an external input without reading it into memory', function (): void { $monorepo = tiaMonorepoRepository(); $handle = fopen($monorepo['root'].'/frontend/database.sqlite', 'wb'); ftruncate($handle, 64 * 1024 * 1024); fclose($handle); $changedFiles = new ChangedFiles($monorepo['project']); memory_reset_peak_usage(); $before = memory_get_peak_usage(); $tree = $changedFiles->baselineTree($monorepo['sha'], ['frontend/database.sqlite']); expect(memory_get_peak_usage() - $before)->toBeLessThan(8 * 1024 * 1024) ->and($tree)->toHaveKey('../frontend/database.sqlite'); })->skipOnWindows(); it('sees a whitespace change inside an external input', function (): void { $monorepo = tiaMonorepoRepository(); file_put_contents($monorepo['root'].'/frontend/data.js', "export default \"a b\";\n"); $changedFiles = new ChangedFiles($monorepo['project']); $tree = $changedFiles->baselineTree($monorepo['sha'], ['frontend/data.js']); file_put_contents($monorepo['root'].'/frontend/data.js', "export default \"a b\";\n"); expect($changedFiles->changedSinceLastRun([], ['frontend/data.js'], $tree))->toBe([[], ['frontend/data.js']]); })->skipOnWindows(); it('reports a changed file whose name looks like a pathspec', function (): void { $monorepo = tiaMonorepoRepository(); file_put_contents($monorepo['project'].'/:(fixtures).php', "since($monorepo['sha']))->toContain(':(fixtures).php'); })->skipOnWindows(); it('reports an external input that the listing no longer names', function (): void { $monorepo = tiaMonorepoRepository(); file_put_contents($monorepo['root'].'/frontend/generated.php', "externalInputHashes(['frontend/generated.php']); expect($changedFiles->changedExternalInputs($before, $changedFiles->externalInputHashes([])))->toBe(['frontend/generated.php']) ->and($changedFiles->changedExternalInputs($before, $changedFiles->externalInputHashes(['frontend/generated.php'])))->toBeEmpty(); })->skipOnWindows(); it('reports no change for an external input it cannot read', function (): void { $monorepo = tiaMonorepoRepository(); file_put_contents($monorepo['root'].'/frontend/secret.php', "changedExternalInputs( $changedFiles->externalInputHashes(['frontend/secret.php']), $changedFiles->externalInputHashes(['frontend/secret.php']), ))->toBeEmpty(); } finally { chmod($monorepo['root'].'/frontend/secret.php', 0644); } })->skipOnWindows()->skip(function_exists('posix_geteuid') && posix_geteuid() === 0, 'root reads every file.'); it('keeps a snapshotted file whose name is a number as a string', function (): void { $project = Project::make(); file_put_contents($project->path('123'), "changed\n"); expect(new ChangedFiles($project->path())->filterUnchangedSinceLastRun([], ['123' => 'stale']))->toBe(['123']); }); it('keeps a branch whose name is a number as a string', function (): void { $project = Project::make(); $project->git()->switchTo('123', new: true); expect(new ChangedFiles($project->path())->branchNames())->toBe(['123', 'master']); }); it('reads the baseline of many changed files and keeps their order', function (): void { $monorepo = tiaMonorepoRepository(); $project = $monorepo['project']; foreach (['a', 'b', 'c', 'd', 'e'] as $name) { file_put_contents($project.'/app/'.$name.'.php', "commit('Add the files'); $sha = $monorepo['repo']->sha(); file_put_contents($project.'/app/a.php', "commit('Change a and c'); file_put_contents($project.'/app/c.php', "since($sha)) ->toBe(['app/a.php', 'app/b.php', 'app/d.php', 'app/new.php']); })->skipOnWindows(); /** * @param list $paths * @return array{0: bool, 1: list} */ function tiaShowEach(Git $git, string $sha, array $paths): array { $contents = array_fill(0, count($paths), 'not received'); $succeeded = $git->showEach($sha, $paths, function (int $position, ?string $content) use (&$contents): void { $contents[$position] = $content; }); return [$succeeded, $contents]; } function tiaWithFakeCatFile(string $mode, string $catFile, Closure $run): mixed { $realGit = (string) new ExecutableFinder()->find('git'); $directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-fake-git-'.bin2hex(random_bytes(8)); mkdir($directory); file_put_contents($directory.'/git', "#!/bin/sh\nif [ \"\$1\" = cat-file ] && [ \"\$2\" = ".$mode." ]; then\n read -r first\n cat > /dev/null\n ".$catFile."\nfi\nexec ".escapeshellarg($realGit)." \"\$@\"\n"); chmod($directory.'/git', 0755); $path = (string) getenv('PATH'); $envPath = $_ENV['PATH'] ?? null; $serverPath = $_SERVER['PATH'] ?? null; putenv('PATH='.$directory.PATH_SEPARATOR.$path); $_SERVER['PATH'] = $_ENV['PATH'] = $directory.PATH_SEPARATOR.$path; try { return $run(); } finally { putenv('PATH='.$path); $_SERVER['PATH'] = $serverPath ?? $path; if ($envPath !== null) { $_ENV['PATH'] = $envPath; } else { unset($_ENV['PATH']); } new Process(['rm', '-rf', $directory])->run(); } } it('reads many baselines with one call and gives the same content as one call per file', function (): void { $monorepo = tiaMonorepoRepository(); $root = $monorepo['root']; file_put_contents($root.'/empty.txt', ''); file_put_contents($root.'/binary.bin', "\x00\n\x01\n\n"); file_put_contents($root."/new\nline.txt", "line\n"); file_put_contents($root."/return.txt\r", "carriage\n"); $monorepo['repo']->commit('Add the files'); $git = new Git($root); $sha = $monorepo['repo']->sha(); $paths = ['backend/app/Service.php', 'missing.php', 'empty.txt', 'backend', "new\nline.txt", 'binary.bin', "return.txt\r", 'frontend/widget.php']; [$succeeded, $contents] = tiaShowEach($git, $sha, $paths); expect($succeeded)->toBeTrue() ->and($contents)->toBe(array_map(static fn (string $path): ?string => $git->show($sha, $path), $paths)) ->and($contents[3])->toStartWith('tree '); })->skipOnWindows(); it('reads no baseline when the commit does not exist', function (): void { $monorepo = tiaMonorepoRepository(); expect(tiaShowEach(new Git($monorepo['root']), str_repeat('0', 40), ['backend/app/Service.php']))->toBe([true, [null]]); })->skipOnWindows(); it('reads the baseline of each file again when the batch fails', function (string $mode, string $catFile): void { $monorepo = tiaMonorepoRepository(); $project = $monorepo['project']; file_put_contents($project.'/app/Service.php', "commit('Change the service'); file_put_contents($project.'/app/Service.php', " tiaShowEach($git, $monorepo['sha'], ['backend/app/Service.php'])[0]))->toBeFalse() ->and(tiaWithFakeCatFile($mode, $catFile, fn (): ?array => new ChangedFiles($project)->since($monorepo['sha'])))->toBe(['app/Other.php']); })->with([ 'a failed check' => ['--batch-check', 'exit 1'], 'a check line that does not parse' => ['--batch-check', 'echo "not a header"; exit 0'], 'a check without a line' => ['--batch-check', 'exit 0'], 'a failed read' => ['--batch', 'exit 1'], 'a header that does not parse after one blob' => ['--batch', 'printf "%s blob 1\nx\nnot a header\n" "$first"; exit 0'], 'a missing blob' => ['--batch', 'exit 0'], 'bytes after the last blob' => ['--batch', 'printf "%s blob 1\nx\nextra" "$first"; exit 0'], 'a blob without its line feed' => ['--batch', 'printf "%s blob 1\nxy" "$first"; exit 0'], 'another blob than the one asked' => ['--batch', 'printf "0123abcd blob 1\nx\n"; exit 0'], ])->skipOnWindows(); it('raises a timed out read of the baseline blobs instead of answering', function (): void { $monorepo = tiaMonorepoRepository(); $git = new Git($monorepo['root'], 0.5); expect(fn (): mixed => tiaWithFakeCatFile('--batch', 'sleep 5; exit 0', fn (): array => tiaShowEach($git, $monorepo['sha'], ['backend/app/Service.php']))) ->toThrow(GitTimedOut::class, 'Git did not answer within 0.5 seconds: git cat-file --batch'); })->skipOnWindows(); it('reads the baseline of many large changed files within a small memory limit', function (): void { $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-baseline-memory-'.bin2hex(random_bytes(8)); mkdir($root, 0755, true); tiaMonorepoRoots($root); $repo = new GitRepo($root); $repo->init('master'); foreach (range(1, 6) as $number) { file_put_contents($root.'/asset'.$number.'.bin', random_bytes(8_000_000)); } $repo->commit('Add the large assets'); $sha = $repo->sha(); foreach (range(1, 6) as $number) { file_put_contents($root.'/asset'.$number.'.bin', 'x', FILE_APPEND); } $script = 'require '.var_export(dirname(__DIR__, 4).'/vendor/autoload.php', true).';' .'echo json_encode(new Pest\Plugins\Tia\ChangedFiles('.var_export($root, true).')->since('.var_export($sha, true).'));'; $process = new Process([PHP_BINARY, '-d', 'memory_limit=64M', '-r', $script]); $process->run(); expect($process->getErrorOutput().$process->getOutput())->not->toContain('Allowed memory size') ->and($process->getOutput())->toBe('["asset1.bin","asset2.bin","asset3.bin","asset4.bin","asset5.bin","asset6.bin"]'); })->skipOnWindows();