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
6 changes: 4 additions & 2 deletions src/main/git/remove-worktree-clean-preflight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
90 changes: 44 additions & 46 deletions src/main/git/worktree-removal-preflight.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand All @@ -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<boolean> =>
!adminDirectory &&
containsSubmoduleCheckout(
resolveWorktreeHostPath(worktreePath, gitOptions) ?? worktreePath,
execution,
await resolveGitDir(worktreePath, gitOptions)
).catch(() => false)
const useNullTerminatedStatus = ignoredUntrackedPaths.length > 0
const { stdout } = await gitExecFileAsync(
[
Expand All @@ -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()}`)
}
Expand All @@ -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<WorktreeRemovalPreflightOptions, 'ignoredUntrackedPaths'>
/** 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<typeof gitExecFileAsync>[1],
adminDirectory: string | null
): Promise<boolean> {
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Stability & Availability · Heavy lift

Keep large-index probe failures from reaching teardown.

If a populated gitlink has no <adminDirectory>/modules directory and ls-files --stage -z emits more than 10 MiB, gitExecFileAsync rejects the output. The caller converts that failure to false. A clean worktree can then lose its terminals before git worktree remove refuses the populated submodule. Use a bounded probe that can find a gitlink without capturing the full index, or refuse deletion when this probe exceeds its output limit. (raw.githubusercontent.com)

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. */
Expand Down
20 changes: 20 additions & 0 deletions src/main/git/worktree-removal-real-git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
4 changes: 4 additions & 0 deletions src/shared/worktree/removal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
Loading