fix(worktree): add SSH preflight check for dirty worktree before archive hooks (#2912)

Co-authored-by: Orca <help@stably.ai>
Co-authored-by: Prethish-Complyance <prethish@complyance.io>
Co-authored-by: brennanb2025 <brennankbenson@gmail.com>
This commit is contained in:
Prethish Kumar
2026-05-27 13:32:52 -07:00
committed by GitHub
co-authored by Orca Prethish-Complyance brennanb2025
parent 8014516253
commit 3c59c019fc
7 changed files with 202 additions and 6 deletions
+133 -3
View File
@@ -2779,6 +2779,10 @@ describe('registerWorktreeHandlers', () => {
removeWorktree: vi.fn().mockImplementation(async () => {
callOrder.push('remove')
}),
worktreeIsClean: vi.fn().mockImplementation(async () => {
callOrder.push('preflight')
return { clean: true }
}),
execNonInteractive: vi.fn().mockImplementation(async () => {
callOrder.push('archive')
return { stdout: '', stderr: '', exitCode: 0, timedOut: false }
@@ -2813,10 +2817,130 @@ describe('registerWorktreeHandlers', () => {
})
)
expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', undefined)
expect(callOrder).toEqual(['archive', 'remove'])
expect(callOrder).toEqual(['archive', 'preflight', 'remove'])
expect(runHookMock).not.toHaveBeenCalled()
})
it('runs SSH archive hooks before failing dirty non-force removal', async () => {
const repo = {
id: 'repo-ssh',
path: '/remote/repo',
displayName: 'ssh',
badgeColor: '#000',
addedAt: 0,
connectionId: 'conn-1',
worktreeBaseRef: null
}
const callOrder: string[] = []
const provider = {
listWorktrees: vi.fn().mockResolvedValue([
{
path: '/remote/repo',
head: 'main',
branch: 'main',
isBare: false,
isMainWorktree: true
},
{
path: '/remote/feature-wt',
head: 'feature',
branch: 'feature',
isBare: false,
isMainWorktree: false
}
]),
removeWorktree: vi.fn().mockImplementation(async () => {
callOrder.push('remove')
}),
worktreeIsClean: vi.fn().mockImplementation(async () => {
callOrder.push('preflight')
return { clean: false, stdout: ' M src/file.ts\n?? scratch.txt\n' }
}),
execNonInteractive: vi.fn().mockImplementation(async () => {
callOrder.push('archive')
return { stdout: '', stderr: '', exitCode: 0, timedOut: false }
})
}
const fsProvider = {
readFile: vi.fn().mockResolvedValue({
content: 'scripts:\n archive: echo archived\n',
isBinary: false
})
}
store.getRepos.mockReturnValue([repo])
store.getRepo.mockReturnValue(repo)
getSshGitProviderMock.mockReturnValue(provider)
getSshFilesystemProviderMock.mockReturnValue(fsProvider)
getEffectiveHooksFromConfigMock.mockReturnValue({ scripts: { archive: 'echo archived' } })
await expect(
handlers['worktrees:remove'](null, {
worktreeId: 'repo-ssh::/remote/feature-wt'
})
).rejects.toThrow('Worktree has uncommitted or untracked changes.')
expect(callOrder).toEqual(['archive', 'preflight'])
expect(provider.removeWorktree).not.toHaveBeenCalled()
expect(store.removeWorktreeMeta).not.toHaveBeenCalled()
})
it('skips SSH dirty preflight for force removal', async () => {
const repo = {
id: 'repo-ssh',
path: '/remote/repo',
displayName: 'ssh',
badgeColor: '#000',
addedAt: 0,
connectionId: 'conn-1',
worktreeBaseRef: null
}
const provider = {
listWorktrees: vi.fn().mockResolvedValue([
{
path: '/remote/repo',
head: 'main',
branch: 'main',
isBare: false,
isMainWorktree: true
},
{
path: '/remote/feature-wt',
head: 'feature',
branch: 'feature',
isBare: false,
isMainWorktree: false
}
]),
removeWorktree: vi.fn().mockResolvedValue(undefined),
worktreeIsClean: vi.fn(),
execNonInteractive: vi.fn().mockResolvedValue({
stdout: '',
stderr: '',
exitCode: 0,
timedOut: false
})
}
const fsProvider = {
readFile: vi.fn().mockResolvedValue({
content: 'scripts:\n archive: echo archived\n',
isBinary: false
})
}
store.getRepos.mockReturnValue([repo])
store.getRepo.mockReturnValue(repo)
getSshGitProviderMock.mockReturnValue(provider)
getSshFilesystemProviderMock.mockReturnValue(fsProvider)
getEffectiveHooksFromConfigMock.mockReturnValue({ scripts: { archive: 'echo archived' } })
await handlers['worktrees:remove'](null, {
worktreeId: 'repo-ssh::/remote/feature-wt',
force: true
})
expect(provider.worktreeIsClean).not.toHaveBeenCalled()
expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', true)
})
it('continues SSH worktree removal when the archive hook fails', async () => {
const repo = {
id: 'repo-ssh',
@@ -2846,6 +2970,7 @@ describe('registerWorktreeHandlers', () => {
}
]),
removeWorktree: vi.fn().mockResolvedValue(undefined),
worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }),
execNonInteractive: vi.fn().mockResolvedValue({
stdout: '',
stderr: 'cleanup failed',
@@ -2908,6 +3033,7 @@ describe('registerWorktreeHandlers', () => {
}
]),
removeWorktree: vi.fn().mockResolvedValue(undefined),
worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }),
execNonInteractive: vi.fn().mockRejectedValue(new Error('relay disconnected'))
}
const fsProvider = {
@@ -2964,6 +3090,7 @@ describe('registerWorktreeHandlers', () => {
}
]),
removeWorktree: vi.fn().mockResolvedValue(undefined),
worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }),
execNonInteractive: vi.fn().mockResolvedValue({
stdout: '',
stderr: '',
@@ -3029,6 +3156,7 @@ describe('registerWorktreeHandlers', () => {
}
]),
removeWorktree: vi.fn().mockResolvedValue(undefined),
worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }),
execNonInteractive: vi.fn()
}
const fsProvider = {
@@ -3310,7 +3438,8 @@ describe('registerWorktreeHandlers', () => {
isBare: false,
isMainWorktree: true
}
])
]),
worktreeIsClean: vi.fn().mockResolvedValue({ clean: true })
}
store.getRepo.mockReturnValue(repo)
store.getWorktreeMeta.mockReturnValue(
@@ -3354,7 +3483,8 @@ describe('registerWorktreeHandlers', () => {
isBare: false,
isMainWorktree: true
}
])
]),
worktreeIsClean: vi.fn().mockResolvedValue({ clean: true })
}
const fsProvider = {
lstat: vi.fn().mockResolvedValue({ type: 'symlink' }),
+13 -1
View File
@@ -1046,6 +1046,8 @@ export function registerWorktreeHandlers(
const canonicalWorktreePath = registeredWorktree.path
const deleteBranch = removedMeta?.preserveBranchOnDelete !== true
let shouldTearDownPtys = true
// Run archive hook before removal so teardown scripts still see the worktree directory.
const hooks = await getArchiveHooksForRemoval(repo)
if (hooks?.scripts.archive && !args.skipArchive) {
@@ -1061,6 +1063,17 @@ export function registerWorktreeHandlers(
}
if (repo.connectionId) {
// Why: SSH deletion mirrors the local flow: hooks run while the
// directory is intact, then the clean check guards destructive removal.
if (!args.force) {
const { clean, stdout } = await provider!.worktreeIsClean(canonicalWorktreePath)
if (!clean) {
const error = new Error('Worktree has uncommitted or untracked changes.')
;(error as Error & { stdout?: string }).stdout = stdout
throw error
}
}
await (deleteBranch
? provider!.removeWorktree(canonicalWorktreePath, args.force)
: provider!.removeWorktree(canonicalWorktreePath, args.force, { deleteBranch }))
@@ -1087,7 +1100,6 @@ export function registerWorktreeHandlers(
await removeWorktreeSymlinks(canonicalWorktreePath, repo.symlinkPaths)
}
let shouldTearDownPtys = true
try {
await assertWorktreeCleanForRemoval(canonicalWorktreePath, args.force ?? false)
} catch (error) {
+7
View File
@@ -402,6 +402,13 @@ export class SshGitProvider implements IGitProvider {
await this.mux.request('git.removeWorktree', { worktreePath, force, ...options })
}
async worktreeIsClean(worktreePath: string): Promise<{ clean: boolean; stdout?: string }> {
return (await this.mux.request('git.worktreeIsClean', { worktreePath })) as {
clean: boolean
stdout?: string
}
}
async exec(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> {
return (await this.mux.request('git.exec', { args, cwd })) as {
stdout: string
+1
View File
@@ -209,6 +209,7 @@ export type IGitProvider = {
isGitRepoAsync(dirPath: string): Promise<{ isRepo: boolean; rootPath: string | null }>
exec(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }>
getRemoteFileUrl(worktreePath: string, relativePath: string, line: number): Promise<string | null>
worktreeIsClean(worktreePath: string): Promise<{ clean: boolean; stdout?: string }>
}
// ─── Provider Registry ──────────────────────────────────────────────
+27 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { GitExec } from './git-handler-ops'
import { addWorktreeOp, removeWorktreeOp } from './git-handler-worktree-ops'
import { addWorktreeOp, removeWorktreeOp, worktreeIsCleanOp } from './git-handler-worktree-ops'
function worktreeList(...entries: { path: string; branch?: string }[]): string {
return entries
@@ -218,3 +218,29 @@ describe('removeWorktreeOp', () => {
expect(git).not.toHaveBeenCalledWith(['branch', '-D', 'feature/test'], expect.any(String))
})
})
describe('worktreeIsCleanOp', () => {
it('reports clean SSH worktrees without returning porcelain output', async () => {
const git = vi.fn<GitExec>(async () => ({ stdout: '\n', stderr: '' }))
await expect(worktreeIsCleanOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({
clean: true,
stdout: undefined
})
expect(git).toHaveBeenCalledWith(
['status', '--porcelain', '--untracked-files=all'],
'/repo-feature'
)
})
it('returns porcelain output for dirty SSH worktrees', async () => {
const stdout = ' M src/file.ts\n?? scratch.txt\n'
const git = vi.fn<GitExec>(async () => ({ stdout, stderr: '' }))
await expect(worktreeIsCleanOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({
clean: false,
stdout
})
})
})
+10
View File
@@ -208,6 +208,16 @@ function areRelayWorktreePathsEqual(leftPath: string, rightPath: string): boolea
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right
}
export async function worktreeIsCleanOp(
git: GitExec,
params: Record<string, unknown>
): Promise<{ clean: boolean; stdout?: string }> {
const worktreePath = params.worktreePath as string
const { stdout } = await git(['status', '--porcelain', '--untracked-files=all'], worktreePath)
const clean = !stdout.trim()
return { clean, stdout: clean ? undefined : stdout }
}
// ─── Commit ──────────────────────────────────────────────────────────
export async function commitChangesRelay(
+11 -1
View File
@@ -16,7 +16,12 @@ import {
validateGitExecArgs
} from './git-handler-ops'
import { commitCompare as commitCompareOp, commitDiffEntry } from './git-handler-commit-diff-ops'
import { commitChangesRelay, addWorktreeOp, removeWorktreeOp } from './git-handler-worktree-ops'
import {
commitChangesRelay,
addWorktreeOp,
removeWorktreeOp,
worktreeIsCleanOp
} from './git-handler-worktree-ops'
import { checkIgnoredPathsOp, detectConflictOperation, getStatusOp } from './git-handler-status-ops'
import { resolveRelayPushTarget } from './git-handler-push-target'
import { normalizeGitErrorMessage, isNoUpstreamError } from '../shared/git-remote-error'
@@ -72,6 +77,7 @@ export class GitHandler {
this.dispatcher.onRequest('git.listWorktrees', (p) => this.listWorktrees(p))
this.dispatcher.onRequest('git.addWorktree', (p) => this.addWorktree(p))
this.dispatcher.onRequest('git.removeWorktree', (p) => this.removeWorktree(p))
this.dispatcher.onRequest('git.worktreeIsClean', (p) => this.worktreeIsClean(p))
this.dispatcher.onRequest('git.exec', (p) => this.exec(p))
this.dispatcher.onRequest('git.isGitRepo', (p) => this.isGitRepo(p))
}
@@ -529,4 +535,8 @@ export class GitHandler {
private async removeWorktree(params: Record<string, unknown>) {
return removeWorktreeOp(this.git.bind(this), params)
}
private async worktreeIsClean(params: Record<string, unknown>) {
return worktreeIsCleanOp(this.git.bind(this), params)
}
}