import * as ChildProcess from "node:child_process" import * as Fs from "node:fs" import * as Path from "node:path" /** * Runs after `changeset version` and thanks the reporters of issues fixed by * maintainer PRs in each new changelog entry, which becomes the GitHub release body. */ const repo = "Effect-TS/effect" const heading = "### Thanks to these issue reporters" export interface Actor { readonly login: string } export interface Issue { readonly number: number readonly author: Actor | null readonly authorAssociation: string readonly repository: { readonly nameWithOwner: string } } export interface PullRequest { readonly author: Actor | null readonly authorAssociation: string readonly issues: ReadonlyArray } // Needs an org member's token: others see private members as `CONTRIBUTOR` const isMaintainer = (association: string) => association === "OWNER" || association === "MEMBER" || association === "COLLABORATOR" const entryRange = (changelog: string, version: string) => { const start = changelog.indexOf(`\n## ${version}\n`) if (start === -1) return undefined const next = changelog.indexOf("\n## ", start + 1) return { start, end: next === -1 ? changelog.length : next + 1 } } /** Pull requests credited by release lines in the changelog entry for `version`. */ export const pullRequestNumbers = (changelog: string, version: string): Array => { const range = entryRange(changelog, version) if (range === undefined) return [] const entry = changelog.slice(range.start, range.end) // Only the generated `- [#123](...)` prefix, not links in descriptions const pattern = new RegExp(`^- \\[#(\\d+)\\]\\(https://github\\.com/${repo}/pull/\\d+\\)`, "gm") return [...new Set(Array.from(entry.matchAll(pattern), (match) => Number(match[1])))] } export const addReporterSection = ( changelog: string, version: string, pullRequests: ReadonlyMap ): string => { const range = entryRange(changelog, version) if (range === undefined) return changelog const entry = changelog.slice(range.start, range.end) if (entry.includes(`\n${heading}\n`)) return changelog const reporters = new Map>() for (const number of pullRequestNumbers(changelog, version)) { const pr = pullRequests.get(number) if (pr === undefined || !isMaintainer(pr.authorAssociation)) continue for (const issue of pr.issues) { const login = issue.author?.login if ( login === undefined || login === pr.author?.login || issue.repository.nameWithOwner !== repo || isMaintainer(issue.authorAssociation) ) continue let issues = reporters.get(login) if (issues === undefined) reporters.set(login, issues = new Set()) issues.add(issue.number) } } if (reporters.size === 0) return changelog const lines = Array.from(reporters, ([login, issues]) => { const links = Array.from(issues).sort((a, b) => a - b).map((number) => `[#${number}](https://github.com/${repo}/issues/${number})` ) return `- @${login} for ${links.join(", ")}` }) const section = `${heading}\n\n${lines.join("\n")}\n` // Directly below the `## ` line, ahead of the release notes const at = changelog.indexOf("\n", range.start + 1) + 1 return `${changelog.slice(0, at)}\n${section}${changelog.slice(at)}` } /** Runs a GitHub GraphQL query and returns its `data`. */ export type Graphql = (query: string, variables: Record) => Promise interface PullRequestPage { readonly author: Actor | null readonly authorAssociation: string readonly closingIssuesReferences: { readonly nodes: ReadonlyArray readonly pageInfo: { readonly hasNextPage: boolean; readonly endCursor: string | null } } } const [owner, name] = repo.split("/") const pullRequestQuery = `query($number: Int!, $after: String) { repository(owner: "${owner}", name: "${name}") { pullRequest(number: $number) { author { login } authorAssociation closingIssuesReferences(first: 100, after: $after) { pageInfo { hasNextPage endCursor } nodes { number author { login } authorAssociation repository { nameWithOwner } } } } } }` const fetchPullRequest = async (number: number, graphql: Graphql): Promise => { const issues: Array = [] let after: string | null = null while (true) { const { author, authorAssociation, closingIssuesReferences }: PullRequestPage = (await graphql(pullRequestQuery, { number, after })).repository.pullRequest issues.push(...closingIssuesReferences.nodes) if (!closingIssuesReferences.pageInfo.hasNextPage) return { author, authorAssociation, issues } after = closingIssuesReferences.pageInfo.endCursor } } // GitHub's secondary rate limit allows 100 concurrent requests const concurrency = 10 /** Fetches each pull request with all pages of its closing issues. */ export const fetchPullRequests = async ( numbers: ReadonlyArray, graphql: Graphql ): Promise> => { const pullRequests = new Map() const queue = numbers.values() await Promise.all(Array.from({ length: concurrency }, async () => { for (const number of queue) pullRequests.set(number, await fetchPullRequest(number, graphql)) })) return pullRequests } const github = (token: string): Graphql => async (query, variables) => { const response = await fetch("https://api.github.com/graphql", { method: "POST", headers: { authorization: `bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ query, variables }) }) const result = await response.json() as { readonly data?: unknown; readonly errors?: ReadonlyArray } if (!response.ok || result.errors !== undefined || result.data === undefined) { throw new Error(`GitHub GraphQL request failed: ${response.status} ${JSON.stringify(result.errors ?? result)}`) } return result.data } if (import.meta.main) { // Changelogs written by `changeset version` in this run const changelogs = ChildProcess.execFileSync( "git", ["ls-files", "--modified", "--others", "--exclude-standard", "--", "*CHANGELOG.md"], { encoding: "utf8" } ).split("\n").filter((file) => file !== "").map((file) => { const { version } = JSON.parse(Fs.readFileSync(Path.join(Path.dirname(file), "package.json"), "utf8")) return { file, version: version as string, content: Fs.readFileSync(file, "utf8") } }) const numbers = [...new Set(changelogs.flatMap(({ content, version }) => pullRequestNumbers(content, version)))] if (numbers.length > 0) { const token = process.env.GITHUB_TOKEN if (!token) throw new Error("GITHUB_TOKEN is required to find issue reporters") const pullRequests = await fetchPullRequests(numbers, github(token)) for (const { content, file, version } of changelogs) { const updated = addReporterSection(content, version, pullRequests) if (updated !== content) Fs.writeFileSync(file, updated) } } }