From e8b859118f07b490d2b3a557b84f9ad10bd271cd Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 30 May 2026 01:04:45 -0700 Subject: [PATCH] Use GitHub merge method metadata for PR actions --- src/main/github/client.test.ts | 63 ++++++++ src/main/github/client.ts | 139 +++++++++++++----- .../src/components/GitHubItemDialog.tsx | 37 +++-- .../src/components/PullRequestPage.tsx | 37 +++-- src/renderer/src/components/TaskPage.tsx | 33 +++-- .../right-sidebar/HostedReviewActions.tsx | 35 +++-- src/shared/github-pr-merge-methods.test.ts | 51 +++++++ src/shared/github-pr-merge-methods.ts | 93 ++++++++++++ src/shared/types.ts | 9 ++ 9 files changed, 396 insertions(+), 101 deletions(-) create mode 100644 src/shared/github-pr-merge-methods.test.ts create mode 100644 src/shared/github-pr-merge-methods.ts diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index 2f1919896..e99076ee7 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -305,6 +305,69 @@ describe('getPRForBranch', () => { }) }) + it('hydrates repository merge method settings for exact PR lookups', async () => { + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 99, + title: 'Linked PR', + state: 'OPEN', + url: 'https://github.com/acme/widgets/pull/99', + statusCheckRollup: [], + updatedAt: '2026-03-28T00:00:00Z', + isDraft: false, + mergeable: 'MERGEABLE', + reviewDecision: 'APPROVED', + mergeStateStatus: 'CLEAN', + autoMergeRequest: null, + baseRefName: 'main', + headRefName: 'someone/fix', + baseRefOid: 'base-oid', + headRefOid: 'linked-head-oid' + }) + }) + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + data: { + repository: { + viewerDefaultMergeMethod: 'REBASE', + mergeCommitAllowed: false, + rebaseMergeAllowed: true, + squashMergeAllowed: true, + mergeQueue: null + } + } + }) + }) + + const pr = await getPRForBranch('/repo-root', 'feature/local-worktree', 99) + + expect(pr?.mergeMethodSettings).toEqual({ + defaultMethod: 'rebase', + allowedMethods: { + squash: true, + merge: false, + rebase: true + } + }) + expect(pr?.mergeQueueRequired).toBe(false) + expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( + 2, + expect.arrayContaining([ + 'api', + 'graphql', + '-f', + 'owner=acme', + '-f', + 'repo=widgets', + '-f', + 'branch=main' + ]), + { cwd: '/repo-root' } + ) + }) + it('treats linked PR metadata as authoritative even when the branch head differs', async () => { getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: 'current-worktree-head\n', stderr: '' }) diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 834cfe7d9..f4be72e45 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -18,13 +18,15 @@ import type { GitHubViewer, GitHubWorkItem, GitHubPullRequestStateUpdate, - GitHubRerunPRChecksResult + GitHubRerunPRChecksResult, + GitHubPRMergeMethodSettings } from '../../shared/types' import type { CreateHostedReviewInput, CreateHostedReviewResult } from '../../shared/hosted-review' import { normalizeHostedReviewBaseRef, normalizeHostedReviewHeadRef } from '../../shared/hosted-review-refs' +import { normalizeGitHubPRMergeMethodSettings } from '../../shared/github-pr-merge-methods' import { parseTaskQuery, type ParsedTaskQuery } from '../../shared/task-query' import { GITHUB_WORK_ITEMS_SSH_REMOTE_REQUIRED_MESSAGE, @@ -88,10 +90,17 @@ type GhExecOptions = ReturnType const ORCA_REPO = 'stablyai/orca' const MERGE_QUEUE_CACHE_TTL_MS = 10 * 60 * 1000 const MERGE_QUEUE_UNKNOWN_CACHE_TTL_MS = 60 * 1000 -const mergeQueueRequiredCache = new Map() +type GitHubRepositoryMergeMetadata = { + mergeQueueRequired: boolean | null + mergeMethodSettings?: GitHubPRMergeMethodSettings +} +const repositoryMergeMetadataCache = new Map< + string, + { value: GitHubRepositoryMergeMetadata; expiresAt: number } +>() export function _resetMergeQueueCacheForTests(): void { - mergeQueueRequiredCache.clear() + repositoryMergeMetadataCache.clear() } async function assertRateLimitBudget(bucket: RateLimitBucketKind): Promise { @@ -735,8 +744,14 @@ async function fetchPullRequestWorkItem( const item = JSON.parse(stdout) as Record const mapped = mapPullRequestWorkItem(item, ownerRepo) const baseRefName = typeof item.baseRefName === 'string' ? item.baseRefName : undefined - const mergeQueueRequired = await detectMergeQueueRequired(ownerRepo, baseRefName, ghOptions) - return { ...mapped, mergeQueueRequired } + const mergeMetadata = await detectRepositoryMergeMetadata(ownerRepo, baseRefName, ghOptions) + return { + ...mapped, + mergeQueueRequired: mergeMetadata.mergeQueueRequired, + ...(mergeMetadata.mergeMethodSettings + ? { mergeMethodSettings: mergeMetadata.mergeMethodSettings } + : {}) + } } catch { const { stdout } = await ghExecFileAsync( ['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${number}`], @@ -1694,6 +1709,7 @@ type PullRequestLookupData = { autoMergeRequest?: unknown autoMergeEnabled?: boolean mergeQueueRequired?: boolean | null + mergeMethodSettings?: GitHubPRMergeMethodSettings mergeStateStatus?: string | null baseRefName?: string headRefName?: string @@ -1760,63 +1776,99 @@ function normalizePullRequestLookupData(data: PullRequestLookupData): PullReques } } -function cacheMergeQueueRequired(cacheKey: string, value: boolean | null, ttlMs: number): void { - mergeQueueRequiredCache.set(cacheKey, { +function cacheRepositoryMergeMetadata( + cacheKey: string, + value: GitHubRepositoryMergeMetadata, + ttlMs: number +): void { + repositoryMergeMetadataCache.set(cacheKey, { value, expiresAt: Date.now() + ttlMs }) } -async function detectMergeQueueRequired( +async function detectRepositoryMergeMetadata( ownerRepo: OwnerRepo, branchName: string | undefined, ghOptions: GhExecOptions -): Promise { - if (!branchName) { - return null - } - const cacheKey = `${ownerRepo.owner.toLowerCase()}/${ownerRepo.repo.toLowerCase()}:${branchName}` - const cached = mergeQueueRequiredCache.get(cacheKey) +): Promise { + const cacheKey = `${ownerRepo.owner.toLowerCase()}/${ownerRepo.repo.toLowerCase()}:${ + branchName ?? '__repo__' + }` + const cached = repositoryMergeMetadataCache.get(cacheKey) if (cached && cached.expiresAt > Date.now()) { return cached.value } const guard = rateLimitGuard('graphql') if (guard.blocked) { - return null + return { mergeQueueRequired: null } } - const query = `query($owner: String!, $repo: String!, $branch: String!) { + const query = branchName + ? `query($owner: String!, $repo: String!, $branch: String!) { repository(owner: $owner, name: $repo) { + viewerDefaultMergeMethod + mergeCommitAllowed + rebaseMergeAllowed + squashMergeAllowed mergeQueue(branch: $branch) { id } } + }` + : `query($owner: String!, $repo: String!) { + repository(owner: $owner, name: $repo) { + viewerDefaultMergeMethod + mergeCommitAllowed + rebaseMergeAllowed + squashMergeAllowed + } }` try { noteRateLimitSpend('graphql') - const { stdout } = await ghExecFileAsync( - [ - 'api', - 'graphql', - '-f', - `query=${query}`, - '-f', - `owner=${ownerRepo.owner}`, - '-f', - `repo=${ownerRepo.repo}`, - '-f', - `branch=${branchName}` - ], - ghOptions - ) - const parsed = JSON.parse(stdout) as { - data?: { repository?: { mergeQueue?: { id?: unknown } | null } | null } + const args = [ + 'api', + 'graphql', + '-f', + `query=${query}`, + '-f', + `owner=${ownerRepo.owner}`, + '-f', + `repo=${ownerRepo.repo}` + ] + if (branchName) { + args.push('-f', `branch=${branchName}`) } - const value = Boolean(parsed.data?.repository?.mergeQueue) - cacheMergeQueueRequired(cacheKey, value, MERGE_QUEUE_CACHE_TTL_MS) + const { stdout } = await ghExecFileAsync(args, ghOptions) + const parsed = JSON.parse(stdout) as { + data?: { + repository?: { + viewerDefaultMergeMethod?: unknown + mergeCommitAllowed?: unknown + rebaseMergeAllowed?: unknown + squashMergeAllowed?: unknown + mergeQueue?: { id?: unknown } | null + } | null + } + } + const repository = parsed.data?.repository + const mergeMethodSettings = repository + ? normalizeGitHubPRMergeMethodSettings({ + defaultMethod: repository.viewerDefaultMergeMethod, + mergeCommitAllowed: repository.mergeCommitAllowed, + rebaseMergeAllowed: repository.rebaseMergeAllowed, + squashMergeAllowed: repository.squashMergeAllowed + }) + : undefined + const value: GitHubRepositoryMergeMetadata = { + mergeQueueRequired: branchName ? Boolean(repository?.mergeQueue) : null, + ...(mergeMethodSettings ? { mergeMethodSettings } : {}) + } + cacheRepositoryMergeMetadata(cacheKey, value, MERGE_QUEUE_CACHE_TTL_MS) return value } catch { // Why: failed merge-queue probes should stay conservative without // retrying GraphQL on every status poll while GitHub/network is unhappy. - cacheMergeQueueRequired(cacheKey, null, MERGE_QUEUE_UNKNOWN_CACHE_TTL_MS) - return null + const value: GitHubRepositoryMergeMetadata = { mergeQueueRequired: null } + cacheRepositoryMergeMetadata(cacheKey, value, MERGE_QUEUE_UNKNOWN_CACHE_TTL_MS) + return value } } @@ -1828,11 +1880,15 @@ async function hydratePullRequestLookupData( const normalized = normalizePullRequestLookupData(data) const hasRichMergeFields = 'reviewDecision' in data || 'mergeStateStatus' in data || 'autoMergeRequest' in data + const mergeMetadata = hasRichMergeFields + ? await detectRepositoryMergeMetadata(ownerRepo, normalized.baseRefName, ghOptions) + : undefined return { ...normalized, - mergeQueueRequired: hasRichMergeFields - ? await detectMergeQueueRequired(ownerRepo, normalized.baseRefName, ghOptions) - : undefined + ...(mergeMetadata ? { mergeQueueRequired: mergeMetadata.mergeQueueRequired } : {}), + ...(mergeMetadata?.mergeMethodSettings + ? { mergeMethodSettings: mergeMetadata.mergeMethodSettings } + : {}) } } @@ -2226,6 +2282,9 @@ export async function getPRForBranchOutcome( ...(data.mergeQueueRequired !== undefined ? { mergeQueueRequired: data.mergeQueueRequired } : {}), + ...(data.mergeMethodSettings !== undefined + ? { mergeMethodSettings: data.mergeMethodSettings } + : {}), ...(data.mergeStateStatus !== undefined ? { mergeStateStatus: data.mergeStateStatus } : {}), headSha: data.headRefOid, prRepo: dataRepo ?? undefined, diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index 9c3929a58..dbfb0eacd 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -114,6 +114,10 @@ import { normalizeGitHubReviewerLogins } from '@/components/github-pr-reviewer-display' import { presentGitHubPRMergeState } from '@/components/github-pr-merge-state' +import { + GITHUB_PR_MERGE_METHOD_LABELS, + resolveGitHubPRMergeMethods +} from '../../../shared/github-pr-merge-methods' import { AGENT_CATALOG } from '@/lib/agent-catalog' import { filterEnabledTuiAgents } from '../../../shared/tui-agent-selection' import { getConnectionId } from '@/lib/connection-context' @@ -135,6 +139,7 @@ import type { GitHubWorkItemDetails, GitHubAssignableUser, GitHubReaction, + GitHubPRMergeMethod, GitBranchChangeEntry, GitDiffResult, PRCheckDetail, @@ -2771,6 +2776,7 @@ function PRActionsPanel({ const confirm = useConfirmationDialog() const actionItem = { ...item, state: localState } const mergePresentation = presentGitHubPRMergeState(actionItem) + const mergeMethods = resolveGitHubPRMergeMethods(actionItem.mergeMethodSettings) const canMutateState = localState !== 'merged' && (!!repoPath || !!projectOrigin) const nextState: 'open' | 'closed' = localState === 'closed' ? 'open' : 'closed' const mergeDisabled = !repoPath || mergePending || !mergePresentation.directMergeAvailable @@ -2832,12 +2838,11 @@ function PRActionsPanel({ } } - const handleMerge = async (method: 'merge' | 'squash' | 'rebase'): Promise => { + const handleMerge = async (method: GitHubPRMergeMethod): Promise => { if (!repoPath || mergeDisabled) { return } - const label = - method === 'squash' ? 'Squash and merge' : method === 'rebase' ? 'Rebase and merge' : 'Merge' + const label = GITHUB_PR_MERGE_METHOD_LABELS[method] const confirmed = await confirm({ title: `${label} PR #${item.number}?`, description: 'This will update the pull request on GitHub.', @@ -2925,7 +2930,9 @@ function PRActionsPanel({ )} {mergePresentation.autoMergeAction?.label ?? - (mergePresentation.directMergeAvailable ? 'Merge' : mergePresentation.label)} + (mergePresentation.directMergeAvailable + ? mergeMethods.defaultLabel + : mergePresentation.label)} @@ -2945,18 +2952,16 @@ function PRActionsPanel({ )} {mergePresentation.autoMergeAction && } - void handleMerge('squash')}> - - Squash and merge - - void handleMerge('merge')}> - - Create merge commit - - void handleMerge('rebase')}> - - Rebase and merge - + {mergeMethods.methods.map(({ method, label }) => ( + void handleMerge(method)} + > + + {label} + + ))} window.api.shell.openUrl(item.url)}> Open GitHub merge box diff --git a/src/renderer/src/components/PullRequestPage.tsx b/src/renderer/src/components/PullRequestPage.tsx index 80ba67590..18dac2c4d 100644 --- a/src/renderer/src/components/PullRequestPage.tsx +++ b/src/renderer/src/components/PullRequestPage.tsx @@ -112,6 +112,10 @@ import { normalizeGitHubReviewerLogins } from '@/components/github-pr-reviewer-display' import { presentGitHubPRMergeState } from '@/components/github-pr-merge-state' +import { + GITHUB_PR_MERGE_METHOD_LABELS, + resolveGitHubPRMergeMethods +} from '../../../shared/github-pr-merge-methods' import { AGENT_CATALOG } from '@/lib/agent-catalog' import { filterEnabledTuiAgents } from '../../../shared/tui-agent-selection' import { getConnectionId } from '@/lib/connection-context' @@ -132,6 +136,7 @@ import type { GitHubWorkItemDetails, GitHubAssignableUser, GitHubReaction, + GitHubPRMergeMethod, GitBranchChangeEntry, GitDiffResult, PRCheckDetail, @@ -3029,6 +3034,7 @@ function PRActionsPanel({ const confirm = useConfirmationDialog() const actionItem = { ...item, state: localState } const mergePresentation = presentGitHubPRMergeState(actionItem) + const mergeMethods = resolveGitHubPRMergeMethods(actionItem.mergeMethodSettings) const canMutateState = localState !== 'merged' && (!!repoPath || !!projectOrigin) const nextState: 'open' | 'closed' = localState === 'closed' ? 'open' : 'closed' const mergeDisabled = !repoPath || mergePending || !mergePresentation.directMergeAvailable @@ -3090,12 +3096,11 @@ function PRActionsPanel({ } } - const handleMerge = async (method: 'merge' | 'squash' | 'rebase'): Promise => { + const handleMerge = async (method: GitHubPRMergeMethod): Promise => { if (!repoPath || mergeDisabled) { return } - const label = - method === 'squash' ? 'Squash and merge' : method === 'rebase' ? 'Rebase and merge' : 'Merge' + const label = GITHUB_PR_MERGE_METHOD_LABELS[method] const confirmed = await confirm({ title: `${label} PR #${item.number}?`, description: 'This will update the pull request on GitHub.', @@ -3183,7 +3188,9 @@ function PRActionsPanel({ )} {mergePresentation.autoMergeAction?.label ?? - (mergePresentation.directMergeAvailable ? 'Merge' : mergePresentation.label)} + (mergePresentation.directMergeAvailable + ? mergeMethods.defaultLabel + : mergePresentation.label)} @@ -3203,18 +3210,16 @@ function PRActionsPanel({ )} {mergePresentation.autoMergeAction && } - void handleMerge('squash')}> - - Squash and merge - - void handleMerge('merge')}> - - Create merge commit - - void handleMerge('rebase')}> - - Rebase and merge - + {mergeMethods.methods.map(({ method, label }) => ( + void handleMerge(method)} + > + + {label} + + ))} window.api.shell.openUrl(item.url)}> Open GitHub merge box diff --git a/src/renderer/src/components/TaskPage.tsx b/src/renderer/src/components/TaskPage.tsx index a0fc77002..2b1559302 100644 --- a/src/renderer/src/components/TaskPage.tsx +++ b/src/renderer/src/components/TaskPage.tsx @@ -142,9 +142,14 @@ import { } from '@/components/task-page-cache-selectors' import { deriveTaskPagePRCheckSummary } from '@/components/task-page-pr-check-summary' import { presentGitHubPRMergeState } from '@/components/github-pr-merge-state' +import { + GITHUB_PR_MERGE_METHOD_LABELS, + resolveGitHubPRMergeMethods +} from '../../../shared/github-pr-merge-methods' import type { GitHubOwnerRepo, GitHubAssignableUser, + GitHubPRMergeMethod, GitHubWorkItem, GitLabTodo, GitLabWorkItem, @@ -1935,14 +1940,14 @@ function PRMergeCell({ return Issue } const mergePresentation = presentGitHubPRMergeState(item) + const mergeMethods = resolveGitHubPRMergeMethods(item.mergeMethodSettings) const mergeDisabled = !repo || merging || !mergePresentation.directMergeAvailable - const handleMerge = async (method: 'merge' | 'squash' | 'rebase'): Promise => { + const handleMerge = async (method: GitHubPRMergeMethod): Promise => { if (!repo || mergeDisabled) { return } - const label = - method === 'squash' ? 'Squash and merge' : method === 'rebase' ? 'Rebase and merge' : 'Merge' + const label = GITHUB_PR_MERGE_METHOD_LABELS[method] const confirmed = await confirm({ title: `${label} PR #${item.number}?`, description: 'This will update the pull request on GitHub.', @@ -2035,18 +2040,16 @@ function PRMergeCell({ )} {mergePresentation.autoMergeAction && } - void handleMerge('squash')}> - - Squash and merge - - void handleMerge('merge')}> - - Create merge commit - - void handleMerge('rebase')}> - - Rebase and merge - + {mergeMethods.methods.map(({ method, label }) => ( + void handleMerge(method)} + > + + {label} + + ))} window.api.shell.openUrl(item.url)}> Open GitHub merge box diff --git a/src/renderer/src/components/right-sidebar/HostedReviewActions.tsx b/src/renderer/src/components/right-sidebar/HostedReviewActions.tsx index bb698ceef..00e1aafa2 100644 --- a/src/renderer/src/components/right-sidebar/HostedReviewActions.tsx +++ b/src/renderer/src/components/right-sidebar/HostedReviewActions.tsx @@ -24,16 +24,10 @@ import { useConfirmationDialog } from '@/components/confirmation-dialog' import { presentGitHubPRMergeState } from '@/components/github-pr-merge-state' import type { HostedReviewInfo } from '../../../../shared/hosted-review' import type { PRInfo, Repo, Worktree } from '../../../../shared/types' +import type { GitHubPRMergeMethod } from '../../../../shared/types' +import { resolveGitHubPRMergeMethods } from '../../../../shared/github-pr-merge-methods' import { runWorktreeDelete } from '../sidebar/delete-worktree-flow' -const MERGE_METHODS = ['squash', 'merge', 'rebase'] as const - -const MERGE_LABELS: Record<(typeof MERGE_METHODS)[number], string> = { - squash: 'Squash and merge', - merge: 'Create a merge commit', - rebase: 'Rebase and merge' -} - type HostedReviewActionInfo = Pick< HostedReviewInfo, 'provider' | 'number' | 'state' | 'status' | 'mergeable' @@ -141,6 +135,11 @@ export default function HostedReviewActions({ mergeQueueRequired: review.mergeQueueRequired }) }, [githubPR, isGitLab, review]) + const mergeMethods = useMemo( + () => + resolveGitHubPRMergeMethods(isGitLab ? null : (githubPR?.mergeMethodSettings ?? null)), + [githubPR?.mergeMethodSettings, isGitLab] + ) const isUpdatingReviewState = stateUpdating !== null const primaryMergeDisabled = merging || @@ -151,7 +150,7 @@ export default function HostedReviewActions({ const menuDisabled = merging || isUpdatingReviewState const handleMerge = useCallback( - async (method: 'merge' | 'squash' | 'rebase' = 'squash') => { + async (method: GitHubPRMergeMethod = mergeMethods.defaultMethod) => { setMerging(true) setActionError(null) try { @@ -179,7 +178,15 @@ export default function HostedReviewActions({ setMerging(false) } }, - [githubPR?.prRepo, isGitLab, onRefreshReview, repo.id, repo.path, review.number] + [ + githubPR?.prRepo, + isGitLab, + mergeMethods.defaultMethod, + onRefreshReview, + repo.id, + repo.path, + review.number + ] ) const handleAutoMerge = useCallback(async () => { @@ -312,7 +319,7 @@ export default function HostedReviewActions({ onClick={() => mergePresentation.autoMergeAction && !mergePresentation.directMergeAvailable ? void handleAutoMerge() - : void handleMerge('squash') + : void handleMerge(mergeMethods.defaultMethod) } disabled={primaryMergeDisabled} > @@ -324,7 +331,7 @@ export default function HostedReviewActions({ {merging ? 'Working...' : mergePresentation.directMergeAvailable - ? 'Squash and merge' + ? mergeMethods.defaultLabel : (mergePresentation.autoMergeAction?.label ?? mergePresentation.label)} @@ -369,14 +376,14 @@ export default function HostedReviewActions({ )} - {MERGE_METHODS.map((method) => ( + {mergeMethods.methods.map(({ method, label }) => ( void handleMerge(method)} > - {MERGE_LABELS[method]} + {label} ))} diff --git a/src/shared/github-pr-merge-methods.test.ts b/src/shared/github-pr-merge-methods.test.ts new file mode 100644 index 000000000..f4705d6b0 --- /dev/null +++ b/src/shared/github-pr-merge-methods.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' +import { + normalizeGitHubPRMergeMethodSettings, + resolveGitHubPRMergeMethods +} from './github-pr-merge-methods' + +describe('GitHub PR merge methods', () => { + it('keeps the historical squash-first fallback when repository metadata is missing', () => { + expect(resolveGitHubPRMergeMethods()).toEqual({ + defaultMethod: 'squash', + defaultLabel: 'Squash and merge', + methods: [ + { method: 'squash', label: 'Squash and merge' }, + { method: 'merge', label: 'Create merge commit' }, + { method: 'rebase', label: 'Rebase and merge' } + ] + }) + }) + + it('uses GitHub viewer defaults and hides methods disabled by the repository', () => { + const settings = normalizeGitHubPRMergeMethodSettings({ + defaultMethod: 'REBASE', + mergeCommitAllowed: false, + rebaseMergeAllowed: true, + squashMergeAllowed: true + }) + + expect(resolveGitHubPRMergeMethods(settings)).toEqual({ + defaultMethod: 'rebase', + defaultLabel: 'Rebase and merge', + methods: [ + { method: 'rebase', label: 'Rebase and merge' }, + { method: 'squash', label: 'Squash and merge' } + ] + }) + }) + + it('falls back to an allowed method when GitHub returns a disabled default', () => { + const settings = normalizeGitHubPRMergeMethodSettings({ + defaultMethod: 'SQUASH', + mergeCommitAllowed: true, + rebaseMergeAllowed: false, + squashMergeAllowed: false + }) + + expect(settings?.defaultMethod).toBe('merge') + expect(resolveGitHubPRMergeMethods(settings).methods).toEqual([ + { method: 'merge', label: 'Create merge commit' } + ]) + }) +}) diff --git a/src/shared/github-pr-merge-methods.ts b/src/shared/github-pr-merge-methods.ts new file mode 100644 index 000000000..a9372b461 --- /dev/null +++ b/src/shared/github-pr-merge-methods.ts @@ -0,0 +1,93 @@ +import type { GitHubPRMergeMethod, GitHubPRMergeMethodSettings } from './types' + +export const GITHUB_PR_MERGE_METHODS = ['squash', 'merge', 'rebase'] as const + +export const GITHUB_PR_MERGE_METHOD_LABELS: Record = { + squash: 'Squash and merge', + merge: 'Create merge commit', + rebase: 'Rebase and merge' +} + +export type GitHubPRMergeMethodOption = { + method: GitHubPRMergeMethod + label: string +} + +export type GitHubPRMergeMethodPresentation = { + defaultMethod: GitHubPRMergeMethod + defaultLabel: string + methods: GitHubPRMergeMethodOption[] +} + +function allMethodsAllowed(): Record { + return { + squash: true, + merge: true, + rebase: true + } +} + +export function mapGitHubDefaultMergeMethod(value: unknown): GitHubPRMergeMethod | null { + switch (typeof value === 'string' ? value.toUpperCase() : '') { + case 'MERGE': + return 'merge' + case 'SQUASH': + return 'squash' + case 'REBASE': + return 'rebase' + default: + return null + } +} + +export function normalizeGitHubPRMergeMethodSettings(args: { + defaultMethod: unknown + mergeCommitAllowed: unknown + rebaseMergeAllowed: unknown + squashMergeAllowed: unknown +}): GitHubPRMergeMethodSettings | undefined { + const allowedMethods = { + squash: args.squashMergeAllowed === true, + merge: args.mergeCommitAllowed === true, + rebase: args.rebaseMergeAllowed === true + } + const defaultMethod = mapGitHubDefaultMergeMethod(args.defaultMethod) + const firstAllowedMethod = GITHUB_PR_MERGE_METHODS.find((method) => allowedMethods[method]) + const resolvedDefault = + defaultMethod && allowedMethods[defaultMethod] + ? defaultMethod + : (firstAllowedMethod ?? defaultMethod) + if (!resolvedDefault) { + return undefined + } + return { + defaultMethod: resolvedDefault, + allowedMethods + } +} + +export function resolveGitHubPRMergeMethods( + settings?: GitHubPRMergeMethodSettings | null +): GitHubPRMergeMethodPresentation { + const allowedMethods = settings?.allowedMethods ?? allMethodsAllowed() + const firstAllowedMethod = GITHUB_PR_MERGE_METHODS.find((method) => allowedMethods[method]) + const defaultMethod = + settings?.defaultMethod && allowedMethods[settings.defaultMethod] + ? settings.defaultMethod + : (firstAllowedMethod ?? 'squash') + const orderedMethods = [ + defaultMethod, + ...GITHUB_PR_MERGE_METHODS.filter((method) => method !== defaultMethod) + ].filter((method) => allowedMethods[method]) + const methods = (orderedMethods.length > 0 ? orderedMethods : GITHUB_PR_MERGE_METHODS).map( + (method) => ({ + method, + label: GITHUB_PR_MERGE_METHOD_LABELS[method] + }) + ) + return { + defaultMethod, + defaultLabel: GITHUB_PR_MERGE_METHOD_LABELS[defaultMethod], + methods + } +} diff --git a/src/shared/types.ts b/src/shared/types.ts index 1ec118400..9cd5a2a67 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -719,6 +719,13 @@ export type PRConflictSummary = { export type GitHubRepositoryIdentity = { owner: string; repo: string } +export type GitHubPRMergeMethod = 'merge' | 'squash' | 'rebase' + +export type GitHubPRMergeMethodSettings = { + defaultMethod: GitHubPRMergeMethod + allowedMethods: Record +} + export type PRInfo = { number: number title: string @@ -730,6 +737,7 @@ export type PRInfo = { reviewDecision?: PRReviewDecision | null autoMergeEnabled?: boolean mergeQueueRequired?: boolean | null + mergeMethodSettings?: GitHubPRMergeMethodSettings mergeStateStatus?: string | null // Why: check-runs are keyed by the PR head commit, not the mutable branch name. // Keeping the head SHA in cached PR metadata lets the checks panel poll the @@ -998,6 +1006,7 @@ export type GitHubWorkItem = { mergeable?: PRMergeableState autoMergeEnabled?: boolean mergeQueueRequired?: boolean | null + mergeMethodSettings?: GitHubPRMergeMethodSettings mergeStateStatus?: string | null maintainerCanModify?: boolean // Why: true when a PR's head lives on a fork (headRepositoryOwner !== selected repo owner).