Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions .github/scripts/ci-test-routing.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ const rootScripts = JSON.parse(read('package.json')).scripts;
* A run block with each `pnpm <root script>` replaced by the script's body,
* recursively; arguments after the script name stay after its body.
*/
// The spec-only lane's run of the tests that read a changed record
// (fs-guard-tests.test.mjs holds its contract); not a lane's suite.
const specReaderRun = step =>
/ tests that read a changed record$/.test(step.name ?? '');

function expandScripts(run) {
return run.replace(/\bpnpm ([a-z][\w:-]*)(?=\s|$)/g, (whole, name) =>
Object.hasOwn(rootScripts, name) ? expandScripts(rootScripts[name]) : whole,
Expand Down Expand Up @@ -147,8 +152,10 @@ describe.each(Object.entries(WORKFLOWS))(
it('runs FR23 only after the parallel UI suite has exited', () => {
const benchmark = 'packages/core/src/Markdown/Markdown.fr23.perf.test.ts';
const job = workflow.jobs['test-ui'];
const suites = job.steps.filter(step =>
expandScripts(step.run ?? '').includes('--project ui'),
const suites = job.steps.filter(
step =>
!specReaderRun(step) &&
expandScripts(step.run ?? '').includes('--project ui'),
);
// The two package scripts every lane calls: the parallel suite without
// FR23, and FR23 alone with no file parallelism.
Expand Down Expand Up @@ -242,8 +249,10 @@ describe.each(Object.entries(WORKFLOWS))(
);
expect(Object.keys(job.strategy.matrix)).toEqual(['shard']);
expect(job.strategy['fail-fast']).toBe(false);
const suites = job.steps.filter(step =>
/--project \w+/.test(expandScripts(step.run ?? '')),
const suites = job.steps.filter(
step =>
!specReaderRun(step) &&
/--project \w+/.test(expandScripts(step.run ?? '')),
);
// The one step that is not sharded is the isolated FR23 benchmark.
const unsharded = suites.filter(
Expand Down Expand Up @@ -330,8 +339,10 @@ describe.each(Object.entries(WORKFLOWS))(
`${lane} has no scope step`,
).toBe(true);
const steps = workflow.jobs[lane].steps;
const suite = steps.find(step =>
expandScripts(step.run ?? '').includes('--project'),
const suite = steps.find(
step =>
!specReaderRun(step) &&
expandScripts(step.run ?? '').includes('--project'),
);
expect(suite.if, `${lane} suite is unconditional`).toContain(
"docsite_only != 'true'",
Expand Down
179 changes: 176 additions & 3 deletions .github/scripts/fs-guard-tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@
// subpath) or a relative path into its `dist/`. A project that loads a
// package from its build sees its source change only through those.
//
// Usage: node .github/scripts/fs-guard-tests.mjs [--changed <ref>]
// - With `--spec-readers --changed <ref>`: instead, the tests that read a
// changed record (spec, component, family, design or theme spec record;
// a renamed one under both names). A spec-only pull request runs no other
// Vitest test, so these are the ones its change can break
// (spec:AST-030 FR2). `--project ui|node` keeps one Vitest project's.
//
// Usage: node .github/scripts/fs-guard-tests.mjs [--spec-readers [--project ui|node]] [--changed <ref>]
// (newline-separated paths)

import {execFileSync} from 'node:child_process';
Expand Down Expand Up @@ -181,25 +187,192 @@ export function scopedExtraTests(files, read, changedFiles = []) {
return files.filter(file => guards.has(file));
}

/**
* The roots of the records a spec-only change may touch (change-scope.cjs's
* spec records): spec and component records, family and design contracts,
* and theme package specs.
*/
const RECORD_ROOTS = [
'docs/specs/',
'docs/families/',
'docs/design/',
'packages/themes/',
];
/** A path literal into a record root, relative (`../…/docs/specs/…`) or from the root. */
const RECORD_LITERAL =
/(['"`])((?:\.\.?\/)*(?:docs\/(?:specs|families|design)|packages\/themes)(?:\/[^'"`\n]*)?)\1/g;
/** `path.join(root, 'docs', 'specs', …)` and the like: the whole root. */
const RECORD_SEGMENTS =
/(['"])(docs|packages)\1\s*,\s*(['"])(specs|families|design|themes)\3/g;
const RECORD_PATH =
/^(?:docs\/(?:specs|families|design)\/|packages\/themes\/[^/]+\/[^/]+\.spec\.md$)/;

/** The source without block comments and whole-line `//` comments, where prose names records. */
function code(source) {
return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also strips /**/ inside string literals, so a reader written fs.globSync('docs/specs/**/spec.md') becomes 'docs/specsspec.md' and is never listed. Stripping only block comments that start a line or follow whitespace keeps it: source.replace(/(^|\s)\/\*[\s\S]*?\*\//g, '$1').

}

/**
* The record paths a file names in its code, as repository paths: an exact
* record, a directory, or a prefix where a template computes the rest
* (`docs/specs/${id}/spec.md` names the whole spec tree).
*/
function recordPathsIn(file, source) {
const body = code(source);
const paths = new Set();
// Theme packages hold sources as well as their spec, and many tests read
// those sources; a file reads theme specs only if it also names a
// `.spec.md`.
const namesSpecFile = /\.spec\.md['"`]/.test(body);
const counts = root => root !== 'packages/themes/' || namesSpecFile;
for (const [, , literal] of body.matchAll(RECORD_LITERAL)) {
const fixed = literal.split('${')[0];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A glob literal such as 'docs/specs/*/spec.md' is cut back to docs/specs/*/, which no changed path starts with. Cutting at the first glob character too (literal.split(/\$\{|[*?[{]/)[0]) names docs/specs/; a ** and a */ glob fixture would pin it.

const joined = fixed.startsWith('.')
? path.posix.normalize(path.posix.join(path.posix.dirname(file), fixed))
: fixed;
const root = RECORD_ROOTS.find(
prefix => joined === prefix.slice(0, -1) || joined.startsWith(prefix),
);
if (root && counts(root))
paths.add(joined.length < root.length ? root : joined);
}
for (const [, , first, , second] of body.matchAll(RECORD_SEGMENTS)) {
const root = `${first}/${second}/`;
if (RECORD_ROOTS.includes(root) && counts(root)) paths.add(root);
}
return paths;
}

/**
* The directories whose tests the Vitest `ui` project collects, read from
* vitest.config.ts so the two cannot drift; every other test belongs to the
* `node` project. Throws when the config's `ui` include list has another
* shape, so a config change fails the lister instead of misrouting tests.
*
* @param {string} config the source of vitest.config.ts
* @returns {string[]} directory prefixes, each ending in `/`
*/
export function uiTestRoots(config) {
const block = /name:\s*'ui'[\s\S]*?include:\s*\[([\s\S]*?)\]/.exec(config);
if (!block) throw new Error('vitest.config.ts: no ui project include list');
const roots = [...block[1].matchAll(/'([^']+)'/g)].map(([, glob]) => {
const match = /^(.+\/)\*\*\/\*\.test\.\{ts,tsx,mjs\}$/.exec(glob);
if (!match)
throw new Error(`vitest.config.ts: unexpected ui include ${glob}`);
return match[1];
});
if (roots.length === 0)
throw new Error('vitest.config.ts: empty ui project include list');
return roots;
}

/**
* The tests that read a record a spec-only change may touch: the import
* closure (relative imports followed, as for the guards above) reads files
* and names a record path in its code. With `changedFiles`, only those whose
* named paths cover a changed record: the record itself, a directory above
* it, or a computed prefix. A renamed record counts under both names, so the
* caller passes the change's paths without rename detection.
*
* @param {string[]} files tracked repository paths
* @param {(file: string) => string} read
* @param {string[] | null} changedFiles the change's paths, or null for every reader
*/
export function specReaderTests(files, read, changedFiles = null) {
const tracked = new Set(files);
const memo = new Map();
const visit = (file, visiting) => {
if (memo.has(file)) return memo.get(file);
const result = {reads: false, paths: new Set()};
if (visiting.has(file)) return result;
visiting.add(file);
let source = '';
try {
source = read(file);
} catch {
source = '';
}
result.reads = READS_FILES.test(source);
for (const named of recordPathsIn(file, source)) result.paths.add(named);
for (const [, raw] of source.matchAll(SPECIFIER)) {
if (!raw.startsWith('.')) continue;
const target = resolve(file, raw, tracked);
if (target == null) continue;
const inner = visit(target, visiting);
result.reads ||= inner.reads;
for (const named of inner.paths) result.paths.add(named);
}
visiting.delete(file);
memo.set(file, result);
return result;
};
const changedSpecs =
changedFiles == null
? null
: changedFiles.filter(file => RECORD_PATH.test(file));
return files.filter(file => {
if (!TEST_FILE.test(file)) return false;
const {reads, paths} = visit(file, new Set());
if (!reads || paths.size === 0) return false;
if (changedSpecs == null) return true;
return changedSpecs.some(changed =>
[...paths].some(
named =>
changed === named ||
changed.startsWith(named.endsWith('/') ? named : `${named}/`),
Comment on lines +347 to +348

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A computed prefix that ends inside a path segment, such as `docs/specs/AST-${id}/spec.md` or 'docs/specs/AST-' + id, names docs/specs/AST-. Appending / here means it matches no record, so that reader is listed with no --changed but never selected for a change. Cutting a truncated literal back to its last / (or matching changed.startsWith(named) for computed prefixes) would keep the description's whole-tree rule.

),
);
});
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
const files = execFileSync('git', ['ls-files', '-z'], {
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
})
.split('\0')
.filter(Boolean);
const specReaders = process.argv.includes('--spec-readers');
const changedFlag = process.argv.indexOf('--changed');
const changedFiles =
changedFlag === -1
? []
: execFileSync(
'git',
['diff', '--name-only', '-z', process.argv[changedFlag + 1], 'HEAD'],
[
'diff',
'--name-only',
'-z',
// A renamed record counts under its old name too: a test that
// reads the old path is the one the rename breaks.
...(specReaders ? ['--no-renames'] : []),
process.argv[changedFlag + 1],
'HEAD',
],
{encoding: 'utf8', maxBuffer: 64 * 1024 * 1024},
)
.split('\0')
.filter(Boolean);
const read = file => fs.readFileSync(file, 'utf8');
const tests = scopedExtraTests(files, read, changedFiles);
let tests;
if (specReaders) {
tests = specReaderTests(
files,
read,
changedFlag === -1 ? null : changedFiles,
);
// `--project ui|node`: only that Vitest project's tests.
const projectFlag = process.argv.indexOf('--project');
if (projectFlag !== -1) {
const project = process.argv[projectFlag + 1];
if (project !== 'ui' && project !== 'node')
throw new Error(`--project must be ui or node, not ${project}`);
const roots = uiTestRoots(read('vitest.config.ts'));
const inUi = test => roots.some(root => test.startsWith(root));
tests = tests.filter(test => inUi(test) === (project === 'ui'));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No test runs this filter: the split case recomputes it inline, so flipping === to !== keeps all 32 lister cases green. With that flip, an AST-094 change sends the Node readers to test-ui and roles.test.ts to test-node, and both legs print "No test files found, exiting with code 0" under --passWithNoTests. A CLI contract case per project (as the rename case does), plus dropping --passWithNoTests from the reader runs, would catch it.

}
} else {
tests = scopedExtraTests(files, read, changedFiles);
}
process.stdout.write(tests.length > 0 ? `${tests.join('\n')}\n` : '');
}
Loading
Loading