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
47 changes: 0 additions & 47 deletions .github/workflows/changelog-comment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ jobs:
github-token: ${{ github.token }}
script: |
const marker = '<!-- changelog -->';
const mergedMarker = '<!-- changelog-merged -->';

const sections = ['### Added', '', '### Changed', '', '### Deprecated', '', '### Removed', '', '### Fixed', '', '### Security'].join('\n');
const productBlock = (name) => `<details>\n<summary>${name}</summary>\n\n${sections}\n\n</details>`;
Expand Down Expand Up @@ -53,13 +52,6 @@ jobs:
return;
}

// Get PR details (need base ref for child PR detection)
const { data: pr } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prNumber,
});

// Check if bot comment already exists
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
Expand All @@ -82,42 +74,3 @@ jobs:
});

core.info(`Posted changelog comment on PR #${prNumber}`);

// Detect child PR: check if this PR's base branch is another open PR's head branch
const baseRef = pr.base.ref;

if (baseRef === 'main' || baseRef === 'prod') {
return;
}

// Look for a parent PR whose head branch matches our base branch
const { data: candidatePRs } = await github.rest.pulls.list({
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open',
head: `${context.repo.owner}:${baseRef}`,
});

if (candidatePRs.length === 0) {
return;
}

const parentPR = candidatePRs[0];
core.info(`Detected parent PR #${parentPR.number} for child PR #${prNumber}`);

// Add admonition to child PR's changelog comment
const { data: childComments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
});

const childChangelogComment = childComments.find(c => c.body.includes(marker));
if (childChangelogComment && !childChangelogComment.body.includes(mergedMarker)) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: childChangelogComment.id,
body: `${mergedMarker}\n> [!NOTE]\n> This changelog has been merged into the changelog for #${parentPR.number}\n\n${childChangelogComment.body}`,
});
}
115 changes: 102 additions & 13 deletions scripts/collect-changelog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,17 @@ interface ParsedChangelog {

interface PRInfo {
number: number
mergedAt: string
mergedAt: string | null
headRef: string
headRepo: string | null
stackedOn?: number
}

interface GitHubPR {
number: number
merged_at: string | null
updated_at: string
head: { ref: string; repo: { full_name: string } | null }
}

interface CommentInfo {
Expand Down Expand Up @@ -230,11 +240,7 @@ async function fetchMergedPRs(token: string, sinceDate: string): Promise<PRInfo[
process.exit(1)
}

const data = (await res.json()) as Array<{
number: number
merged_at: string | null
updated_at: string
}>
const data = (await res.json()) as GitHubPR[]

if (data.length === 0) break

Expand All @@ -244,7 +250,7 @@ async function fetchMergedPRs(token: string, sinceDate: string): Promise<PRInfo[
allTooOld = false
if (!pr.merged_at) continue
if (new Date(pr.merged_at) > new Date(sinceDate)) {
prs.push({ number: pr.number, mergedAt: pr.merged_at })
prs.push(toPRInfo(pr))
}
}

Expand All @@ -255,6 +261,84 @@ async function fetchMergedPRs(token: string, sinceDate: string): Promise<PRInfo[
return prs
}

function toPRInfo(pr: GitHubPR, stackedOn?: number): PRInfo {
return {
number: pr.number,
mergedAt: pr.merged_at,
headRef: pr.head.ref,
headRepo: pr.head.repo?.full_name ?? null,
stackedOn,
}
}

async function fetchPR(token: string, prNumber: number): Promise<PRInfo> {
const res = await githubFetch(`/repos/${REPO}/pulls/${prNumber}`, token)

if (!res.ok) {
console.error(
chalk.red(`GitHub API error for PR #${prNumber}: ${res.status} ${res.statusText}`),
)
process.exit(1)
}

return toPRInfo((await res.json()) as GitHubPR)
}

async function fetchStackedPRs(
token: string,
parent: PRInfo,
seen: Set<number>,
): Promise<PRInfo[]> {
if (parent.headRepo !== REPO) return []

const stacked: PRInfo[] = []
let page = 1

while (true) {
const res = await githubFetch(
`/repos/${REPO}/pulls?state=closed&base=${encodeURIComponent(parent.headRef)}&per_page=100&page=${page}`,
token,
)

if (!res.ok) {
console.error(chalk.red(`GitHub API error: ${res.status} ${res.statusText}`))
process.exit(1)
}

const data = (await res.json()) as GitHubPR[]

for (const pr of data) {
if (!pr.merged_at || seen.has(pr.number)) continue
if (parent.mergedAt && new Date(pr.merged_at) > new Date(parent.mergedAt)) continue

seen.add(pr.number)
const child = toPRInfo(pr, parent.number)
stacked.push(child, ...(await fetchStackedPRs(token, child, seen)))
Comment thread
IMB11 marked this conversation as resolved.
Resolved
}

if (data.length < 100) break
page++
}

return stacked
}

async function withStackedPRs(token: string, roots: PRInfo[]): Promise<PRInfo[]> {
const seen = new Set(roots.map((pr) => pr.number))
const prs: PRInfo[] = []

for (const root of roots) {
prs.push(root, ...(await fetchStackedPRs(token, root, seen)))
}

const stackedCount = prs.length - roots.length
if (stackedCount > 0) {
console.log(chalk.gray(`Found ${stackedCount} PR(s) merged into stacked branches`))
}

return prs
}

function getLatestAppRelease(): AppRelease {
const tag = execFileSync(
'git',
Expand Down Expand Up @@ -349,11 +433,11 @@ async function main() {
const rootDir = path.resolve(__dirname, '..')
const changelogPath = path.join(rootDir, 'packages', 'blog', 'changelog.ts')

let prs: PRInfo[]
let roots: PRInfo[]

if (args.pr) {
console.log(chalk.gray(`Targeting single PR #${args.pr}`))
prs = [{ number: args.pr, mergedAt: '' }]
roots = [await fetchPR(token, args.pr)]
} else {
const prodDate = execSync('git log -1 --format=%aI origin/prod', { encoding: 'utf-8' }).trim()
console.log(chalk.gray(`Last prod commit: ${prodDate}`))
Expand All @@ -367,15 +451,17 @@ async function main() {
}
}

prs = await fetchMergedPRs(token, sinceDate)
console.log(chalk.gray(`Found ${prs.length} merged PR(s) since ${sinceDate}`))
roots = await fetchMergedPRs(token, sinceDate)
console.log(chalk.gray(`Found ${roots.length} merged PR(s) since ${sinceDate}`))

if (prs.length === 0) {
if (roots.length === 0) {
console.log(chalk.yellow(`No merged PRs found since ${sinceDate}`))
return
}
}

const prs = await withStackedPRs(token, roots)

const allEntries = new Map<Product, { sections: Map<string, string[]>; prNumber: number }[]>()
const processedComments: { commentId: number; body: string }[] = []

Expand All @@ -399,7 +485,10 @@ async function main() {

const products = [...parsed.entries.keys()]
const types = [...new Set([...parsed.entries.values()].flatMap((s) => [...s.keys()]))]
console.log(chalk.cyan(`PR #${pr.number}: ${products.join(', ')} — ${types.join(', ')}`))
const label = pr.stackedOn
? `PR #${pr.number} (stacked on #${pr.stackedOn})`
: `PR #${pr.number}`
console.log(chalk.cyan(`${label}: ${products.join(', ')} — ${types.join(', ')}`))

for (const [product, sections] of parsed.entries) {
if (!allEntries.has(product)) {
Expand Down
123 changes: 123 additions & 0 deletions scripts/migrate-changelog-stack-notes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { execSync } from 'child_process'
import chalk from 'chalk'

const GITHUB_API = 'https://api.github.com'
const REPO = 'modrinth/code'
const CHANGELOG_MARKER = '<!-- changelog -->'
const STACK_NOTE_MARKER = '<!-- changelog-merged -->'
const STACK_NOTE = /<!-- changelog-merged -->[ \t]*\r?\n(?:>.*(?:\r?\n|$))*(?:[ \t]*\r?\n)*/g
const CHANGELOG_SYSTEM_INTRODUCED = '2026-03-23T00:00:00Z'

interface IssueComment {
id: number
body: string
issue_url: string
}

function parseArgs(argv: string[]): { dryRun: boolean } {
let dryRun = false

for (const arg of argv) {
if (arg === '--') continue
if (arg === '--dry-run') {
dryRun = true
} else {
console.error(chalk.red(`Unknown argument: ${arg}`))
process.exit(1)
}
}

return { dryRun }
}

function getToken(): string {
if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN

try {
return execSync('gh auth token', { encoding: 'utf-8' }).trim()
} catch {
console.error(
chalk.red(
'GITHUB_TOKEN not set and `gh auth token` failed. Run `gh auth login` or set GITHUB_TOKEN.',
),
)
process.exit(1)
}
}

async function githubFetch(
endpoint: string,
token: string,
options?: RequestInit,
): Promise<Response> {
return fetch(`${GITHUB_API}${endpoint}`, {
...options,
headers: {
Authorization: `token ${token}`,
Accept: 'application/vnd.github.v3+json',
...options?.headers,
},
})
}

async function fetchStackNoteComments(token: string): Promise<IssueComment[]> {
const matches: IssueComment[] = []
let page = 1

while (true) {
const res = await githubFetch(
`/repos/${REPO}/issues/comments?since=${CHANGELOG_SYSTEM_INTRODUCED}&sort=created&direction=asc&per_page=100&page=${page}`,
token,
)

if (!res.ok) {
console.error(chalk.red(`GitHub API error: ${res.status} ${res.statusText}`))
process.exit(1)
}

const data = (await res.json()) as IssueComment[]
matches.push(
...data.filter(
(c) => c.body?.includes(CHANGELOG_MARKER) && c.body.includes(STACK_NOTE_MARKER),
),
)

if (data.length < 100) break
page++
}

return matches
}

async function main() {
const args = parseArgs(process.argv.slice(2))
const token = getToken()

const comments = await fetchStackNoteComments(token)
console.log(chalk.gray(`Found ${comments.length} changelog comment(s) with a stack note`))

for (const comment of comments) {
const prNumber = comment.issue_url.split('/').pop()
const body = comment.body.replace(STACK_NOTE, '')

if (args.dryRun) {
console.log(chalk.cyan(`[dry-run] PR #${prNumber}: would remove stack note`))
continue
}

const res = await githubFetch(`/repos/${REPO}/issues/comments/${comment.id}`, token, {
method: 'PATCH',
body: JSON.stringify({ body }),
})

if (res.ok) {
console.log(chalk.green(`PR #${prNumber}: removed stack note`))
} else {
console.error(
chalk.red(`PR #${prNumber}: failed to update (${res.status} ${res.statusText})`),
)
}
Comment thread
IMB11 marked this conversation as resolved.
Resolved
}
}

main()
Loading