mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 09:47:56 -05:00
A local semantic-release plugin, after the release notes generator, looks up the pull request each squash-merged commit names, 100 per GraphQL request, and appends a Contributors section: every human author by @handle, alphabetically, with the ones whose first merged pull request is in the release called out above the list. It reaches CHANGELOG.md, the release commit and the GitHub Release alike. A GitHub API failure leaves the section out instead of failing the release. CI runs its Node tests with the other release script tests.
159 lines
6.6 KiB
JavaScript
159 lines
6.6 KiB
JavaScript
// semantic-release plugin: appends a Contributors section to the release notes.
|
|
//
|
|
// Each squash-merged commit on main ends its subject with the pull request number, "(#1234)".
|
|
// The plugin looks those pull requests up on GitHub, 100 per GraphQL request, and lists
|
|
// their human authors by @handle, alphabetically. Authors whose first merged pull request
|
|
// is in this release are called out above the list. Bots and deleted accounts are left out.
|
|
//
|
|
// It runs after @semantic-release/release-notes-generator, so the section reaches
|
|
// CHANGELOG.md, the release commit and the GitHub Release alike. A GitHub API failure is
|
|
// logged and leaves the section out rather than failing the release.
|
|
|
|
const GRAPHQL_URL = 'https://api.github.com/graphql';
|
|
const PULL_REQUESTS_PER_QUERY = 100;
|
|
const SEARCHES_PER_QUERY = 20;
|
|
|
|
/** The pull request numbers the commits name, from a "(#N)" subject suffix or a merge commit. */
|
|
export function pullRequestNumbers(commits) {
|
|
const numbers = new Set();
|
|
for (const commit of commits) {
|
|
const subject = (commit.subject ?? commit.message ?? '').split('\n')[0];
|
|
const match = subject.match(/\(#(\d+)\)\s*$/) ?? subject.match(/^Merge pull request #(\d+)/);
|
|
if (match) {
|
|
numbers.add(Number(match[1]));
|
|
}
|
|
}
|
|
return [...numbers].sort((a, b) => a - b);
|
|
}
|
|
|
|
/** True for an author the list leaves out: a bot, or an account GitHub no longer has. */
|
|
export function isExcluded(author) {
|
|
return !author || author.__typename === 'Bot' || author.login.endsWith('[bot]');
|
|
}
|
|
|
|
/**
|
|
* The section for {@code contributions} (one {login, number, mergedAt} per pull request), naming
|
|
* as new each login in {@code newcomers}. Empty when there is no one to thank.
|
|
*/
|
|
export function formatSection(contributions, newcomers) {
|
|
const logins = [...new Set(contributions.map((c) => c.login))]
|
|
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
|
|
if (logins.length === 0) {
|
|
return '';
|
|
}
|
|
const lines = ['### Contributors', ''];
|
|
const firsts = logins.filter((login) => newcomers.has(login)).map((login) => {
|
|
const first = contributions
|
|
.filter((c) => c.login === login)
|
|
.sort((a, b) => (a.mergedAt ?? '').localeCompare(b.mergedAt ?? '') || a.number - b.number)[0];
|
|
return `* @${login} made their first contribution in #${first.number}`;
|
|
});
|
|
if (firsts.length > 0) {
|
|
lines.push('**New contributors**', ...firsts, '');
|
|
}
|
|
lines.push('Thanks to everyone who contributed to this release:');
|
|
lines.push(logins.map((login) => `@${login}`).join(', '));
|
|
return lines.join('\n');
|
|
}
|
|
|
|
async function graphql(query, token, fetchImpl) {
|
|
const response = await fetchImpl(GRAPHQL_URL, {
|
|
method: 'POST',
|
|
headers: { Authorization: `bearer ${token}`, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ query }),
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(`GitHub GraphQL answered ${response.status}`);
|
|
}
|
|
const body = await response.json();
|
|
if (body.errors?.length) {
|
|
throw new Error(`GitHub GraphQL: ${body.errors.map((e) => e.message).join('; ')}`);
|
|
}
|
|
return body.data;
|
|
}
|
|
|
|
/** The human author, pull request number and merge time of each of {@code numbers}. */
|
|
export async function contributionsOf(owner, repo, numbers, token, fetchImpl = fetch) {
|
|
const contributions = [];
|
|
for (let i = 0; i < numbers.length; i += PULL_REQUESTS_PER_QUERY) {
|
|
const fields = numbers.slice(i, i + PULL_REQUESTS_PER_QUERY)
|
|
.map((n) => `p${n}: pullRequest(number: ${n}) { number mergedAt author { login __typename } }`)
|
|
.join(' ');
|
|
const data = await graphql(
|
|
`query { repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(repo)}) { ${fields} } }`,
|
|
token, fetchImpl);
|
|
for (const pullRequest of Object.values(data.repository)) {
|
|
if (pullRequest && !isExcluded(pullRequest.author)) {
|
|
contributions.push({
|
|
login: pullRequest.author.login, number: pullRequest.number, mergedAt: pullRequest.mergedAt,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
return contributions;
|
|
}
|
|
|
|
/** The logins with no pull request merged into the repository before {@code since}. */
|
|
export async function newcomersAmong(owner, repo, logins, since, token, fetchImpl = fetch) {
|
|
const newcomers = new Set();
|
|
for (let i = 0; i < logins.length; i += SEARCHES_PER_QUERY) {
|
|
const chunk = logins.slice(i, i + SEARCHES_PER_QUERY);
|
|
const fields = chunk.map((login, index) => {
|
|
const q = `repo:${owner}/${repo} is:pr is:merged author:${login} merged:<${since}`;
|
|
return `s${index}: search(query: ${JSON.stringify(q)}, type: ISSUE, first: 0) { issueCount }`;
|
|
}).join(' ');
|
|
const data = await graphql(`query { ${fields} }`, token, fetchImpl);
|
|
chunk.forEach((login, index) => {
|
|
if (data[`s${index}`].issueCount === 0) {
|
|
newcomers.add(login);
|
|
}
|
|
});
|
|
}
|
|
return newcomers;
|
|
}
|
|
|
|
function ownerAndRepo(repositoryUrl) {
|
|
const match = (repositoryUrl ?? '').match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/);
|
|
return match ? { owner: match[1], repo: match[2] } : null;
|
|
}
|
|
|
|
/** semantic-release's generateNotes step. */
|
|
export async function generateNotes(pluginConfig, context) {
|
|
const { commits, lastRelease, options, env, logger } = context;
|
|
const token = env.GH_TOKEN || env.GITHUB_TOKEN;
|
|
const repository = ownerAndRepo(options.repositoryUrl);
|
|
const numbers = pullRequestNumbers(commits);
|
|
if (!token || !repository || numbers.length === 0) {
|
|
logger.log('Contributors: no token, repository or pull requests to read; section left out');
|
|
return '';
|
|
}
|
|
const fetchImpl = pluginConfig.fetch ?? fetch;
|
|
try {
|
|
const contributions = await contributionsOf(repository.owner, repository.repo, numbers, token, fetchImpl);
|
|
const logins = [...new Set(contributions.map((c) => c.login))];
|
|
const since = lastRelease?.gitTag ? pluginConfig.lastReleaseDate ?? await tagDate(lastRelease.gitTag) : null;
|
|
const newcomers = since
|
|
? await newcomersAmong(repository.owner, repository.repo, logins, since, token, fetchImpl)
|
|
: new Set();
|
|
logger.log(`Contributors: ${logins.length} from ${numbers.length} pull requests, ${newcomers.size} new`);
|
|
return formatSection(contributions, newcomers);
|
|
} catch (error) {
|
|
logger.error(`Contributors: section left out, ${error.message}`);
|
|
return '';
|
|
}
|
|
}
|
|
|
|
/** The commit time of {@code tag}, ISO 8601, as GitHub's merged: qualifier takes it. */
|
|
async function tagDate(tag) {
|
|
const { execFile } = await import('node:child_process');
|
|
return new Promise((resolve, reject) => {
|
|
execFile('git', ['log', '-1', '--format=%cI', tag], (error, stdout) => {
|
|
if (error) {
|
|
reject(error);
|
|
} else {
|
|
resolve(stdout.trim());
|
|
}
|
|
});
|
|
});
|
|
}
|