diff --git a/src/main/git/remove-worktree-clean-preflight.test.ts b/src/main/git/remove-worktree-clean-preflight.test.ts index b872d1fc7215..4b0069c7d983 100644 --- a/src/main/git/remove-worktree-clean-preflight.test.ts +++ b/src/main/git/remove-worktree-clean-preflight.test.ts @@ -43,8 +43,10 @@ beforeEach(() => { describe('assertWorktreeCleanForRemoval', () => { beforeEach(() => { - // Calls after the status read are the dirty refusal's `.gitmodules` probe: no file, exit 1. - gitExecFileAsyncMock.mockReset().mockRejectedValue(new Error('git config exited with code 1')) + // Calls after the status read are the submodule probe's `ls-files`; failing leaves the verdict to Git. + gitExecFileAsyncMock + .mockReset() + .mockRejectedValue(new Error('git ls-files exited with code 128')) }) it('returns without checking git status for force removals', async () => { diff --git a/src/main/git/worktree-removal-preflight.ts b/src/main/git/worktree-removal-preflight.ts index b5ab72129c55..fa2db3d028b7 100644 --- a/src/main/git/worktree-removal-preflight.ts +++ b/src/main/git/worktree-removal-preflight.ts @@ -1,8 +1,12 @@ -import { stat } from 'node:fs/promises' import { join } from 'node:path' +import { resolveWorktreeHostPath } from '../../shared/git-metadata-path' import { isWorktreePathMissing } from '../worktree-removal-safety' -import { SUBMODULE_DIRTY_REMOVAL_DETAIL } from '../../shared/worktree/removal' +import { + SUBMODULE_DIRTY_REMOVAL_DETAIL, + SUBMODULE_REMOVAL_REFUSAL +} from '../../shared/worktree/removal' import { gitExecFileAsync } from './runner' +import { resolveGitDir } from './source-control/resolve-git-dir' import type { WorktreeRemovalPreflightOptions } from './worktree-operation-options' import { WORKTREE_REMOVAL_PREFLIGHT_TIMEOUT_MS, gitExecOptions } from './worktree-operation-options' @@ -25,22 +29,21 @@ export async function assertWorktreeCleanForRemoval( ...bound, timeout: gitOptions.timeout ?? WORKTREE_REMOVAL_PREFLIGHT_TIMEOUT_MS } - if (adminDirectory) { - const { stdout: index } = await gitExecFileAsync(['ls-files', '--stage', '-z'], execution) - if (!(await isWorktreePathMissing(join(adminDirectory, 'modules')))) { - throw new Error(SUBMODULE_DIRTY_REMOVAL_DETAIL) - } - for (const entry of index.split('\0')) { - if ( - entry.startsWith('160000 ') && - !(await isWorktreePathMissing( - join(worktreePath, entry.slice(entry.indexOf('\t') + 1), '.git') - )) - ) { - throw new Error(SUBMODULE_DIRTY_REMOVAL_DETAIL) - } - } + // Native Windows deletion bypasses Git, so Git's refusal must hold here, before any status read. + if ( + adminDirectory && + (await containsSubmoduleCheckout(worktreePath, execution, adminDirectory)) + ) { + throw new Error(SUBMODULE_DIRTY_REMOVAL_DETAIL) } + // Windows refused above; elsewhere Git re-checks on delete, so a failed probe leaves the decision to Git. + const hasSubmoduleCheckout = async (): Promise => + !adminDirectory && + containsSubmoduleCheckout( + resolveWorktreeHostPath(worktreePath, gitOptions) ?? worktreePath, + execution, + await resolveGitDir(worktreePath, gitOptions) + ).catch(() => false) const useNullTerminatedStatus = ignoredUntrackedPaths.length > 0 const { stdout } = await gitExecFileAsync( [ @@ -58,11 +61,15 @@ export async function assertWorktreeCleanForRemoval( ? getBlockingUntrackedStatusEntries(stdout, ignoredUntrackedPaths) : null if (blockingEntries ? blockingEntries.length === 0 : !stdout.trim()) { + // Git refuses these even when clean; refuse before teardown instead of after terminals stop. + if (await hasSubmoduleCheckout()) { + throw new Error(SUBMODULE_REMOVAL_REFUSAL) + } return } const blockingStatus = blockingEntries ? blockingEntries.join('\n') : stdout - if (await hasPopulatedSubmodule(worktreePath, gitOptions)) { + if (await hasSubmoduleCheckout()) { // Force Delete also destroys submodule-only commits; put that detail before stdout for the formatter. throw new Error(`${SUBMODULE_DIRTY_REMOVAL_DETAIL}\n${blockingStatus.trim()}`) } @@ -73,36 +80,27 @@ export async function assertWorktreeCleanForRemoval( }) } -/** Git's main submodule refusal test: a `.gitmodules` path whose directory holds a `.git`. */ -async function hasPopulatedSubmodule( - worktreePath: string, - gitOptions: Omit +/** Git's own refusal test: submodule repositories under the admin directory, or a gitlink checked out with its `.git`. */ +async function containsSubmoduleCheckout( + hostWorktreePath: string, + execution: Parameters[1], + adminDirectory: string | null ): Promise { - try { - const { stdout } = await gitExecFileAsync( - ['config', '-z', '--file', '.gitmodules', '--get-regexp', '^submodule\\..*\\.path$'], - { - ...gitExecOptions(worktreePath, gitOptions), - timeout: gitOptions.timeout ?? WORKTREE_REMOVAL_PREFLIGHT_TIMEOUT_MS - } - ) - const paths = stdout - .split('\0') - .map((entry) => entry.slice(entry.indexOf('\n') + 1)) - .filter(Boolean) - const populated = await Promise.all( - paths.map((path) => - stat(join(worktreePath, path, '.git')).then( - () => true, - () => false - ) - ) - ) - return populated.includes(true) - } catch { - // No .gitmodules exits non-zero. Any failure keeps the plain dirty refusal, which still blocks. - return false + if (adminDirectory && !(await isWorktreePathMissing(join(adminDirectory, 'modules')))) { + return true + } + const { stdout: index } = await gitExecFileAsync(['ls-files', '--stage', '-z'], execution) + for (const entry of index.split('\0')) { + if ( + entry.startsWith('160000 ') && + !(await isWorktreePathMissing( + join(hostWorktreePath, entry.slice(entry.indexOf('\t') + 1), '.git') + )) + ) { + return true + } } + return false } /** Exclude only the untracked shared links tolerated by the caller. */ diff --git a/src/main/git/worktree-removal-real-git.test.ts b/src/main/git/worktree-removal-real-git.test.ts index a907c858d2a5..3d134be5bf20 100644 --- a/src/main/git/worktree-removal-real-git.test.ts +++ b/src/main/git/worktree-removal-real-git.test.ts @@ -288,6 +288,26 @@ describe('worktree removal against the real Git binary', () => { expect(await isRegistered(subWorktreePath)).toBe(false) }) + it.each([ + ['a checked-out submodule', false], + ['a deinitialized submodule whose repository stays in the admin directory', true] + ])('refuses a clean checkout with %s before teardown, as Git would', async (_name, deinit) => { + // A background delete that Git refuses would surface only after terminals were stopped (#35135). + const { subWorktreePath } = await addSubmoduleCheckoutWithLocalCommit() + await git(['commit', '-qam', 'bump vendor'], subWorktreePath) + if (deinit) { + await git(['submodule', '-q', 'deinit', '-f', 'vendor'], subWorktreePath) + } + + const refusal = await assertWorktreeCleanForRemoval(subWorktreePath).catch((error) => error) + expect(refusal).toBeInstanceOf(Error) + const message = formatWorktreeRemovalError(refusal, subWorktreePath, false) + expect(classifyWorktreeForceDeleteReason(message)).toBe('submodules') + // Git itself, not Orca's native Windows remover, decides what counts. + const gitRefusal = await git(['worktree', 'remove', subWorktreePath], repoPath).catch((e) => e) + expect(String(gitRefusal?.stderr)).toContain('containing submodules') + }) + it('names submodules when the dirty check refuses a checkout that has them', async () => { // Parent status cannot show the submodule-only commit that Force Delete would destroy. const { subWorktreePath } = await addSubmoduleCheckoutWithLocalCommit() diff --git a/src/shared/worktree/removal.ts b/src/shared/worktree/removal.ts index 3088e532ddba..4f07ade9502f 100644 --- a/src/shared/worktree/removal.ts +++ b/src/shared/worktree/removal.ts @@ -102,6 +102,10 @@ export function getLockedWorktreeRemovalReason(error: string): string | null { export const SUBMODULE_DIRTY_REMOVAL_DETAIL = 'Worktree has uncommitted or untracked changes, and it contains submodules.' +// Carries Git's own refusal text so every client version classifies it as the submodule Force Delete reason. +export const SUBMODULE_REMOVAL_REFUSAL = + 'This checkout contains submodule repositories, and Git refuses to remove it without force (working trees containing submodules cannot be moved or removed). Force also deletes anything in those submodules that was never pushed: commits, local branches and stashes.' + // Git refuses initialized submodules even when clean; force deletes their unpushed history too. English output lets clients classify older hosts. export function isSubmoduleWorktreeRemovalRefusal(error: string): boolean { return (