diff --git a/backend/src/services/git/GitService.ts b/backend/src/services/git/GitService.ts index fabc102c..95038948 100644 --- a/backend/src/services/git/GitService.ts +++ b/backend/src/services/git/GitService.ts @@ -965,22 +965,32 @@ export class GitService { throw new GitOperationError('BRANCH_CHECKED_OUT', `Cannot delete branch '${name}' because it is currently checked out`) } - let upstreamRemote: string | null = null - let upstreamBranch: string | null = null + let remoteToDelete: string | null = null if (options.deleteRemote) { + const [remote, merge] = await Promise.all([ + this.readBranchConfig(fullPath, name, 'remote', env), + this.readBranchConfig(fullPath, name, 'merge', env), + ]) + if (remote && remote !== '.' && merge?.startsWith('refs/heads/')) { + remoteToDelete = remote + const upstreamBranch = merge.slice('refs/heads/'.length) + if (upstreamBranch !== name) { + throw new GitOperationError( + 'REMOTE_BRANCH_MISMATCH', + `Branch '${name}' was kept because its upstream is '${remote}/${upstreamBranch}', not '${remote}/${name}'. Delete it without deleting the remote branch.` + ) + } + } + } + + if (remoteToDelete && !options.force) { try { - const upstream = await executeCommand( - ['git', '-C', fullPath, 'rev-parse', '--abbrev-ref', `${name}@{upstream}`], + await executeCommand( + ['git', '-C', fullPath, 'merge-base', '--is-ancestor', `refs/heads/${name}`, 'HEAD'], { env, silent: true } ) - const separator = upstream.trim().indexOf('/') - if (separator > 0) { - upstreamRemote = upstream.trim().slice(0, separator) - upstreamBranch = upstream.trim().slice(separator + 1) - } } catch { - upstreamRemote = null - upstreamBranch = null + throw new GitOperationError('BRANCH_NOT_MERGED', `Branch '${name}' was kept because it has unmerged commits.`) } } @@ -995,11 +1005,12 @@ export class GitService { } let remoteDeleted = false - if (upstreamRemote && upstreamBranch) { + if (remoteToDelete) { + const remote = remoteToDelete try { await this.withRemoteAuth(target, async (remoteEnv) => { await executeCommand( - ['git', '-C', fullPath, 'push', upstreamRemote, '--delete', upstreamBranch], + ['git', '-C', fullPath, 'push', remote, '--delete', name], { env: remoteEnv } ) }) @@ -1012,6 +1023,24 @@ export class GitService { return { remoteDeleted } } + private async readBranchConfig( + repoPath: string, + branch: string, + key: string, + env: Record + ): Promise { + try { + const output = await executeCommand( + ['git', '-C', repoPath, 'config', '--get', `branch.${branch}.${key}`], + { env, silent: true } + ) + const value = output.trim() + return value.length > 0 ? value : null + } catch { + return null + } + } + async deleteBranch( repoId: number, request: { name: string; force: boolean; deleteRemote: boolean }, @@ -1100,11 +1129,25 @@ export class GitService { throw new GitOperationError('UNCOMMITTED_CHANGES', 'You have uncommitted changes. Commit or stash them first.') } - const countOutput = await executeCommand( - ['git', '-C', sourcePath, 'rev-list', '--count', `${targetRef}..${sourceRef}`], - { env: sourceEnv, silent: true } - ) - const integratedCommits = Number.parseInt(countOutput.trim(), 10) + let integratedCommits: number + let cherryPickCommits: string[] = [] + if (request.strategy === 'cherry-pick') { + const commitsOutput = await executeCommand( + ['git', '-C', sourcePath, 'rev-list', '--reverse', '--right-only', '--cherry-pick', '--no-merges', `${targetRef}...${sourceRef}`], + { env: sourceEnv, silent: true } + ) + cherryPickCommits = commitsOutput + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0) + integratedCommits = cherryPickCommits.length + } else { + const countOutput = await executeCommand( + ['git', '-C', sourcePath, 'rev-list', '--count', `${targetRef}..${sourceRef}`], + { env: sourceEnv, silent: true } + ) + integratedCommits = Number.parseInt(countOutput.trim(), 10) + } if (!integratedCommits) { throw new GitOperationError('INTEGRATE_NOTHING_TO_INTEGRATE', 'Nothing to integrate') } @@ -1115,7 +1158,7 @@ export class GitService { } const args = request.strategy === 'cherry-pick' - ? ['git', '-C', targetPath, 'cherry-pick', `${targetRef}..${sourceRef}`] + ? ['git', '-C', targetPath, 'cherry-pick', ...cherryPickCommits] : ['git', '-C', targetPath, 'merge', '--no-ff', '--no-edit', sourceRef] try { diff --git a/backend/src/utils/git-errors.ts b/backend/src/utils/git-errors.ts index 3f427cde..618545b8 100644 --- a/backend/src/utils/git-errors.ts +++ b/backend/src/utils/git-errors.ts @@ -183,6 +183,12 @@ const ERROR_PATTERNS: ErrorPattern[] = [ /is not fully merged/i, ], }, + { + code: 'REMOTE_BRANCH_MISMATCH', + summary: "The branch's upstream has a different name, so its remote branch was not deleted.", + statusCode: 409, + patterns: [], + }, { code: 'STASH_CHANGED', summary: 'The stash list changed. Refresh and try again.', diff --git a/backend/test/services/git/GitService.real.test.ts b/backend/test/services/git/GitService.real.test.ts index b2cf1788..77c19d88 100644 --- a/backend/test/services/git/GitService.real.test.ts +++ b/backend/test/services/git/GitService.real.test.ts @@ -305,6 +305,7 @@ describe('GitService real git', () => { cloneOrigin(origin, repoPath) git(['checkout', '-b', 'feature', 'origin/feature'], repoPath) git(['checkout', 'main'], repoPath) + git(['merge', 'feature'], repoPath) const repo = registerClone(origin, repoPath) const result = await service.deleteBranch(repo.id, { name: 'feature', force: false, deleteRemote: true }, db) @@ -314,6 +315,71 @@ describe('GitService real git', () => { expect(git(['branch', '--list', 'feature'], origin)).toBe('') }) + it('refuses to delete a remote branch whose upstream has a different name', async () => { + const origin = path.join(workspaceRoot, uniqueName('delete-mismatch-origin.git')) + const work = path.join(workspaceRoot, uniqueName('delete-mismatch-work')) + createOrigin(origin, work) + const repoPath = path.join(reposPath, uniqueName('delete-mismatch-clone')) + cloneOrigin(origin, repoPath) + git(['checkout', '-b', 'myfix', 'origin/main'], repoPath) + git(['checkout', 'main'], repoPath) + const repo = registerClone(origin, repoPath) + + const error = await service + .deleteBranch(repo.id, { name: 'myfix', force: true, deleteRemote: true }, db) + .catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(GitOperationError) + expect(parseGitError(error).code).toBe('REMOTE_BRANCH_MISMATCH') + expect(git(['branch', '--list', 'myfix'], repoPath)).toContain('myfix') + expect(git(['branch', '--list', 'main'], origin)).toContain('main') + }) + + it('keeps a pushed unmerged branch and its remote without force', async () => { + const origin = path.join(workspaceRoot, uniqueName('delete-pushed-unmerged-origin.git')) + const work = path.join(workspaceRoot, uniqueName('delete-pushed-unmerged-work')) + createOrigin(origin, work) + const repoPath = path.join(reposPath, uniqueName('delete-pushed-unmerged-clone')) + cloneOrigin(origin, repoPath) + git(['checkout', '-b', 'feature'], repoPath) + writeFileSync(path.join(repoPath, 'feature.txt'), 'feature\n') + git(['add', 'feature.txt'], repoPath) + git(['commit', '-m', 'feature work'], repoPath) + git(['push', '-u', 'origin', 'feature'], repoPath) + git(['checkout', 'main'], repoPath) + const repo = registerClone(origin, repoPath) + + const error = await service + .deleteBranch(repo.id, { name: 'feature', force: false, deleteRemote: true }, db) + .catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(GitOperationError) + expect(parseGitError(error).code).toBe('BRANCH_NOT_MERGED') + expect(git(['branch', '--list', 'feature'], repoPath)).toContain('feature') + expect(git(['branch', '--list', 'feature'], origin)).toContain('feature') + }) + + it('force deletes a pushed unmerged branch and its remote', async () => { + const origin = path.join(workspaceRoot, uniqueName('delete-pushed-force-origin.git')) + const work = path.join(workspaceRoot, uniqueName('delete-pushed-force-work')) + createOrigin(origin, work) + const repoPath = path.join(reposPath, uniqueName('delete-pushed-force-clone')) + cloneOrigin(origin, repoPath) + git(['checkout', '-b', 'feature'], repoPath) + writeFileSync(path.join(repoPath, 'feature.txt'), 'feature\n') + git(['add', 'feature.txt'], repoPath) + git(['commit', '-m', 'feature work'], repoPath) + git(['push', '-u', 'origin', 'feature'], repoPath) + git(['checkout', 'main'], repoPath) + const repo = registerClone(origin, repoPath) + + const result = await service.deleteBranch(repo.id, { name: 'feature', force: true, deleteRemote: true }, db) + + expect(result.remoteDeleted).toBe(true) + expect(git(['branch', '--list', 'feature'], repoPath)).toBe('') + expect(git(['branch', '--list', 'feature'], origin)).toBe('') + }) + it('reports remoteDeleted false when the branch has no upstream', async () => { const origin = path.join(workspaceRoot, uniqueName('delete-no-upstream-origin.git')) const work = path.join(workspaceRoot, uniqueName('delete-no-upstream-work')) @@ -760,6 +826,32 @@ describe('GitService real git', () => { expect(git(['log', '-1', '--format=%P'], basePath).split(' ')).toHaveLength(1) }) + it('skips already-applied commits when cherry-picking the same branch twice', async () => { + const { base, basePath, worktree, worktreePath } = await setupWorktreeRepo('integrate-cherry-twice') + writeFileSync(path.join(worktreePath, 'a.txt'), 'a\n') + git(['add', 'a.txt'], worktreePath) + git(['commit', '-m', 'add a'], worktreePath) + + const first = await service.integrateBranch(worktree.id, { targetBranch: 'main', strategy: 'cherry-pick' }, db) + expect(first.integratedCommits).toBe(1) + + const error = await service + .integrateBranch(worktree.id, { targetBranch: 'main', strategy: 'cherry-pick' }, db) + .catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(GitOperationError) + expect(parseGitError(error).code).toBe('INTEGRATE_NOTHING_TO_INTEGRATE') + expect((await service.getStatus(base.id, db)).operation).toBeNull() + + writeFileSync(path.join(worktreePath, 'b.txt'), 'b\n') + git(['add', 'b.txt'], worktreePath) + git(['commit', '-m', 'add b'], worktreePath) + + const third = await service.integrateBranch(worktree.id, { targetBranch: 'main', strategy: 'cherry-pick' }, db) + expect(third.integratedCommits).toBe(1) + expect(git(['log', '-2', '--format=%s'], basePath).split('\n')).toEqual(['add b', 'add a']) + }) + it('rejects a target with tracked changes', async () => { const { basePath, worktree, worktreePath } = await setupWorktreeRepo('integrate-dirty') writeFileSync(path.join(basePath, 'tracked.txt'), 'base\n') @@ -1063,6 +1155,7 @@ describe('GitService real git', () => { it('also deletes the pushed origin branch with local-and-remote', async () => { const { origin, basePath, worktree, worktreePath } = await setupDeleteWorktree('delete-wt-remote') pushFeatureWithUpstream(worktreePath) + mergeFeatureIntoMain(basePath) const res = await createDeleteApp().request(`/repos/${worktree.id}`, { method: 'DELETE', @@ -1080,6 +1173,30 @@ describe('GitService real git', () => { expect(git(['branch', '--list', 'feature'], origin)).toBe('') }) + it('keeps an unmerged pushed branch and its remote with local-and-remote', async () => { + const { origin, basePath, worktree, worktreePath } = await setupDeleteWorktree('delete-wt-remote-unmerged') + pushFeatureWithUpstream(worktreePath) + + const res = await createDeleteApp().request(`/repos/${worktree.id}`, { + method: 'DELETE', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ deleteBranch: 'local-and-remote' }), + }) + + expect(res.status).toBe(200) + const data = await res.json() as { success: boolean; branch?: { name: string; deleted: boolean; remoteDeleted: boolean; error?: string } } + expect(data.success).toBe(true) + expect(data.branch).toEqual({ + name: 'feature', + deleted: false, + remoteDeleted: false, + error: "Branch 'feature' was kept because it has unmerged commits.", + }) + expect(existsSync(worktreePath)).toBe(false) + expect(git(['branch', '--list', 'feature'], basePath)).toContain('feature') + expect(git(['branch', '--list', 'feature'], origin)).toContain('feature') + }) + it('deletes a local worktree without a repoUrl together with its branch', async () => { const { basePath, worktree, worktreePath } = await setupLocalWorktree('delete-wt-local-no-url') mergeFeatureIntoMain(basePath) @@ -1103,6 +1220,7 @@ describe('GitService real git', () => { it('reports local deletion as complete when the remote rejects the branch deletion', async () => { const { origin, basePath, worktree, worktreePath } = await setupDeleteWorktree('delete-wt-reject') pushFeatureWithUpstream(worktreePath) + mergeFeatureIntoMain(basePath) rejectPushes(origin) const res = await createDeleteApp().request(`/repos/${worktree.id}`, { diff --git a/docs/features/git.md b/docs/features/git.md index b64c9e13..e587f8ae 100644 --- a/docs/features/git.md +++ b/docs/features/git.md @@ -55,7 +55,7 @@ Worktrees share the same git history but have independent working directories. T From a worktree's Branches tab, click **Integrate** to bring its commits into another branch: 1. Choose the target branch. It must be checked out cleanly in another managed worktree, with no uncommitted changes or operation already in progress. -2. Choose a strategy: **Merge commit** integrates all commits with a merge commit, while **Cherry-pick commits** replays each commit onto the target. +2. Choose a strategy: **Merge commit** integrates all commits with a merge commit, while **Cherry-pick commits** replays each commit onto the target. Cherry-pick integration skips commits already applied to the target and skips merge commits. 3. Click **Integrate**. If the target stops on conflicts, the operation banner appears in the dialog so you can resolve, continue, or abort the integration. @@ -68,7 +68,9 @@ Deleting a worktree offers three branch options: - **Delete local branch** - Remove the branch from the parent repository. - **Delete local and remote branch** - Also delete the branch from origin. -**Delete local branch** and **Delete local and remote branch** use a safe delete: if the branch has unmerged commits it is kept (and the remote branch is not deleted either), and a warning names it. Force-delete it from the Branches tab if intended. +**Delete local branch** and **Delete local and remote branch** use a safe delete: if the branch has unmerged commits it is kept, and a warning names it. Force-delete it from the Branches tab if intended. + +The remote branch is deleted only when the branch's upstream has the same name. If the upstream has a different name, nothing is deleted and the reason is shown. Without force, deleting the remote branch also requires the branch to be merged into the checked-out branch. ## Source Control Panel @@ -98,7 +100,7 @@ Access comprehensive git operations via the source control button. - Create new branches from current HEAD - Switch branches (checks out the branch) - Rename a local branch from its actions menu. Renaming also updates the base branch of schedules in every checkout of the same git repository that used the old name. A worktree's folder keeps the old branch name; `ocm` mirroring looks for a folder named after the new branch, so mirroring the renamed branch fails while that worktree exists. -- Delete local branches, optionally force-deleting an unmerged branch and, when the branch tracks a remote, also deleting the remote branch. The current branch and branches checked out in another worktree cannot be deleted. +- Delete local branches, optionally force-deleting an unmerged branch and, when the branch's upstream has the same name, also deleting the remote branch. The current branch and branches checked out in another worktree cannot be deleted. ![Branches Tab](../images/git/git-branch.png){ .phone } diff --git a/frontend/src/components/repo/CreateWorktreeDialog.test.tsx b/frontend/src/components/repo/CreateWorktreeDialog.test.tsx index 604e9cfc..a5f46e2a 100644 --- a/frontend/src/components/repo/CreateWorktreeDialog.test.tsx +++ b/frontend/src/components/repo/CreateWorktreeDialog.test.tsx @@ -130,6 +130,24 @@ describe('CreateWorktreeDialog', () => { }) }) + it('submits a remote-only base branch qualified with origin', async () => { + const user = userEvent.setup() + renderDialog() + + await user.type(screen.getByPlaceholderText('feature/my-branch'), 'my-new-branch') + await user.click(screen.getByRole('combobox')) + await user.click(screen.getByRole('option', { name: /release/ })) + await user.click(screen.getByRole('button', { name: 'Create Worktree' })) + + await waitFor(() => expect(createRepo).toHaveBeenCalledTimes(1)) + expect(createRepo).toHaveBeenCalledWith({ + repoUrl, + branch: 'my-new-branch', + useWorktree: true, + baseBranch: 'origin/release', + }) + }) + it('prompts to use existing mode when a new branch name already exists', async () => { const user = userEvent.setup() renderDialog() diff --git a/frontend/src/components/repo/CreateWorktreeDialog.tsx b/frontend/src/components/repo/CreateWorktreeDialog.tsx index af858655..af0566dd 100644 --- a/frontend/src/components/repo/CreateWorktreeDialog.tsx +++ b/frontend/src/components/repo/CreateWorktreeDialog.tsx @@ -240,7 +240,7 @@ export function CreateWorktreeDialog({ )} {remoteBranches.map((branch) => ( - +
{branch.shortName} diff --git a/frontend/src/components/repo/RepoList.tsx b/frontend/src/components/repo/RepoList.tsx index 60fd6110..53aaaf9d 100644 --- a/frontend/src/components/repo/RepoList.tsx +++ b/frontend/src/components/repo/RepoList.tsx @@ -33,7 +33,7 @@ import { ASSISTANT_REPO_ID } from "@opencode-manager/shared/utils" const DELETE_BRANCH_OPTIONS: Array> = [ { value: 'none', label: 'Keep branch', description: 'Leave the branch in the parent repository.' }, { value: 'local', label: 'Delete local branch', description: 'Remove the branch from the parent repository.' }, - { value: 'local-and-remote', label: 'Delete local and remote branch', description: 'Also delete the branch from origin.' }, + { value: 'local-and-remote', label: 'Delete local and remote branch', description: 'Also delete its remote branch when it has the same name and is merged.' }, ] interface RepoCardWrapperProps { diff --git a/frontend/src/components/source-control/BranchesTab.test.tsx b/frontend/src/components/source-control/BranchesTab.test.tsx index ebab7023..d1fa416e 100644 --- a/frontend/src/components/source-control/BranchesTab.test.tsx +++ b/frontend/src/components/source-control/BranchesTab.test.tsx @@ -72,4 +72,21 @@ describe('BranchesTab', () => { expect(screen.getByRole('textbox', { name: 'New name for branch feature' })).toBeInTheDocument() }) + + it('shows the upstream branch name in the delete dialog', async () => { + vi.mocked(listBranches).mockResolvedValue({ + branches: [ + { name: 'main', type: 'local', current: true }, + { name: 'feature', type: 'local', current: false, upstream: 'origin/feature' }, + ], + status: { ahead: 0, behind: 0 }, + }) + const user = userEvent.setup() + render(, { wrapper: createWrapper() }) + + await user.click(await screen.findByRole('button', { name: 'Actions for feature' })) + await user.click(await screen.findByRole('menuitem', { name: 'Delete' })) + + expect(await screen.findByText('origin/feature')).toBeInTheDocument() + }) }) diff --git a/frontend/src/components/source-control/BranchesTab.tsx b/frontend/src/components/source-control/BranchesTab.tsx index 187a41fd..1a185357 100644 --- a/frontend/src/components/source-control/BranchesTab.tsx +++ b/frontend/src/components/source-control/BranchesTab.tsx @@ -423,7 +423,8 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) { checked={deleteRemote} onCheckedChange={(checked) => setDeleteRemote(checked === true)} /> - Also delete remote branch + Also delete remote branch{' '} + {branchToDelete.upstream} )}
diff --git a/shared/src/types/errors.ts b/shared/src/types/errors.ts index e98ee1c5..30a374e3 100644 --- a/shared/src/types/errors.ts +++ b/shared/src/types/errors.ts @@ -14,6 +14,7 @@ export type GitErrorCode = | 'BRANCH_CHECKED_OUT' | 'BRANCH_IN_OTHER_WORKTREE' | 'BRANCH_NOT_MERGED' + | 'REMOTE_BRANCH_MISMATCH' | 'STASH_CHANGED' | 'UNCOMMITTED_CHANGES' | 'NO_OPERATION_IN_PROGRESS'