Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
99 changes: 97 additions & 2 deletions .github/scripts/fs-guard-tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
// 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 spec record (`docs/specs/`). A spec-only pull request runs no other
// Vitest test, so these are the ones its change can break
// (spec:AST-030 FR2).
//
// Usage: node .github/scripts/fs-guard-tests.mjs [--spec-readers] [--changed <ref>]
// (newline-separated paths)

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

const SPEC_ROOT = 'docs/specs/';
/** A path literal into the spec tree, relative (`../…/docs/specs/…`) or from the root. */
const SPEC_LITERAL = /(['"`])((?:\.\.?\/)*docs\/specs(?:\/[^'"`\n]*)?)\1/g;
/** `path.join(root, 'docs', 'specs', …)` and the like: the whole tree. */
const SPEC_SEGMENTS = /(['"])docs\1\s*,\s*(['"])specs\2/;

/** 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 spec-tree 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 tree).
*/
function specPathsIn(file, source) {
const body = code(source);
const paths = new Set();
for (const [, , literal] of body.matchAll(SPEC_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;
if (joined === 'docs/specs' || joined.startsWith(SPEC_ROOT))
paths.add(joined.length < SPEC_ROOT.length ? SPEC_ROOT : joined);
}
if (SPEC_SEGMENTS.test(body)) paths.add(SPEC_ROOT);
return paths;
}

/**
* The tests that read a spec record: the import closure (relative imports
* followed, as for the guards above) reads files and names a spec-tree 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.
*
* @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 specPathsIn(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 => file.startsWith(SPEC_ROOT));

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.

The trusted classifier's spec-only lane also admits docs/families/*.md, docs/design/*.md and packages/themes/<t>/<t>.spec.md (change-scope.cjs:22-27). This filter drops them, so a family-only change lists no readers, even though scripts/check-knowledge.test.mjs reads those records through validateKnowledgeRoot(repoRoot). Either count every spec-only record path (and recognise those roots in SPEC_LITERAL), or narrow FR2's owner text to docs/specs/ records.

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',
Expand All @@ -200,6 +293,8 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
.split('\0')
.filter(Boolean);
const read = file => fs.readFileSync(file, 'utf8');
const tests = scopedExtraTests(files, read, changedFiles);
const tests = process.argv.includes('--spec-readers')
? specReaderTests(files, read, changedFlag === -1 ? null : changedFiles)
: scopedExtraTests(files, read, changedFiles);
process.stdout.write(tests.length > 0 ? `${tests.join('\n')}\n` : '');
}
148 changes: 147 additions & 1 deletion .github/scripts/fs-guard-tests.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ import {execFileSync} from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';

import {fsGuardTests, scopedExtraTests} from './fs-guard-tests.mjs';
import {
fsGuardTests,
scopedExtraTests,
specReaderTests,
} from './fs-guard-tests.mjs';
import yaml from 'yaml';

const sources = {
'packages/core/src/Button/Button.test.tsx':
Expand Down Expand Up @@ -170,3 +175,144 @@ describe('scopedExtraTests on this repository (contract)', () => {
}
});
});

describe('specReaderTests: the tests a spec-only change runs (spec:AST-030 FR2)', () => {
const sources = {
// Reads one record by a path relative to itself.
'packages/core/src/motion/roles.test.ts':
"import {readFileSync} from 'node:fs';\nconst spec = readFileSync(resolve(import.meta.dirname, '../../../../docs/specs/AST-094-x/spec.md'), 'utf8');",
// Reads the component tree through a helper it imports.
'scripts/components.test.mjs': "import {records} from './lib/records.mjs';",
'scripts/lib/records.mjs':
"import fs from 'node:fs';\nexport const records = () => fs.readdirSync('docs/specs/components');",
// A computed record path names the whole tree.
'scripts/any.test.mjs':
"import fs from 'node:fs';\nconst read = id => fs.readFileSync(`docs/specs/${id}/spec.md`, 'utf8');",
// So does path.join(root, 'docs', 'specs', …).
'scripts/joined.test.mjs':
"import fs from 'node:fs';\nconst dir = path.join(root, 'docs', 'specs');",
// Names a record only in prose.
'packages/core/src/Button/Button.a11y.test.tsx':
"import fs from 'node:fs';\n/**\n * The contract (`docs/specs/AST-021/spec.md` FR5).\n */\n// see docs/specs/AST-021/spec.md\nexport {};",
// Names a record as data but reads no files.
'scripts/classify.test.mjs':
"const path = 'docs/specs/AST-094-x/spec.md';\nexpect(classify(path)).toBe(true);",
};
const files = Object.keys(sources);
const read = file => sources[file];

it('lists every test whose imports read files and name a spec path in code', () => {
expect(specReaderTests(files, read)).toEqual([
'packages/core/src/motion/roles.test.ts',
'scripts/components.test.mjs',
'scripts/any.test.mjs',
'scripts/joined.test.mjs',
]);
});

it('narrows to the readers of a changed record: the record, a directory above it, or the whole tree', () => {
expect(
specReaderTests(files, read, ['docs/specs/AST-094-x/spec.md']),
).toEqual([
'packages/core/src/motion/roles.test.ts',
'scripts/any.test.mjs',
'scripts/joined.test.mjs',
]);
expect(
specReaderTests(files, read, [
'docs/specs/components/Button/Button.spec.md',
]),
).toEqual([
'scripts/components.test.mjs',
'scripts/any.test.mjs',
'scripts/joined.test.mjs',
]);
// A record no test names at all still runs the whole-tree readers.
expect(
specReaderTests(files, read, ['docs/specs/AST-001/spec.md']),
).toEqual(['scripts/any.test.mjs', 'scripts/joined.test.mjs']);
});

it('lists none for a change outside the spec tree', () => {
expect(specReaderTests(files, read, ['packages/core/src/x.ts'])).toEqual(
[],
);
});
});

describe('spec readers on this repository (contract)', () => {
const root = path.resolve(import.meta.dirname, '../..');
const files = execFileSync('git', ['ls-files', '-z'], {
cwd: root,
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
})
.split('\0')
.filter(Boolean);
const read = file => fs.readFileSync(path.join(root, file), 'utf8');

it('a spec-only change to AST-094 runs the motion roles test that reads its FR4 table', () => {
expect(
specReaderTests(files, read, [
'docs/specs/AST-094-touch-presentations/spec.md',
]),
).toContain('packages/core/src/motion/roles.test.ts');
});

it('a change to AST-084 runs the icon-set checks that read it', () => {
expect(
specReaderTests(files, read, ['docs/specs/AST-084-icon-sets/spec.md']),
).toContain('packages/cli/foundation/discovery/icon-set-checks.test.mjs');
});

const ci = yaml.parse(read('.github/workflows/ci.yml'));
it.each([
['test-ui', 'test:ui'],
['test-node', 'test:node'],
])(
'%s runs the readers of a changed record on a spec-only change, on one leg',
(id, script) => {
const steps = ci.jobs[id].steps;
const index = name => steps.findIndex(step => step.name === name);
const SPEC_LEG =
"matrix.shard == 1 && steps.scope.outputs.spec_only == 'true'";
const checkout =
steps[
index('Check out the change for the tests that read its records')
];
expect(checkout).toMatchObject({
if: SPEC_LEG,
uses: 'actions/checkout@v7',
with: {'fetch-depth': 2},
});
const list = steps[index('List the tests that read a changed record')];
expect(list.if).toBe(SPEC_LEG);
expect(list.run).toContain(
'node .github/scripts/fs-guard-tests.mjs --spec-readers --changed HEAD^1',
);
const setup =
steps[index('List the tests that read a changed record') + 1];
expect(setup).toEqual({
uses: './.github/actions/setup',
if: "steps.spec-readers.outputs.any == 'true'",
});
const runner = steps.find(
step =>
step.name?.startsWith('Run the ') &&
step.name.endsWith(' tests that read a changed record'),
);
expect(runner.if).toBe("steps.spec-readers.outputs.any == 'true'");
expect(runner.run).toContain(
`pnpm ${script} --passWithNoTests "\${READERS[@]}"`,
);
// Before the steps a spec-only change skips.
expect(steps.indexOf(runner)).toBeLessThan(
steps.findIndex(
step =>
step.uses === 'actions/checkout@v7' &&
String(step.if).includes("spec_only != 'true'"),
),
);
},
);
});
Loading
Loading