Update release PR workflow to credit all committers (#865)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Attempts to credit everyone who contributed to a PR instead of just the
pr opener.

#### Type of change

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
7w1 authored and GitHub committed 2026-05-18 18:03:36 -05:00
commit fac87b6246
3 files changed
+246 -74

No files matched your search

-2
View File
@@ -4,8 +4,6 @@ default: minor
Change Image Viewer to feel more natural to use.
# Changes to Image viewer
- Fixed zoom gestures generally not working on mobile.
- Changed the % number in the top right to reflect the zoom of the original image as opposed to the change from it fitting the container.
- Made the zoom pill allow entering custom values.
+243
View File
@@ -0,0 +1,243 @@
#!/usr/bin/env node
/* oxlint-disable no-console */
/**
* Replaces Knope commit markers with PR links and credits every human commit author.
*
* Usage:
* GITHUB_TOKEN=... GITHUB_REPOSITORY=owner/repo node .github/scripts/enrich-changelog.mjs [options]
*
* Options:
* --file <path> Changelog to enrich (default: CHANGELOG.md)
* --dry-run Print enriched output without writing files or updating PRs
* --update-release-pr Also enrich the open release PR body and apply the internal label
*/
import fs from 'node:fs';
const BOT_USER_TYPE = 'Bot';
const COMMIT_MARKER = /<!-- commit:([0-9a-f]+) -->/g;
function parseArgs(argv) {
const opts = {
file: 'CHANGELOG.md',
dryRun: false,
updateReleasePr: false,
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--dry-run') opts.dryRun = true;
else if (arg === '--update-release-pr') opts.updateReleasePr = true;
else if (arg === '--file') opts.file = argv[++i];
else if (arg === '--help' || arg === '-h') {
console.log(`See the header comment in ${import.meta.url}`);
process.exit(0);
} else {
console.error(`Unknown argument: ${arg}`);
process.exit(1);
}
}
return opts;
}
function isBot(user) {
if (!user?.login) return true;
if (user.type === BOT_USER_TYPE) return true;
return user.login.endsWith('[bot]');
}
function parseRepository() {
const repoEnv = process.env.GITHUB_REPOSITORY;
if (!repoEnv?.includes('/')) {
throw new Error('Set GITHUB_REPOSITORY to owner/repo (e.g. SableClient/Sable).');
}
const [owner, repo] = repoEnv.split('/');
return { owner, repo };
}
function setSearchParams(url, params) {
for (const [key, value] of Object.entries(params ?? {})) {
if (value === undefined) continue;
if (typeof value === 'string' || typeof value === 'number') {
url.searchParams.set(key, String(value));
}
}
}
async function githubRequest(token, path, { params, method = 'GET', body, accept } = {}) {
const url = new URL(`https://api.github.com${path}`);
setSearchParams(url, params);
const headers = {
Authorization: `Bearer ${token}`,
Accept: accept ?? 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'sable-changelog-enrich',
};
const init = { method, headers };
if (body != null && method !== 'GET') {
headers['Content-Type'] = 'application/json';
init.body = JSON.stringify(body);
}
const response = await fetch(url, init);
if (!response.ok) {
const text = await response.text();
throw new Error(`GitHub API ${response.status} ${path}: ${text}`);
}
if (response.status === 204) return null;
return response.json();
}
async function fetchPullRequestCommitPage(token, owner, repo, pullNumber, page, commits) {
const batch = await githubRequest(token, `/repos/${owner}/${repo}/pulls/${pullNumber}/commits`, {
params: { per_page: 100, page },
});
commits.push(...batch);
if (batch.length < 100) return commits;
return fetchPullRequestCommitPage(token, owner, repo, pullNumber, page + 1, commits);
}
async function listPullRequestCommits(token, owner, repo, pullNumber) {
return fetchPullRequestCommitPage(token, owner, repo, pullNumber, 1, []);
}
async function getPullRequestContributors(token, owner, repo, pullNumber, cache) {
if (cache.has(pullNumber)) return cache.get(pullNumber);
const commits = await listPullRequestCommits(token, owner, repo, pullNumber);
const logins = new Set();
for (const commit of commits) {
const author = commit.author;
if (author?.login && !isBot(author)) {
logins.add(author.login);
}
}
const contributors = [...logins].toSorted((a, b) => a.localeCompare(b, 'en'));
cache.set(pullNumber, contributors);
return contributors;
}
function formatPullRequestCredit(pr, contributors) {
const link = `[#${pr.number}](<${pr.html_url}>)`;
if (contributors.length === 0) return `(${link})`;
const byline = contributors.map((login) => `@${login}`).join(', ');
return `(${link} by ${byline})`;
}
async function resolveCommitMarker(token, owner, repo, hash, contributorCache) {
try {
const associated = await githubRequest(token, `/repos/${owner}/${repo}/commits/${hash}/pulls`, {
accept: 'application/vnd.github.groot-preview+json',
});
const pr = associated[0];
if (!pr) return `(\`${hash}\`)`;
const contributors = await getPullRequestContributors(
token,
owner,
repo,
pr.number,
contributorCache
);
return formatPullRequestCredit(pr, contributors);
} catch {
return `(\`${hash}\`)`;
}
}
async function enrichText(token, owner, repo, text, contributorCache) {
const hashes = [...new Set([...text.matchAll(COMMIT_MARKER)].map((match) => match[1]))];
const credits = await Promise.all(
hashes.map(async (hash) => ({
hash,
credit: await resolveCommitMarker(token, owner, repo, hash, contributorCache),
}))
);
let enriched = text;
for (const { hash, credit } of credits) {
enriched = enriched.replaceAll(`<!-- commit:${hash} -->`, credit);
}
return enriched;
}
async function ensureLabel(token, owner, repo, name, color) {
try {
await githubRequest(token, `/repos/${owner}/${repo}/labels/${encodeURIComponent(name)}`);
} catch (error) {
if (!String(error.message).includes('404')) throw error;
await githubRequest(token, `/repos/${owner}/${repo}/labels`, {
method: 'POST',
body: { name, color },
});
}
}
async function updateReleasePullRequest(token, owner, repo, contributorCache, dryRun) {
const openPulls = await githubRequest(token, `/repos/${owner}/${repo}/pulls`, {
params: { head: `${owner}:release`, state: 'open' },
});
if (openPulls.length === 0) {
console.warn('No open PR found for the release branch.');
return;
}
const releasePr = openPulls[0];
const enrichedBody = await enrichText(token, owner, repo, releasePr.body ?? '', contributorCache);
if (dryRun) {
console.log('--- release PR body (dry run) ---\n');
console.log(enrichedBody);
return;
}
const label = 'internal';
await ensureLabel(token, owner, repo, label, 'e4e669');
await Promise.all([
githubRequest(token, `/repos/${owner}/${repo}/pulls/${releasePr.number}`, {
method: 'PATCH',
body: { body: enrichedBody },
}),
githubRequest(token, `/repos/${owner}/${repo}/issues/${releasePr.number}/labels`, {
method: 'POST',
body: { labels: [label] },
}),
]);
}
async function main() {
const opts = parseArgs(process.argv.slice(2));
const token = process.env.GITHUB_TOKEN;
if (!token) {
throw new Error(
'Set GITHUB_TOKEN to a token with repo read access (and write for --update-release-pr).'
);
}
const { owner, repo } = parseRepository();
const contributorCache = new Map();
if (!fs.existsSync(opts.file)) {
console.warn(`Changelog file not found: ${opts.file}`);
} else {
const original = fs.readFileSync(opts.file, 'utf8');
const enriched = await enrichText(token, owner, repo, original, contributorCache);
if (opts.dryRun) {
console.log(enriched);
} else {
fs.writeFileSync(opts.file, enriched);
}
}
if (opts.updateReleasePr) {
await updateReleasePullRequest(token, owner, repo, contributorCache, opts.dryRun);
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
+3 -72
View File
@@ -39,78 +39,9 @@ jobs:
GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }}
- name: Enrich changelog and update release PR
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
github-token: ${{ steps.generate-token.outputs.token }}
script: |
const fs = require("fs");
const { owner, repo } = context.repo;
async function resolveHash(hash) {
try {
const prs = await github.rest.repos.listPullRequestsAssociatedWithCommit({
owner, repo, commit_sha: hash,
});
const pr = prs.data[0];
return pr
? `([#${pr.number}](<${pr.html_url}>) by @${pr.user.login})`
: `(\`${hash}\`)`;
} catch {
return `(\`${hash}\`)`;
}
}
async function enrichText(text) {
const marker = /<!-- commit:([0-9a-f]+) -->/g;
const hashes = [...new Set([...text.matchAll(marker)].map(m => m[1]))];
for (const hash of hashes) {
text = text.replaceAll(`<!-- commit:${hash} -->`, await resolveHash(hash));
}
return text;
}
const changelog = "CHANGELOG.md";
if (fs.existsSync(changelog)) {
const enriched = await enrichText(fs.readFileSync(changelog, "utf8"));
fs.writeFileSync(changelog, enriched);
}
const prs = await github.rest.pulls.list({
owner, repo,
head: `${owner}:release`,
state: "open",
});
if (prs.data.length === 0) {
core.warning("No open PR found for the release branch.");
return;
}
const pr = prs.data[0];
const label = "internal";
try {
await github.rest.issues.getLabel({ owner, repo, name: label });
} catch (e) {
if (e.status === 404) {
await github.rest.issues.createLabel({ owner, repo, name: label, color: "e4e669" });
} else {
throw e;
}
}
await Promise.all([
github.rest.pulls.update({
owner, repo,
pull_number: pr.number,
body: await enrichText(pr.body ?? ""),
}),
github.rest.issues.addLabels({
owner, repo,
issue_number: pr.number,
labels: [label],
}),
]);
env:
GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }}
run: node .github/scripts/enrich-changelog.mjs --update-release-pr
- name: Amend release commit with enriched changelog
shell: bash