From 082a539ae8571b7f92db22ae77c9d7353357ec9d Mon Sep 17 00:00:00 2001 From: Julius Knorr Date: Mon, 30 Nov 2026 21:01:37 +0100 Subject: [PATCH] fix: backport the landed commits of squash and rebase merges Full requests picked the original commits of a pull request. After a squash or rebase merge those only live on the head branch, which is often a fork or already deleted, so the cherry-pick failed. Use the commits that landed on the base branch when the merge method is certain, and fetch the pull request head so the original commits are always available. Report the cherry-pick error instead of the failed abort that hid it. Signed-off-by: Julius Knorr Assisted-by: ClaudeCode:claude-opus-5-5 --- src/gitUtils.spec.ts | 12 ++++++++ src/gitUtils.ts | 5 +++- src/githubUtils.spec.ts | 49 ++++++++++++++++++++++++++++++++ src/githubUtils.ts | 62 ++++++++++++++++++++++++++++++++++++++--- 4 files changed, 123 insertions(+), 5 deletions(-) diff --git a/src/gitUtils.spec.ts b/src/gitUtils.spec.ts index 083d9bf..60f75ee 100644 --- a/src/gitUtils.spec.ts +++ b/src/gitUtils.spec.ts @@ -61,6 +61,18 @@ describe('cherryPickCommits', () => { const amended = await git.raw(['log', '-1', '--format=%B']) expect(amended.trim()).toBe(`${message}\n\n[skip ci]`) }) + + test('reports why a commit could not be picked, not the failed abort', async () => { + const git = simpleGit(repoRoot) + await git.init() + await git.addConfig('user.name', 'Test') + await git.addConfig('user.email', 'test@example.com') + await git.addConfig('commit.gpgsign', 'false') + await git.commit('init', ['--allow-empty']) + + const task = { commits: ['1da5c3e0aca402cb18f9894503c0a39e102285c4'] } as Task + await expect(cherryPickCommits(task, repoRoot)).rejects.toThrow('bad object') + }) }) describe('installation token', () => { diff --git a/src/gitUtils.ts b/src/gitUtils.ts index 6caba82..4fa72c3 100644 --- a/src/gitUtils.ts +++ b/src/gitUtils.ts @@ -76,6 +76,8 @@ export const cloneAndCacheRepo = async (task: Task, backportBranch: string, toke // fetch upstream version of the branch - well we need to fetch all because we do not know where the commits are located we need to cherry-pick await git.fetch(['-p', '--all']) + // Commits of fork pull requests and deleted branches are only kept here + await git.fetch(['origin', `pull/${task.prNumber}/head`]) // make sure the branch doesn't already exist try { @@ -109,7 +111,8 @@ export const cherryPickCommits = async (task: Task, repoRoot: string): Promise { throw e }) error(task, `Could not cherry pick commit ${commit.slice(0, 8)}: ${e.message}`) } diff --git a/src/githubUtils.spec.ts b/src/githubUtils.spec.ts index 1a2ce2d..75342c0 100644 --- a/src/githubUtils.spec.ts +++ b/src/githubUtils.spec.ts @@ -90,3 +90,52 @@ describe('Pull requests GitHub cannot fully list', () => { await expect(getCommitsForPR(pagedOctokit(commits), 'nextcloud', 'server', 1)).rejects.toThrow('250 commits or more') }) }) + +describe('Commits of a merged pull request', () => { + const commit = (sha: string, message: string, parents = 1) => ({ sha, commit: { message }, parents: Array.from({ length: parents }, () => ({})) }) + const prCommits = [commit('a1', 'fix: first'), commit('a2', 'fix: second')] + + // Answers the pull request, its commits, the merge commit and the base branch history + const mergedOctokit = (mergeSha: string | null, mergeParents: number, baseHistory: ReturnType[], mergeMessage = baseHistory[0]?.commit.message ?? '') => new Octokit({ + request: { + fetch: async (url: string) => { + const { pathname } = new URL(url) + const body = pathname.endsWith('/pulls/1/commits') ? prCommits + : pathname.endsWith('/pulls/1') ? { merged_at: mergeSha ? '2026-11-30T00:00:00Z' : null, merge_commit_sha: mergeSha } + : pathname.includes('/git/commits/') ? { sha: mergeSha, message: mergeMessage, parents: Array.from({ length: mergeParents }, () => ({})) } + : baseHistory + return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }) + }, + }, + }) + + test('squash merge backports the squashed commit', async () => { + const octokit = mergedOctokit('s1', 1, [commit('s1', 'fix: both (#1)'), commit('m0', 'chore: older')]) + expect(await getCommitsForPR(octokit, 'nextcloud', 'server', 1)).toEqual(['s1']) + }) + + test('rebase merge backports the rebased commits in order', async () => { + const octokit = mergedOctokit('r2', 1, [commit('r2', 'fix: second'), commit('r1', 'fix: first'), commit('m0', 'chore: older')]) + expect(await getCommitsForPR(octokit, 'nextcloud', 'server', 1)).toEqual(['r1', 'r2']) + }) + + test('rebase merge is found whatever order GitHub lists the pull request commits in', async () => { + const octokit = mergedOctokit('r2', 1, [commit('r2', 'fix: first'), commit('r1', 'fix: second'), commit('m0', 'chore: older')]) + expect(await getCommitsForPR(octokit, 'nextcloud', 'server', 1)).toEqual(['r1', 'r2']) + }) + + test('unknown merge method backports the original commits instead of guessing', async () => { + const octokit = mergedOctokit('x1', 1, [commit('x1', 'fix: reworded'), commit('m0', 'chore: older')]) + expect(await getCommitsForPR(octokit, 'nextcloud', 'server', 1)).toEqual(['a1', 'a2']) + }) + + test('merge commit backports the original commits', async () => { + const octokit = mergedOctokit('mc', 2, []) + expect(await getCommitsForPR(octokit, 'nextcloud', 'server', 1)).toEqual(['a1', 'a2']) + }) + + test('open pull request backports the original commits', async () => { + const octokit = mergedOctokit(null, 1, []) + expect(await getCommitsForPR(octokit, 'nextcloud', 'server', 1)).toEqual(['a1', 'a2']) + }) +}) diff --git a/src/githubUtils.ts b/src/githubUtils.ts index 30237b0..7b30f37 100644 --- a/src/githubUtils.ts +++ b/src/githubUtils.ts @@ -1,4 +1,5 @@ import { Octokit } from '@octokit/rest' +import { info, warn } from 'node:console' import { getApp } from './appUtils' import { AuthResponse, COMMAND_PREFIX, PRChanges, Task } from './constants' import { IssueComment, Milestone } from '@octokit/webhooks-types' @@ -64,10 +65,63 @@ export const getCommitsForPR = async (octokit: Octokit, owner: string, repo: str if (commits.length >= MAX_PR_COMMITS) { throw new Error(`Pull request has ${MAX_PR_COMMITS} commits or more, GitHub does not list them all`) } - return commits - // Filter out merge commits - .filter(commit => (commit.parents || []).length <= 1) - .map(commit => commit.sha) + // Filter out merge commits + const prCommits = commits.filter(commit => (commit.parents || []).length <= 1) + + const { data: pull } = await octokit.rest.pulls.get({ owner, repo, pull_number: pr }) + if (!pull.merged_at || !pull.merge_commit_sha) { + return prCommits.map(commit => commit.sha) + } + return getLandedCommits(octokit, owner, repo, pr, pull.merge_commit_sha, prCommits) +} + +const firstLine = (message: string) => message.split('\n')[0].trim() +const sortedSubjects = (commits: { commit: { message: string } }[]) => commits.map(commit => firstLine(commit.commit.message)).sort() + +/** + * Squash and rebase merges create new commits on the base branch. + * The original commits are based on an older base branch and can + * conflict where the landed ones don't. Use the landed commits when + * the merge method is certain, else keep the original commits. + */ +const getLandedCommits = async (octokit: Octokit, owner: string, repo: string, pr: number, mergeSha: string, prCommits: { sha: string, commit: { message: string } }[]): Promise => { + const { data: mergeCommit } = await octokit.rest.git.getCommit({ owner, repo, commit_sha: mergeSha }) + if (mergeCommit.parents.length > 1) { + info(`├ PR #${pr} was merged with a merge commit, using its commits`) + return prCommits.map(commit => commit.sha) + } + if (prCommits.length <= 1) { + info(`├ PR #${pr} landed as ${mergeSha.slice(0, 8)}`) + return [mergeSha] + } + + // Rebase merge: the last commits of the base branch carry the same subjects + let listed = 0 + const landed = await octokit.paginate( + octokit.rest.repos.listCommits, + { owner, repo, sha: mergeSha, per_page: Math.min(prCommits.length, 100) }, + (response, done) => { + listed += response.data.length + if (listed >= prCommits.length) { + done() + } + return response.data + }, + ) + const rebased = landed.slice(0, prCommits.length).reverse() + if (sortedSubjects(rebased).join('\n') === sortedSubjects(prCommits).join('\n')) { + info(`├ PR #${pr} was rebase merged, using the rebased commits`) + return rebased.map(commit => commit.sha) + } + + // Squash merge: GitHub adds the pull request number to the subject + if (firstLine(mergeCommit.message).endsWith(`(#${pr})`)) { + info(`├ PR #${pr} was squash merged, using ${mergeSha.slice(0, 8)}`) + return [mergeSha] + } + + warn(`├ PR #${pr} merge method unknown, using its original commits`) + return prCommits.map(commit => commit.sha) } export const addReaction = async (octokit: Octokit, task: Task, reaction: Reaction): Promise => {