Compare commits

...

3 Commits

Author SHA1 Message Date
Ben Dailey 4cfeb458fe fix(tia): end the SFC script tag after quoted attributes that hold > (#2063)
Co-authored-by: Ben Dailey <ben@dev-deb12>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-22 21:32:28 +05:30
Jhon Farias 5cb7a1c043 fix(tia): keep the results of a parallel full-suite fallback (#2067) 2026-11-22 21:02:01 +05:30
Jhon Farias a2d3e6badd 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>
2026-11-22 20:41:58 +05:30
17 changed files with 1153 additions and 143 deletions
+1 -1
View File
@@ -13,7 +13,7 @@ const PAGE_EXTENSIONS = new Set([
'.mts', '.cts', '.mjs', '.cjs',
])
const SFC_RE = /\.(vue|svelte)$/i
const SCRIPT_BLOCK_RE = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi
const SCRIPT_BLOCK_RE = /<script\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/script>/gi
const ASSET_EXT_RE = /\.(css|scss|sass|less|styl|stylus|svg|png|jpe?g|gif|webp|avif|ico|bmp|woff2?|ttf|eot|otf|md|mdx|txt|html|mp4|webm|mp3|wav|ogg|m4a|pdf|wasm|glsl|frag|vert)$/i
const PROJECT_ROOT = resolve(process.argv[2] ?? process.cwd())
const PAGE_DIR_CANDIDATES = [
@@ -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;
}
}
+143 -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),
@@ -1116,6 +1117,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
if ($hasProjectPhpSourceChanges && ! $coverageAvailable) {
$this->fullSuiteFallbackRan = true;
$this->requestWorkerResults();
$this->renderBadge('WARN', 'Detected PHP source changes but no coverage driver is available.');
$this->renderChild('Running the full suite to avoid using a stale dependency graph.');
@@ -1143,7 +1145,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 +1210,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 +1281,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 +2368,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 +2383,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 +2390,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']);
}
}
+34 -1
View File
@@ -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
@@ -2252,6 +2272,9 @@
✓ it keeps every import a single file component declares with ('default-export-in-line-comment')
✓ it keeps every import a single file component declares with ('default-export-in-block-comment')
✓ it keeps every import a single file component declares with ('default-export-in-string')
✓ it keeps every import a single file component declares with ('generic-attribute')
✓ it keeps every import a single file component declares with ('generic-attribute-single-quoted')
✓ it keeps every import a single file component declares with ('generic-attribute-before-lang')
✓ it reports the script block language so the parser matches it with ('script-setup')
✓ it reports the script block language so the parser matches it with ('plain-script-with-default')
✓ it reports the script block language so the parser matches it with ('typescript-lang')
@@ -2266,6 +2289,9 @@
✓ it reports the script block language so the parser matches it with ('default-export-in-line-comment')
✓ it reports the script block language so the parser matches it with ('default-export-in-block-comment')
✓ it reports the script block language so the parser matches it with ('default-export-in-string')
✓ it reports the script block language so the parser matches it with ('generic-attribute')
✓ it reports the script block language so the parser matches it with ('generic-attribute-single-quoted')
✓ it reports the script block language so the parser matches it with ('generic-attribute-before-lang')
✓ it always leaves a default export for importers to resolve against with ('script-setup')
✓ it always leaves a default export for importers to resolve against with ('plain-script-with-default')
✓ it always leaves a default export for importers to resolve against with ('typescript-lang')
@@ -2280,6 +2306,12 @@
✓ it always leaves a default export for importers to resolve against with ('default-export-in-line-comment')
✓ it always leaves a default export for importers to resolve against with ('default-export-in-block-comment')
✓ it always leaves a default export for importers to resolve against with ('default-export-in-string')
✓ it always leaves a default export for importers to resolve against with ('generic-attribute')
✓ it always leaves a default export for importers to resolve against with ('generic-attribute-single-quoted')
✓ it always leaves a default export for importers to resolve against with ('generic-attribute-before-lang')
✓ it ends the opening script tag after a quoted attribute that holds a closing angle bracket with ('generic-attribute')
✓ it ends the opening script tag after a quoted attribute that holds a closing angle bracket with ('generic-attribute-single-quoted')
✓ it ends the opening script tag after a quoted attribute that holds a closing angle bracket with ('generic-attribute-before-lang')
✓ it does not add a second default export when the block already has one
✓ it drops template and style markup that the parser would reject
✓ it stubs assets as JS modules so rolldown does not reject them as CSS with ('/app/resources/css/app.css')
@@ -2291,6 +2323,7 @@
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-block-comment')
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-string')
- it bundles a script setup component that mentions export default in a comment → rolldown is not resolvable.
- it bundles a generic component whose script tag holds a closing angle bracket → rolldown is not resolvable.
PASS Tests\Unit\Plugins\Tia\WatchPatterns
✓ it keeps the built-in fallbacks enabled by default
@@ -2627,4 +2660,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)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 39 skipped, 1949 passed (4417 assertions)
-12
View File
@@ -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']);
+356
View File
@@ -0,0 +1,356 @@
<?php
declare(strict_types=1);
use Pest\Plugins\Tia;
use Pest\Support\Coverage;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
/**
* @return array{0: Project, 1: string}
*/
function tiaMonorepo(string $directory = 'nested'): array
{
$project = Project::make('master');
$nested = $project->nested($directory);
$project->write($directory.'/resources/views/greeting.blade.php', "<p>Hello</p>\n");
$project->write('frontend/widget.php', "<?php\n\n\$widget = 1;\n");
$project->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", [
'<?php',
'',
'declare(strict_types=1);',
'',
"require_once __DIR__.'/../../shared/greeting.php';",
"require_once __DIR__.'/../app/Calculator.php';",
"require_once __DIR__.'/../app/Greeter.php';",
'',
]));
$project->write('nested/app/Greeter.php', implode("\n", [
'<?php',
'',
'declare(strict_types=1);',
'',
'namespace Fixture\\App;',
'',
'final class Greeter',
'{',
' public function greet(string $name): string',
' {',
' return \\shared_greeting($name);',
' }',
'}',
'',
]));
$project->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", [
'<?php',
'',
'declare(strict_types=1);',
'',
'function shared_greeting(string $name): string',
'{',
sprintf(' return %s(sprintf(%s, $name));', $wrapper, var_export($format, true)),
'}',
'',
]);
}
test('a project in a subdirectory of the repository replays its baseline', function (array $arguments): void {
[$project, $nested] = tiaMonorepo();
$result = $project->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', "<p>Hi</p>\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', "<p>Hi</p>\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', "<p>Hi</p>\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'
<?php
declare(strict_types=1);
namespace Fixture\App;
final class Greeter
{
public function greet(string $name): string
{
(new Calculator)->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", [
'<?php',
'',
'declare(strict_types=1);',
'',
'function shared_greeting(string $name): string',
'{',
' (new \\Fixture\\App\\Calculator)->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', "<p>Hi</p>\n");
$project->git()->commit('reword the greeting');
$project->write('nested/resources/views/greeting.blade.php', "<p>Hello</p>\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<string, mixed> $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();
+23
View File
@@ -2,6 +2,7 @@
declare(strict_types=1);
use PHPUnit\Framework\TestStatus\TestStatus;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
@@ -385,3 +386,25 @@ test('a full suite run without a coverage driver clears the tree it could not re
->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe())
->and($delta->writtenCount())->toBe(0, $delta->summary());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('a full suite run without a coverage driver records the results it ran', function (array $arguments): void {
$project = Project::make('master');
$project->seed('master');
$id = Project::testId('tests/Unit/CalculatorTest.php', 'adds two numbers');
expect($project->graph()['baselines']['master']['results'][$id]['status'])->toBe(TestStatus::success()->asInt());
$project->write('app/Calculator.php', str_replace(
'return $a + $b;',
'return $a - $b;',
(string) file_get_contents($project->path().'/app/Calculator.php'),
));
$project->git()->commit('break the adder');
$result = $project->pestWithEnvironment($project->path(), ['XDEBUG_MODE' => 'off'], '--tia', ...$arguments);
expect($result->exitCode)->toBe(1, $result->describe())
->and($result->output)->toContain('no coverage driver is available')
->and($project->graph()['baselines']['master']['results'][$id]['status'])->toBe(TestStatus::failure()->asInt());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
+9 -1
View File
@@ -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
+287
View File
@@ -0,0 +1,287 @@
<?php
declare(strict_types=1);
use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\Fingerprint;
use Symfony\Component\Process\Process;
use Tests\Fixtures\Tia\GitRepo;
/**
* @return array<int, string>
*/
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', "<?php\n\$service = 1;\n");
file_put_contents($root.'/frontend/widget.php', "<?php\n\$widget = 1;\n");
tiaMonorepoRoots($root);
$repo = new GitRepo($root);
$repo->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', "<?php\n\$service = 1;\n");
tiaMonorepoRoots($root);
$repo = new GitRepo($root);
$repo->init('master');
file_put_contents($root.'/ backend/app/Service.php', "<?php\n\$service = 2;\n");
$project = new ChangedFiles($root.'/ backend');
expect($project->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', "<?php\n\$service = 1;\n");
file_put_contents($root.'/frontend/widget.php', "<?php\n\$widget = 1;\n");
tiaMonorepoRoots($root);
$repo = new GitRepo($root);
$repo->init('master');
file_put_contents($root.'/backend/app/Service.php', "<?php\n\$service = 2;\n");
file_put_contents($root.'/frontend/widget.php', "<?php\n\$widget = 2;\n");
$project = new ChangedFiles($root.'/backend');
expect($project->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', "<?php\n\$service = 2;\n");
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
expect(new ChangedFiles($monorepo['project'])->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', "<?php\n\$service = 2;\n");
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
$monorepo['repo']->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', "<?php\n\$service = 2;\n");
$monorepo['repo']->commit('Change the service');
file_put_contents($monorepo['project'].'/app/Service.php', "<?php\n\$service = 1;\n");
$monorepo['repo']->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', "<?php\n");
file_put_contents($monorepo['project'].'/app/Service.php', "<?php\n\$service = 2;\n");
expect(new ChangedFiles($monorepo['project'])->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', "<?php\n\$widget = 2;\n");
expect(new ChangedFiles($monorepo['root'])->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', "<?php\n\$service = 2;\n");
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
$changedFiles = new ChangedFiles($monorepo['project']);
$changedFiles->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', "<?php\n\$widget = 2;\n");
$changedFiles = new ChangedFiles($monorepo['root']);
$changedFiles->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', "<?php\n\$service = 1;\n");
$monorepo['repo']->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', "<div>a</div>\n");
$monorepo['repo']->commit('add a lightning view');
$sha = $monorepo['repo']->sha();
file_put_contents($monorepo['project'].'/resources/views/\u{26a1}orders.blade.php', "<div>b</div>\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', "<?php\n\$widget = 1;\n");
$monorepo['repo']->commit('add a lightning widget');
$sha = $monorepo['repo']->sha();
file_put_contents($monorepo['root'].'/frontend/\u{26a1}widget.php', "<?php\n\$widget = 2;\n");
$monorepo['repo']->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', "<?php\n\$built = 1;\n");
$monorepo['repo']->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', "<?php\n\$built = 2;\n");
file_put_contents($monorepo['project'].'/build/Untracked.php', "<?php\n");
$monorepo['repo']->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', "<?php\n\$service = 2;\n");
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
$monorepo['repo']->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();
+31
View File
@@ -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();
+63
View File
@@ -473,6 +473,18 @@ function tiaSfcFixtures(): array
"<script setup>\nimport A from '@/A.vue'\nconst hint = 'export default'\n</script>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'generic-attribute' => [
"<script setup lang=\"ts\" generic=\"T extends Record<string, unknown>\">\nimport E from '@/E.vue'\n</script>",
['imports' => ['@/E.vue'], 'moduleType' => 'ts'],
],
'generic-attribute-single-quoted' => [
"<script setup lang='ts' generic='T extends Array<string>'>\nimport F from '@/F.vue'\n</script>",
['imports' => ['@/F.vue'], 'moduleType' => 'ts'],
],
'generic-attribute-before-lang' => [
"<script setup generic=\"K extends string, V extends Map<K, number>\" lang=\"ts\">\nimport G from '@/G.vue'\n</script>",
['imports' => ['@/G.vue'], 'moduleType' => 'ts'],
],
];
}
@@ -630,6 +642,10 @@ it('always leaves a default export for importers to resolve against', function (
expect(tiaSfcResults()[$name]['code'])->toMatch('/export\s+default\b/');
})->with(array_keys(tiaSfcFixtures()));
it('ends the opening script tag after a quoted attribute that holds a closing angle bracket', function (string $name): void {
expect(tiaSfcResults()[$name]['code'])->toStartWith("\nimport ");
})->with(['generic-attribute', 'generic-attribute-single-quoted', 'generic-attribute-before-lang']);
it('does not add a second default export when the block already has one', function (): void {
preg_match_all('/export\s+default\b/', tiaSfcResults()['plain-script-with-default']['code'], $matches);
@@ -711,3 +727,50 @@ it('bundles a script setup component that mentions export default in a comment',
'resources/js/components/format.js' => ['Dashboard'],
]);
});
it('bundles a generic component whose script tag holds a closing angle bracket', function (): void {
$rolldown = tiaRolldownPackageDir();
if ($rolldown === null) {
$this->markTestSkipped('rolldown is not resolvable.');
}
$root = sys_get_temp_dir().'/pest-tia-rolldown-generic-'.bin2hex(random_bytes(6));
mkdir($root.'/resources/js/pages', 0755, true);
mkdir($root.'/resources/js/components', 0755, true);
mkdir($root.'/node_modules', 0755, true);
$root = realpath($root);
symlink($rolldown, $root.'/node_modules/rolldown');
file_put_contents($root.'/package.json', '{}');
file_put_contents($root.'/resources/js/pages/Items.vue', <<<'VUE'
<script setup lang="ts">
import SortableList from '../components/SortableList.vue'
</script>
<template><SortableList :items="[]" /></template>
VUE);
file_put_contents($root.'/resources/js/components/SortableList.vue', <<<'VUE'
<script setup lang="ts" generic="T extends Record<string, unknown>">
import { label } from './label.ts'
defineProps<{ items: T[] }>()
</script>
<template><li v-for="item in items">{{ label(item) }}</li></template>
VUE);
file_put_contents($root.'/resources/js/components/label.ts', "export const label = (v: unknown): string => String(v)\n");
$process = new Process(['node', tiaViteHelperPath(), $root]);
$process->run();
unlink($root.'/node_modules/rolldown');
foreach (['resources/js/pages/Items.vue', 'resources/js/components/SortableList.vue', 'resources/js/components/label.ts', 'package.json'] as $file) {
@unlink($root.'/'.$file);
}
foreach (['node_modules', 'resources/js/pages', 'resources/js/components', 'resources/js', 'resources', ''] as $dir) {
@rmdir($root.'/'.$dir);
}
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
->and(json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR))->toMatchArray([
'resources/js/components/SortableList.vue' => ['Items'],
'resources/js/components/label.ts' => ['Items'],
]);
});
+1 -1
View File
@@ -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, 31 skipped, 1822 passed (3892 assertions)';
expect($output)
->toContain("Tests: {$expected}")