Skip to content

Commit 9946def

Browse files
cknittclaude
andauthored
Derive changelog PR links from the squash commit (#8888)
* Derive changelog PR links from the squash commit Fragments no longer need a PR link, so new PRs don't need the placeholder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NP47qMfjMbjUTKZDsLthDo Signed-off-by: Christoph Knittel <ck@cca.io> * Preview merged fragments with their derived links Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NP47qMfjMbjUTKZDsLthDo Signed-off-by: Christoph Knittel <ck@cca.io> --------- Signed-off-by: Christoph Knittel <ck@cca.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2ac9971 commit 9946def

5 files changed

Lines changed: 211 additions & 15 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ on `master`. CI runs on every PR in the stack.
100100

101101
## Testing and changelog
102102

103-
**Add a changelog fragment** `changes/<description>.<category>.md` for any user-facing change (bug fix, feature, or breaking change) instead of editing `CHANGELOG.md`; see [changes/README.md](changes/README.md) for categories and format. Validate with `yarn changelog:check`. Since the PR number is not known yet, open the PR as a draft with the placeholder link `https://github.com/rescript-lang/rescript/pull/XXXX`, then replace it with the real link, amend, push again, and mark the PR ready for review (`gh pr ready`).
103+
**Add a changelog fragment** `changes/<description>.<category>.md` for any user-facing change (bug fix, feature, or breaking change) instead of editing `CHANGELOG.md`; see [changes/README.md](changes/README.md) for categories and format. Validate with `yarn changelog:check`. Fragments need no PR link: the release adds it from the squash commit that merged the fragment.
104104

105105
For compiler or standard-library changes, run `make test`. For syntax changes,
106106
also run `make test-syntax`; use `make test-syntax-roundtrip` when parsing or

‎changes/README.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
Add a unique `<description>.<category>.md` file for each change that needs release notes. For example, `fix-watcher-recovery.fix.md`:
44

55
```markdown
6-
- Recover blocked dependents after a failed build. https://github.com/rescript-lang/rescript/pull/8667
6+
- Recover blocked dependents after a failed build.
77
```
88

9-
The PR number is only known once the PR exists, so open it as a draft with the placeholder link `https://github.com/rescript-lang/rescript/pull/XXXX`, replace the placeholder with the real link, amend and push again, then mark the PR ready for review. The changelog check fails while the placeholder remains. Each file may contain multiple bullets in the same category. Indent wrapped lines by two spaces; each bullet ends with one or more PR links.
9+
Each file may contain multiple bullets in the same category. Indent wrapped lines by two spaces.
10+
11+
A bullet needs no PR link: `yarn changelog:release` appends the link of the pull request that added the fragment, taken from the subject of its squash commit (`... (#8667)`). Pull requests are therefore squash-merged, keeping the `(#N)` GitHub adds to the title. A bullet may still end with explicit PR links, for example for a change spanning several pull requests, and those are kept as written. After each push to `master`, the changelog check fails if a fragment without a link cannot be traced to its pull request; add the link to that fragment.
1012

1113
| Category | Section |
1214
| --- | --- |
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Fragments no longer need a PR link; the release adds it from the squash commit that merged the fragment.

‎scripts/changelog.js‎

Lines changed: 85 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export const placeholderLink =
1919
const trailingPrLinks = new RegExp(
2020
`${prLink.source}(?:\\s+${prLink.source})*$`,
2121
);
22+
const repositoryUrl = "https://github.com/rescript-lang/rescript";
2223

2324
export function parseFragment(name, content) {
2425
const match = /^([a-z0-9][a-z0-9-]*)\.([a-z]+)\.md$/.exec(name);
@@ -37,21 +38,74 @@ export function parseFragment(name, content) {
3738
const invalid = bullets.some(
3839
bullet =>
3940
!/^- \S/.test(bullet) ||
40-
!trailingPrLinks.test(bullet) ||
4141
bullet
4242
.split("\n")
4343
.slice(1)
4444
.some(line => line && !/^ {2}\S/.test(line)),
4545
);
4646
if (!text || invalid) {
4747
throw new Error(
48-
`${name}: expected Markdown bullets ending with PR links (indent continuation lines by two spaces)`,
48+
`${name}: expected Markdown bullets (indent continuation lines by two spaces)`,
4949
);
5050
}
51-
const pr = Math.max(
52-
...[...text.matchAll(new RegExp(prLink, "g"))].map(link => Number(link[1])),
51+
const links = [...text.matchAll(new RegExp(prLink, "g"))].map(link =>
52+
Number(link[1]),
5353
);
54-
return { name, category: match[2], text, pr };
54+
// A bullet without a link gets the link of the pull request that added the
55+
// fragment when the release is prepared.
56+
const unlinked = bullets.some(bullet => !trailingPrLinks.test(bullet));
57+
const pr = links.length ? Math.max(...links) : null;
58+
return { name, category: match[2], text, pr, unlinked };
59+
}
60+
61+
// The pull request that added a fragment, from the subject of the squash
62+
// commit that added it ("... (#1234)"). Rebase merges and merge commits carry
63+
// no such subject, which is why pull requests are squash-merged.
64+
export function addedByPullRequest(root, name) {
65+
const subjects = execFileSync(
66+
"git",
67+
["log", "--diff-filter=A", "--format=%s", "--", `changes/${name}`],
68+
{ cwd: root, encoding: "utf8" },
69+
)
70+
.split("\n")
71+
.filter(Boolean);
72+
// The most recent addition, in case an earlier fragment had the same name.
73+
const match = /\(#([1-9]\d*)\)\s*$/.exec(subjects[0] ?? "");
74+
return match ? Number(match[1]) : null;
75+
}
76+
77+
// Appends the link of the pull request that added the fragment to each bullet
78+
// without one.
79+
export function linkFragment(fragment, pullRequestOf) {
80+
if (!fragment.unlinked) return fragment;
81+
const pr = pullRequestOf(fragment.name);
82+
if (!pr) {
83+
throw new Error(
84+
`changes/${fragment.name}: no PR link, and the commit that added it does not name its pull request; add the link to the fragment`,
85+
);
86+
}
87+
const text = fragment.text
88+
.split(/\n(?=- )/)
89+
.map(bullet =>
90+
trailingPrLinks.test(bullet)
91+
? bullet
92+
: `${bullet} ${repositoryUrl}/pull/${pr}`,
93+
)
94+
.join("\n");
95+
return {
96+
...fragment,
97+
text,
98+
pr: Math.max(pr, fragment.pr ?? 0),
99+
unlinked: false,
100+
};
101+
}
102+
103+
// What the release will write for a fragment: linked once its pull request is
104+
// merged, and as written before that.
105+
export function previewFragment(fragment, pullRequestOf) {
106+
if (!fragment.unlinked) return fragment;
107+
const pr = pullRequestOf(fragment.name);
108+
return pr ? linkFragment(fragment, () => pr) : fragment;
55109
}
56110

57111
export async function readFragments(root) {
@@ -76,12 +130,17 @@ export async function readFragments(root) {
76130
return fragments;
77131
}
78132

79-
// Newest PR first, matching the order of existing CHANGELOG.md entries.
133+
// Newest PR first, matching the order of existing CHANGELOG.md entries. A
134+
// fragment without a link yet belongs to an unmerged pull request, so it comes
135+
// first.
80136
function categoryNotes(fragments, category) {
137+
const order = fragment => fragment.pr ?? Number.POSITIVE_INFINITY;
81138
return fragments
82139
.filter(fragment => fragment.category === category)
83140
.sort(
84-
(a, b) => b.pr - a.pr || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
141+
(a, b) =>
142+
Math.sign(order(b) - order(a) || 0) ||
143+
(a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
85144
)
86145
.map(fragment => fragment.text);
87146
}
@@ -217,7 +276,11 @@ export function checkPullRequest(files, pullRequest) {
217276
}
218277
}
219278

220-
export async function run(command, root = process.cwd()) {
279+
export async function run(
280+
command,
281+
root = process.cwd(),
282+
pullRequestOf = name => addedByPullRequest(root, name),
283+
) {
221284
if (!["check", "preview", "release", "open"].includes(command)) {
222285
throw new Error(
223286
"Usage: node scripts/changelog.js check|preview|release|open",
@@ -245,11 +308,19 @@ export async function run(command, root = process.cwd()) {
245308
files.push({ status: diff[i], name: diff[i + 1] });
246309
}
247310
checkPullRequest(files, pullRequest);
311+
} else if (process.env.GITHUB_EVENT_NAME === "push") {
312+
// Once merged, every fragment must resolve to its pull request, so a
313+
// merge without "(#N)" in its subject fails here rather than at release.
314+
for (const fragment of fragments) linkFragment(fragment, pullRequestOf);
248315
}
249316
return;
250317
}
251318
if (command === "preview") {
252-
process.stdout.write(renderFragments(fragments));
319+
process.stdout.write(
320+
renderFragments(
321+
fragments.map(fragment => previewFragment(fragment, pullRequestOf)),
322+
),
323+
);
253324
return;
254325
}
255326
const { version, repository } = JSON.parse(
@@ -261,13 +332,16 @@ export async function run(command, root = process.cwd()) {
261332
await fs.writeFile(target, openSection(changelog, version));
262333
return;
263334
}
335+
const linked = fragments.map(fragment =>
336+
linkFragment(fragment, pullRequestOf),
337+
);
264338
const tagged =
265-
fragments.length > 0 &&
339+
linked.length > 0 &&
266340
isFinalized(changelog, version) &&
267341
releaseTagExists(repository.url, version);
268342
await fs.writeFile(
269343
target,
270-
prepareRelease(changelog, version, fragments, { tagged }),
344+
prepareRelease(changelog, version, linked, { tagged }),
271345
);
272346
for (const fragment of fragments) {
273347
await fs.unlink(path.join(root, "changes", fragment.name));

‎scripts/changelog.test.js‎

Lines changed: 120 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
import assert from "node:assert/strict";
2+
import { execFileSync } from "node:child_process";
23
import fs from "node:fs/promises";
34
import os from "node:os";
45
import path from "node:path";
56
import test from "node:test";
67
import {
8+
addedByPullRequest,
79
categories,
810
checkPullRequest,
11+
linkFragment,
912
openSection,
1013
parseFragment,
1114
placeholderLink,
1215
prepareRelease,
16+
previewFragment,
1317
readFragments,
1418
renderFragments,
1519
run,
@@ -26,8 +30,8 @@ test("validates category names and bullet content", () => {
2630
["recovery.bugfix.md", note],
2731
["recovery.md", note],
2832
["recovery.fix.md", ""],
29-
["recovery.fix.md", "- Missing link"],
3033
["recovery.fix.md", `Heading\n${note}`],
34+
["recovery.fix.md", "- Bad\ncontinuation"],
3135
]) {
3236
assert.throws(() => parseFragment(name, content));
3337
}
@@ -217,6 +221,121 @@ test("validates before mutation, sorts fragments, consumes only on release", asy
217221
await assert.rejects(run("release", root));
218222
});
219223

224+
test("links bullets without a link to the pull request that added them", () => {
225+
const fragment = parseFragment(
226+
"recovery.fix.md",
227+
"- Fix recovery\n after errors.\n- Fix formatting. https://github.com/rescript-lang/rescript/pull/7",
228+
);
229+
assert.equal(fragment.unlinked, true);
230+
assert.equal(fragment.pr, 7);
231+
const linked = linkFragment(fragment, () => 42);
232+
assert.equal(
233+
linked.text,
234+
"- Fix recovery\n after errors. https://github.com/rescript-lang/rescript/pull/42\n- Fix formatting. https://github.com/rescript-lang/rescript/pull/7",
235+
);
236+
assert.equal(linked.pr, 42);
237+
const plain = parseFragment("plain.fix.md", "- Fix recovery.");
238+
assert.equal(plain.pr, null);
239+
assert.equal(
240+
linkFragment(parseFragment("linked.fix.md", note), () => {
241+
throw new Error("not looked up");
242+
}).text,
243+
note,
244+
);
245+
assert.throws(
246+
() => linkFragment(plain, () => null),
247+
/changes\/plain\.fix\.md: no PR link/,
248+
);
249+
});
250+
251+
test("previews merged fragments with their links, newest PR first", () => {
252+
const numbers = { "a.fix.md": 10, "b.fix.md": 30, "c.fix.md": null };
253+
const fragments = [
254+
parseFragment("a.fix.md", "- Older."),
255+
parseFragment("b.fix.md", "- Newer."),
256+
parseFragment("c.fix.md", "- Not merged yet."),
257+
parseFragment(
258+
"d.fix.md",
259+
"- Linked. https://github.com/rescript-lang/rescript/pull/20",
260+
),
261+
].map(fragment => previewFragment(fragment, name => numbers[name]));
262+
assert.ok(
263+
renderFragments(fragments).includes(
264+
[
265+
"- Not merged yet.",
266+
"- Newer. https://github.com/rescript-lang/rescript/pull/30",
267+
"- Linked. https://github.com/rescript-lang/rescript/pull/20",
268+
"- Older. https://github.com/rescript-lang/rescript/pull/10",
269+
].join("\n"),
270+
),
271+
);
272+
});
273+
274+
test("releases fragments without a link with their pull request's link", async t => {
275+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "rescript-changelog-"));
276+
t.after(() => fs.rm(root, { recursive: true, force: true }));
277+
await fs.mkdir(path.join(root, "changes"));
278+
await fs.writeFile(
279+
path.join(root, "package.json"),
280+
JSON.stringify({ version: "13.0.0" }),
281+
);
282+
await fs.writeFile(path.join(root, "CHANGELOG.md"), changelog);
283+
await fs.writeFile(path.join(root, "changes", "old.fix.md"), note);
284+
await fs.writeFile(path.join(root, "changes", "new.fix.md"), "- New fix.");
285+
await fs.writeFile(path.join(root, "changes", "lost.fix.md"), "- Lost.");
286+
const numbers = { "new.fix.md": 9000, "lost.fix.md": null };
287+
await assert.rejects(
288+
run("release", root, name => numbers[name]),
289+
/changes\/lost\.fix\.md/,
290+
);
291+
assert.equal(
292+
await fs.readFile(path.join(root, "CHANGELOG.md"), "utf8"),
293+
changelog,
294+
);
295+
await fs.unlink(path.join(root, "changes", "lost.fix.md"));
296+
await run("release", root, name => numbers[name]);
297+
assert.ok(
298+
(await fs.readFile(path.join(root, "CHANGELOG.md"), "utf8")).includes(
299+
`${categories.fix}\n\n- New fix. https://github.com/rescript-lang/rescript/pull/9000\n${note}\n`,
300+
),
301+
);
302+
});
303+
304+
test("finds the pull request in the subject of the commit that added a fragment", async t => {
305+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "rescript-changelog-"));
306+
t.after(() => fs.rm(root, { recursive: true, force: true }));
307+
const git = (...args) =>
308+
execFileSync("git", args, {
309+
cwd: root,
310+
env: {
311+
...process.env,
312+
GIT_AUTHOR_NAME: "a",
313+
GIT_AUTHOR_EMAIL: "a@example.com",
314+
GIT_COMMITTER_NAME: "a",
315+
GIT_COMMITTER_EMAIL: "a@example.com",
316+
},
317+
});
318+
git("init", "-q");
319+
await fs.mkdir(path.join(root, "changes"));
320+
const commit = async (name, subject) => {
321+
await fs.writeFile(path.join(root, "changes", name), "- Note.");
322+
git("add", ".");
323+
git("commit", "-q", "-m", subject);
324+
};
325+
await commit("squashed.fix.md", "Fix recovery (#123)");
326+
await commit("rebased.fix.md", "Fix formatting");
327+
assert.equal(addedByPullRequest(root, "squashed.fix.md"), 123);
328+
assert.equal(addedByPullRequest(root, "rebased.fix.md"), null);
329+
assert.equal(addedByPullRequest(root, "missing.fix.md"), null);
330+
// A later edit by another pull request does not change who added it.
331+
await fs.writeFile(
332+
path.join(root, "changes", "squashed.fix.md"),
333+
"- Edited.",
334+
);
335+
git("commit", "-q", "-am", "Reword (#456)");
336+
assert.equal(addedByPullRequest(root, "squashed.fix.md"), 123);
337+
});
338+
220339
test("preview groups categories without consuming fragments", () => {
221340
const fragments = [parseFragment("recovery.fix.md", note)];
222341
const preview = renderFragments(fragments);

0 commit comments

Comments
 (0)