Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

ci(api-report): warn when a pull request changes a package's API and leaves its report behind (#10006)

Cindy Zhang3918c1d87c67
diff --git a/scripts/api-report/api-report.test.mjs b/scripts/api-report/api-report.test.mjs
index 0d4823e875..9c66fa5cb3 100644
--- a/scripts/api-report/api-report.test.mjs
+++ b/scripts/api-report/api-report.test.mjs
@@ -21,6 +21,7 @@ import {
diffReports,
parseReport,
renderChanges,
+ staleReportWarnings,
usageFor,
} from './changes.mjs';
import {chooseBase, publishedPackages} from './cli.mjs';
@@ -285,6 +286,169 @@ describe('API changes', () => {
expect(md).not.toContain("prop size?: ChipSize = 'sm'");
});
+ describe('a warning when this pull request leaves its own rows out of the report', () => {
+ const file = () => 'packages/demo/api-report.md';
+ const warn = input => staleReportWarnings(computeChanges([input]), file);
+
+ it('warns when the pull request changes a row and does not regenerate the report', () => {
+ const [change] = computeChanges([
+ {
+ pkg: '@astryxdesign/demo',
+ base: report,
+ head: resize(report),
+ committed: report,
+ baseSource: 'build',
+ },
+ ]);
+ expect(change.staleOwnRows).toBe(1);
+ expect(staleReportWarnings([change], file)).toEqual([
+ '::warning file=packages/demo/api-report.md,title=API report not regenerated::' +
+ "This pull request changes 1 row of @astryxdesign/demo's public API " +
+ 'that its committed api-report.md does not show. Run pnpm api:report and commit the report.',
+ ]);
+ });
+
+ it('counts only its own rows when the report was already behind main', () => {
+ const [change] = computeChanges([
+ {
+ pkg: '@astryxdesign/demo',
+ base: resize(report),
+ head: addTone(resize(report)),
+ committed: report,
+ baseSource: 'build',
+ },
+ ]);
+ expect(change).toMatchObject({
+ stale: true,
+ staleRows: 2,
+ staleOwnRows: 1,
+ });
+ expect(staleReportWarnings([change], file)[0]).toContain(
+ 'changes 1 row of',
+ );
+ });
+
+ it('counts a wholly added component as one row, as the pull request report does', () => {
+ const withChip2 = text =>
+ text.replace(
+ '### Components\n\n```text\n',
+ '### Components\n\n```text\ncomponent Chip2\n prop a?: string\n prop b?: string\n prop c?: string\n prop d?: string\n prop e?: string\n',
+ );
+ const head = withChip2(report);
+ expect(head).not.toBe(report);
+ const [change] = computeChanges([
+ {
+ pkg: '@astryxdesign/demo',
+ base: report,
+ head,
+ committed: report,
+ baseSource: 'build',
+ },
+ ]);
+ expect(change.counts.added).toBe(1);
+ expect(change).toMatchObject({staleRows: 1, staleOwnRows: 1});
+ expect(staleReportWarnings([change], file)[0]).toContain(
+ 'changes 1 row of',
+ );
+ });
+
+ // Small hand-written reports: one component with two props.
+ const tiny = ({
+ item = 'component Chip',
+ size = "'md'",
+ tone = "'neutral'",
+ chip = true,
+ } = {}) =>
+ '## `.`\n\n### Components\n\n```text\n' +
+ (chip
+ ? `${item}\n prop size?: ChipSize = ${size}\n prop tone?: ChipTone = ${tone}\n`
+ : '') +
+ '```\n';
+
+ it('warns for a prop change to a component the committed report lacks entirely', () => {
+ const [change] = computeChanges([
+ {
+ pkg: '@astryxdesign/demo',
+ base: tiny(),
+ head: tiny({size: "'sm'"}),
+ committed: tiny({chip: false}),
+ baseSource: 'build',
+ },
+ ]);
+ expect(change.rows.map(r => r.member)).toEqual(['size']);
+ expect(change.staleOwnRows).toBe(1);
+ });
+
+ it('does not count a changed item line the report already shows, when another member is behind', () => {
+ const head = tiny({item: 'component Chip<T>'});
+ const [change] = computeChanges([
+ {
+ pkg: '@astryxdesign/demo',
+ base: tiny(),
+ head,
+ committed: tiny({item: 'component Chip<T>', tone: "'accent'"}),
+ baseSource: 'build',
+ },
+ ]);
+ expect(change.rows.map(r => [r.item, r.member])).toEqual([
+ ['component Chip', null],
+ ]);
+ expect(change).toMatchObject({
+ stale: true,
+ staleRows: 1,
+ staleOwnRows: 0,
+ });
+ });
+
+ it('does not warn for a report that was stale before the pull request', () => {
+ expect(
+ warn({
+ pkg: '@astryxdesign/demo',
+ base: resize(report),
+ head: resize(report),
+ committed: report,
+ baseSource: 'build',
+ }),
+ ).toEqual([]);
+ });
+
+ it('does not warn when the pull request regenerated its report', () => {
+ expect(
+ warn({
+ pkg: '@astryxdesign/demo',
+ base: report,
+ head: resize(report),
+ committed: resize(report),
+ baseSource: 'build',
+ }),
+ ).toEqual([]);
+ });
+
+ it("does not warn against the merge base's committed report, which cannot tell the rows apart", () => {
+ expect(
+ warn({
+ pkg: '@astryxdesign/demo',
+ base: report,
+ head: resize(report),
+ committed: report,
+ baseSource: 'committed',
+ }),
+ ).toEqual([]);
+ });
+
+ it('does not warn for a new package with no report at the merge base', () => {
+ expect(
+ warn({
+ pkg: '@astryxdesign/demo',
+ base: null,
+ head: report,
+ committed: null,
+ baseSource: 'build',
+ }),
+ ).toEqual([]);
+ });
+ });
+
it('renders a stale report with no API change as one line', () => {
const md = renderChanges(
computeChanges([
diff --git a/scripts/api-report/changes.mjs b/scripts/api-report/changes.mjs
index 44d1ee4099..a44a0cc370 100644
--- a/scripts/api-report/changes.mjs
+++ b/scripts/api-report/changes.mjs
@@ -78,9 +78,13 @@ export function parseReport(text) {
});
}
}
+ for (const [key, row] of rows) ROW_KEY.set(row, key);
return rows;
}
+/** Each parsed row's key in its report, for matching rows across two diffs. */
+const ROW_KEY = new WeakMap();
+
function itemName(line) {
if (/^[\w$]+ \(/.test(line)) return line.split(' ')[0]; // `Name (./entry)` in an also-exported list
const m = line.match(/^(\w+) ([^\s(:<=]+)(?: (\([^)]*\)))?/);
@@ -118,12 +122,22 @@ export function diffReports(base, head) {
const added = [];
const changed = [];
const removed = [];
+ // Every differing key before folding, so a caller can match single members.
+ const keys = new Set();
for (const [k, row] of b) {
if (!a.has(k)) added.push(row);
- else if (a.get(k).line !== row.line)
- changed.push({...row, before: a.get(k).line});
+ else if (a.get(k).line !== row.line) {
+ const change = {...row, before: a.get(k).line};
+ ROW_KEY.set(change, k);
+ changed.push(change);
+ } else continue;
+ keys.add(k);
}
- for (const [k, row] of a) if (!b.has(k)) removed.push(row);
+ for (const [k, row] of a)
+ if (!b.has(k)) {
+ removed.push(row);
+ keys.add(k);
+ }
// A wholly added or removed item reports once, not once per member.
const fold = rows => {
const items = new Set(
@@ -135,7 +149,7 @@ export function diffReports(base, head) {
r => !r.member || !items.has(`${r.entry}\0${r.section}\0${r.item}`),
);
};
- return {added: fold(added), changed, removed: fold(removed)};
+ return {added: fold(added), changed, removed: fold(removed), keys};
}
/**
@@ -186,6 +200,34 @@ export function usageFor(pkg, row) {
const rowCount = ({added, changed, removed}) =>
added.length + changed.length + removed.length;
+/** The rows of a `diffReports` result, in one list. */
+const rowsOf = ({added, changed, removed}) => [
+ ...added,
+ ...changed,
+ ...removed,
+];
+
+/**
+ * How many of the pull request's rows its committed report does not show,
+ * counted as the pull request report counts them (a wholly added or removed
+ * item is one row). Rows a report on main already lacked are not the pull
+ * request's, and only a built surface of the merge base tells the two apart:
+ * against the merge base's committed report, this counts none.
+ */
+function staleOwnRowCount({base, head, committed, baseSource, stale}) {
+ if (!stale || base == null || baseSource === 'committed') return 0;
+ const behind = diffReports(committed, head).keys;
+ const own = diffReports(base, head);
+ const whole = new Set([...own.added, ...own.removed].filter(r => !r.member));
+ // A member or a changed item line matches by its own key; a wholly added
+ // or removed item matches when any of its keys is behind.
+ return rowsOf(own).filter(r => {
+ const key = ROW_KEY.get(r);
+ if (behind.has(key)) return true;
+ return whole.has(r) && [...behind].some(k => k.startsWith(`${key}\0`));
+ }).length;
+}
+
/**
* @param {Array<{pkg: string, base: string|null, head: string,
* committed: string|null, baseSource?: 'build'|'head'|'committed'}>} packages
@@ -207,6 +249,13 @@ export function computeChanges(packages) {
stale,
// A stale report is one line in the PR report, not its rows.
staleRows: stale ? rowCount(diffReports(committed, head)) : 0,
+ staleOwnRows: staleOwnRowCount({
+ base,
+ head,
+ committed,
+ baseSource,
+ stale,
+ }),
missing: committed == null,
counts: {
added: d.added.length,
@@ -223,6 +272,26 @@ export function computeChanges(packages) {
.sort((x, y) => (x.pkg < y.pkg ? -1 : x.pkg > y.pkg ? 1 : 0));
}
+/**
+ * A GitHub Actions warning for each package whose public API this pull
+ * request changed while its committed report stayed behind. It never fails
+ * the job (architecture:public-component-api INV24); a report that was stale
+ * before this pull request gets only the pull request report's line.
+ * @param {ReturnType<typeof computeChanges>} changes
+ * @param {(pkg: string) => string} reportFile the package's committed report path
+ * @returns {string[]}
+ */
+export function staleReportWarnings(changes, reportFile) {
+ return changes
+ .filter(c => c.staleOwnRows > 0)
+ .map(
+ c =>
+ `::warning file=${reportFile(c.pkg)},title=API report not regenerated::` +
+ `This pull request changes ${plural(c.staleOwnRows, 'row')} of ${c.pkg}'s public API ` +
+ `that its committed api-report.md does not show. Run pnpm api:report and commit the report.`,
+ );
+}
+
// The pull request comment has a size limit; a wide change lists its first rows.
const MAX_ROWS = 150;
diff --git a/scripts/api-report/cli.mjs b/scripts/api-report/cli.mjs
index a41ce11aea..392d2fff47 100644
--- a/scripts/api-report/cli.mjs
+++ b/scripts/api-report/cli.mjs
@@ -36,12 +36,19 @@ import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
import {expandWorkspaceDirs} from '../lib/workspace-globs.mjs';
import {isStableReleasePackage} from '../release/active-release.mjs';
-import {computeChanges, renderChanges} from './changes.mjs';
+import {
+ computeChanges,
+ renderChanges,
+ staleReportWarnings,
+} from './changes.mjs';
import {generateReport} from './generate.mjs';
export const REPORT_FILE = 'api-report.md';
export const SURFACE_FILE = 'surface.json';
-/** api-changes.json's shape; 2 added `baseRecord`, `baseSource`, `staleRows`. */
+/**
+ * api-changes.json's shape. Version 2 has `baseRecord`, `baseSource`, `staleRows`
+ * and `staleOwnRows`; a reader of version 2 accepts a missing `staleOwnRows`.
+ */
export const CHANGES_VERSION = 2;
const REPO_ROOT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -312,6 +319,9 @@ async function main() {
2,
) + '\n',
);
+ const fileOf = new Map(results.map(r => [r.pkg, r.file]));
+ for (const warning of staleReportWarnings(changes, pkg => fileOf.get(pkg)))
+ console.log(warning);
const total = changes.reduce((n, c) => n + c.rows.length, 0);
const stale = changes.filter(c => c.stale || c.missing).map(c => c.pkg);
console.log(