Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 20 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,26 @@

<!-- What changes and why. Link the issue: Fixes #n / Refs #n -->

## Whole-change check

<!--
Needed when the pull request changes docs or code; CI checks for it. Write your answers below this comment.

Docs: each page you touched, read whole and rendered.
- Its reader, and the task they come with.
- Does the reader find what to do in 30 seconds? Is the order by importance? Is every paragraph worth their time?
- How you reshaped it: detail moved to a sub-page and linked, shortened with the full version elsewhere,
a list or table instead of prose, a section moved where it belongs.
- What you removed or moved, item by item, and where it went.

Code: each function or file you touched, read whole.
- Its job now. One job each; a second job is a split.
- What you extracted or reused.
- Why the rest fits as it is.

A growth guard that fails: the entry, and why the growth is right.
-->

## Checklist

- [ ] Linked issue
Expand Down
46 changes: 46 additions & 0 deletions .github/workflows/whole-change-check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: Whole-change check

# A pull request that changes docs or code says in its description what its author read whole and how
# the change reshaped it (build/whole-change-check.js says what counts and who is exempt). It runs
# again when the description is edited, so fixing the description turns it green; a workflow of its
# own, so an edit does not run all of CI again.
#
# The description, title and author reach the script only through env: whoever opens the pull request
# writes them, and an expression inside `run` would become part of the shell script.
on:
# pull requests to main, as ci.yml
pull_request:
branches: ["main"]
types: [opened, synchronize, reopened, edited]

permissions:
contents: read

concurrency:
group: whole-change-check-${{ github.ref }}
cancel-in-progress: true

jobs:
check:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# the merge commit and its first parent, the base: their difference is what the pull request changes
fetch-depth: 2
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "22"
- name: Whole-change check
env:
PR_BODY: ${{ github.event.pull_request.body }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
# quotepath off: a path with non-ASCII letters as it is, not quoted and escaped. No renames:
# a file moved out of scope counts by its old path too
CHANGED_FILES="$(git -c core.quotepath=off diff --no-renames --name-only HEAD^1 HEAD)"
export CHANGED_FILES
node build/whole-change-check.js
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ The limits and their reasons are in that file. Each guard is a CI step:
- `docs`: lines per docs page and README by kind of page, and of all of them together.

The offenders over a limit are in `build/growth-baseline.json`. A new or grown one fails. A smaller one
fails until `node build/growth.js --update` lowers the baseline in the same pull request.
fails until `node build/growth.js --update` lowers the baseline in the same pull request. A raised
baseline needs its reason in the pull request's whole-change check.

A change to a component is checked on a PSU test instance in a browser (light and dark theme, a
narrow and a wide window, the events it fires) before it is called done; unit tests do not cover
Expand Down
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ Thanks for helping.
4. Update the pages in `docs/` and add an entry under `[Unreleased]` in the `CHANGELOG.md` of each
module you changed.
5. Open a pull request. Use Conventional Commits with the module as scope: `fix(pivot): ...`.
A change to docs or code fills in the template's whole-change check: what you read whole, and how
you reshaped it instead of appending. CI fails without it; editing the description runs it again.

## Check your change

Expand Down
19 changes: 13 additions & 6 deletions build/growth.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
// build/growth-baseline.json with their numbers. A check fails when an offender grows or a new one
// appears. It also fails when an offender shrank or went: the baseline must follow in the same pull
// request (--update), or the room it left could be filled again unseen. --update never raises an
// entry by itself. Raising one is --accept-growth, and the pull request says why.
// entry by itself. Raising one is --accept-growth, and the pull request's whole-change check says
// why (.github/PULL_REQUEST_TEMPLATE.md).
// eizedev/pivotkit has the same guards in scripts/growth.js; both work alike.
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
Expand Down Expand Up @@ -57,16 +58,22 @@ export const DOCS_LIMITS = Object.freeze({ overview: 150, topic: 200, reference:
/** How far the lines of all pages together may drift from the baseline, in percent, before it is updated. */
export const DOCS_TOTAL_MARGIN = 2;

/**
* What to do when a function or a page grew. A number cannot judge sense: the guard is an alarm to
* look at the whole, and squeezing lines or cutting words to pass it makes the code or page worse.
*/
const STOP = `Stop and read the whole of it; write what you found in the pull request's whole-change check (.github/PULL_REQUEST_TEMPLATE.md, "Whole-change check").`;

/** What to do when a guard fails, said once per guard. */
const ADVICE = {
powershell: `Split the function into smaller ones, one job each, and the file into one file per function (AGENTS.md, "Small units"). Limits: ${POWERSHELL_LIMITS.function} code lines per function, ${POWERSHELL_LIMITS.file} per file; blank lines and comments do not count.`,
javascript: `Split the function into smaller ones, one job each (AGENTS.md, "Small units"). Limits: ${FUNCTION_LIMITS.lines} lines without blank lines and comments, complexity ${FUNCTION_LIMITS.complexity}.`,
powershell: `The function or file grew. ${STOP} Then reshape it for real: extract the jobs it does beside its own, one function per file (AGENTS.md, "Small units"). Limits: ${POWERSHELL_LIMITS.function} code lines per function, ${POWERSHELL_LIMITS.file} per file; blank lines and comments do not count.`,
javascript: `The function grew. ${STOP} Then reshape it for real: extract the jobs it does beside its own (AGENTS.md, "Small units"). Limits: ${FUNCTION_LIMITS.lines} lines without blank lines and comments, complexity ${FUNCTION_LIMITS.complexity}.`,
duplication: "Move the copied code into one function or module that both places import (AGENTS.md, \"One place per fact\"; shared/js once a second module needs it). The threshold is in .jscpd.json.",
docs: "Shorten the page, or split it into pages with one topic each; rewrite instead of appending (AGENTS.md, \"Shape what exists\"). When all pages together grew, make room in the pages the change touches.",
docs: `The page grew. ${STOP} Then reshape it for real: move detail to a sub-page and link it, write a list or a table instead of prose, or move a section to the page that owns its topic (AGENTS.md, "Shape what exists"). When all pages together grew, make room in the pages the change touches.`,
};

/** The way out when the growth is right, said under every guard that grew. */
const ACCEPT = `If the growth is right, raise the baseline with ${UPDATE} --accept-growth and say why in the pull request.`;
const ACCEPT = `Or raise the baseline with ${UPDATE} --accept-growth, with the reason in the whole-change check and the maintainer's approval. Never merge lines or cut words only to pass the number.`;

const posix = (path, base = root) => relative(base, path).split(sep).join("/");

Expand Down Expand Up @@ -320,7 +327,7 @@ export async function main(argv, { dir = root, baselineFile = fileURLToPath(BASE
writeFileSync(baselineFile, formatBaseline(next));
console.log(`wrote ${posix(baselineFile)}`);
} else if (update) {
console.error(`\nThe baseline was not written: something grew. Fix that, or raise the baseline with ${UPDATE} --accept-growth and say why in the pull request.`);
console.error(`\nThe baseline was not written: something grew. Reshape it, or raise the baseline with ${UPDATE} --accept-growth and give the reason in the pull request's whole-change check.`);
}
process.exitCode = failed ? 1 : 0;
}
Expand Down
93 changes: 93 additions & 0 deletions build/whole-change-check.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Whole-change check: a pull request that changes docs or code has a "## Whole-change check" section
// with text in its description. There its author says what they read whole and how the change
// reshaped it instead of appending (.github/PULL_REQUEST_TEMPLATE.md). The growth guards (growth.js)
// count lines; a number cannot judge sense, so this asks for the judgement, and the review judges it.
//
// .github/workflows/whole-change-check.yml runs it on every pull request, also when the description
// is edited. It reads everything from environment variables, never from the command line, because
// the description and title are written by whoever opens the pull request:
//
// PR_BODY, PR_TITLE, PR_AUTHOR the description, the title and the author's login
// CHANGED_FILES the changed paths, one per line
//
// Exempt are Dependabot's pull requests and release pull requests (docs/development/release.md),
// known by their title: "chore(release): ... x.y.z" or "chore(<scope>): release ... x.y.z", the scope
// optional. The title is the author's word; the review sees it.
import { fileURLToPath } from "node:url";

/** The heading the description needs, without its "## ". */
export const HEADING = "Whole-change check";

/**
* The paths whose change needs the check: Markdown of the docs site, READMEs and the root, and code:
* a module's components, functions, .psm1 (some modules keep their functions there) and showcase
* apps, shared/ and build/.
*/
const SCOPE = [/^docs\/.*\.md$/, /(^|\/)README\.md$/, /^[^/]+\.md$/, /^modules\/[^/]+\/(Components|Public|Private|Apps)\//, /^modules\/[^/]+\/[^/]+\.psm1$/, /^shared\//, /^build\//];

/**
* The changed paths that need the check.
* @param {string[]} files
*/
export const inScope = (files) => files.filter((file) => SCOPE.some((re) => re.test(file)));

/**
* The text of the description's whole-change check, without HTML comments (the template's prompts),
* up to the next heading of level 1 or 2; null when the description has no such heading.
* @param {string | null | undefined} body
*/
export function sectionText(body) {
// an unclosed comment hides the rest of the description, on GitHub as here
const lines = String(body ?? "").replace(/<!--[\s\S]*?(?:-->|$)/g, "").split(/\r?\n/);
// the level of each heading line, 0 for other lines; a "#" inside a code fence is no heading
let fenced = false;
const levels = lines.map((line) => {
if (/^ {0,3}(?:```|~~~)/.test(line)) fenced = !fenced;
return fenced ? 0 : (/^ {0,3}(#{1,6})\s/.exec(line)?.[1].length ?? 0);
});
const start = lines.findIndex((line, i) => levels[i] === 2 && /^ {0,3}##\s+whole-change check\s*#*\s*$/i.test(line));
if (start === -1) return null;
const end = levels.findIndex((level, i) => i > start && level > 0 && level <= 2);
return lines.slice(start + 1, end === -1 ? undefined : end).join("\n").trim();
}

/**
* Why a pull request needs no whole-change check whatever it changes, or null.
* @param {{ author?: string, title?: string }} pr
*/
export function exemption({ author = "", title = "" }) {
if (author === "dependabot[bot]") return "a Dependabot pull request";
if (/^chore(?:\(release\)!?:|(?:\([^)]*\))?!?:\s*release\b).*\s\d+\.\d+\.\d+$/i.test(title)) return "a release pull request";
return null;
}

/**
* The verdict on a pull request, with the text to print.
* @param {{ body?: string | null, title?: string, author?: string, files: string[] }} pr
* @returns {{ ok: boolean, message: string }}
*/
export function check({ body, title, author, files }) {
const exempt = exemption({ author, title });
if (exempt) return { ok: true, message: `Whole-change check: not needed for ${exempt}.` };
const touched = inScope(files);
if (touched.length === 0) return { ok: true, message: "Whole-change check: not needed, no docs or code changed." };
if (/[\p{L}\p{N}]/u.test(sectionText(body) ?? "")) return { ok: true, message: "Whole-change check: found in the description." };
const shown = touched.slice(0, 10).join("\n ") + (touched.length > 10 ? `\n and ${touched.length - 10} more` : "");
return {
ok: false,
message: [
`This pull request changes docs or code:\n ${shown}`,
`Its description needs a "## ${HEADING}" section with text: what you read whole, and how you`,
"reshaped it instead of appending. The prompts are in .github/PULL_REQUEST_TEMPLATE.md.",
"Edit the description; the check runs again.",
].join("\n"),
};
}

if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
const { PR_BODY, PR_TITLE, PR_AUTHOR, CHANGED_FILES = "" } = process.env;
const files = CHANGED_FILES.split("\n").map((line) => line.trim()).filter(Boolean);
const { ok, message } = check({ body: PR_BODY, title: PR_TITLE, author: PR_AUTHOR, files });
(ok ? console.log : console.error)(message);
process.exitCode = ok ? 0 : 1;
}
29 changes: 29 additions & 0 deletions tests/js/ci.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,32 @@ test("the docs workflow checks the README links against the built site, after bu
const upload = steps.findIndex((step) => String(step.uses ?? "").startsWith("actions/upload-pages-artifact@"));
assert.ok(check < upload, "docs.yml uploads the site before checking the README links");
});

// The whole-change check (build/whole-change-check.js) runs again when the description is edited,
// reads only, and gets the description, title and author through env: an expression in a `run` would
// put text whoever opens the pull request wrote into the shell script
test("the whole-change check runs on every pull request event that can fix it, reads only, and takes the pull request only through env", () => {
const check = workflow("whole-change-check.yml");
assert.deepEqual(Object.keys(check.on), ["pull_request"], "the check runs on another event than pull_request (pull_request_target would hold a write token)");
assert.deepEqual([...check.on.pull_request.types].sort(), ["edited", "opened", "reopened", "synchronize"]);
assert.equal(check.on.pull_request.paths ?? check.on.pull_request["paths-ignore"], undefined, "the script decides what needs the check");
assert.deepEqual(check.on.pull_request.branches, workflow("ci.yml").on.pull_request.branches, "the check runs for other base branches than ci.yml");
assert.deepEqual(check.permissions, { contents: "read" });
assert.notEqual(check.concurrency.group, workflow("ci.yml").concurrency.group, "an edit of the description cancels CI");
const steps = Object.values(check.jobs).flatMap((job) => {
assert.equal(job.permissions, undefined, "a job of the check asks for more permissions");
return job.steps;
});
for (const step of steps) assert.doesNotMatch(String(step.run ?? ""), /\$\{\{/, `"${step.name ?? step.uses}" has an expression in its run`);
const run = steps.find((step) => commandsOf(step).includes("node build/whole-change-check.js"));
assert.ok(run, "no step runs build/whole-change-check.js");
assert.deepEqual(run.env, {
PR_BODY: "${{ github.event.pull_request.body }}",
PR_TITLE: "${{ github.event.pull_request.title }}",
PR_AUTHOR: "${{ github.event.pull_request.user.login }}",
});
assert.ok(commandsOf(run).some((line) => /^CHANGED_FILES="\$\(git -c core\.quotepath=off diff --no-renames --name-only HEAD\^1 HEAD\)"$/.test(line)), "the changed files are not the merge commit's difference to its base");
const checkout = steps.find((step) => String(step.uses).startsWith("actions/checkout@"));
assert.equal(checkout.with["persist-credentials"], false);
assert.equal(checkout.with["fetch-depth"], 2, "without the merge commit's parent there is nothing to compare with");
});
6 changes: 4 additions & 2 deletions tests/js/growth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,10 @@ test("the command fails on growth and on a stale baseline, and --update writes o
let run = await runDocsGuard(dir);
assert.equal(run.exitCode, 1);
assert.ok(run.output.includes(`docs: grew\n docs/page.md: ${DOCS_LIMITS.topic + 10} lines, new`), run.output);
assert.match(run.output, /Shorten the page/);
assert.match(run.output, /--accept-growth and say why/);
assert.match(run.output, /The page grew\. Stop and read the whole of it/);
assert.match(run.output, /PULL_REQUEST_TEMPLATE\.md, "Whole-change check"/);
assert.match(run.output, /--accept-growth, with the reason in the whole-change check/);
assert.match(run.output, /Never merge lines or cut words only to pass the number/);
run = await runDocsGuard(dir, "--update");
assert.equal(run.exitCode, 1, "--update alone never raises the baseline");
run = await runDocsGuard(dir, "--update", "--accept-growth");
Expand Down
Loading
Loading