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
12 changes: 12 additions & 0 deletions src/gitUtils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
5 changes: 4 additions & 1 deletion src/gitUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -109,7 +111,8 @@ export const cherryPickCommits = async (task: Task, repoRoot: string): Promise<C
continue
} catch (e) {
conflicts = true
await git.raw(['cherry-pick', '--abort'])
// Nothing to abort if the cherry-pick could not start, report why
await git.raw(['cherry-pick', '--abort']).catch(() => { throw e })
error(task, `Could not cherry pick commit ${commit.slice(0, 8)}: ${e.message}`)
}

Expand Down
49 changes: 49 additions & 0 deletions src/githubUtils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof commit>[], 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'])
})
})
62 changes: 58 additions & 4 deletions src/githubUtils.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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<string[]> => {
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<void> => {
Expand Down
Loading