fix(worktree): restore sparse checkout without per-poll git subprocesses (#1316)

Co-authored-by: Orca <help@stably.ai>
Co-authored-by: Colin <colin.chambachan@gmail.com>
This commit is contained in:
Jinwoo Hong
2026-05-01 13:25:22 -07:00
committed by GitHub
co-authored by Orca Colin
parent d4bbf473c1
commit bbd77c2449
35 changed files with 2543 additions and 76 deletions
+135 -17
View File
@@ -1,6 +1,12 @@
import { posix, win32 } from 'path'
import { stat } from 'fs/promises'
import { join, posix, win32 } from 'path'
import type { GitWorktreeInfo } from '../../shared/types'
import { gitExecFileAsync, translateWslOutputPaths } from './runner'
import { resolveGitDir } from './status'
type SparseWorktreeCreateError = Error & {
cleanupFailed?: boolean
}
function normalizeLocalBranchRef(branch: string): string {
return branch.replace(/^refs\/heads\//, '')
@@ -29,21 +35,23 @@ function looksLikeWindowsPath(pathValue: string): boolean {
*/
export function parseWorktreeList(output: string): GitWorktreeInfo[] {
const worktrees: GitWorktreeInfo[] = []
// [Fix]: Use /\r?\n\r?\n/ to handle both LF and CRLF (\r\n) line endings,
// which are common when running git on Windows.
const blocks = output.trim().split(/\r?\n\r?\n/)
const blocks = output.includes('\0')
? parseNullDelimitedWorktreeBlocks(output)
: output
.trim()
.split(/\r?\n\r?\n/)
.map((block) => block.trim().split(/\r?\n/))
for (const block of blocks) {
if (!block.trim()) {
for (const lines of blocks) {
if (lines.length === 0) {
continue
}
// [Fix]: Use /\r?\n/ to handle both LF and CRLF (\r\n) line endings.
const lines = block.trim().split(/\r?\n/)
let path = ''
let head = ''
let branch = ''
let isBare = false
let isSparse = false
for (const line of lines) {
if (line.startsWith('worktree ')) {
@@ -54,12 +62,21 @@ export function parseWorktreeList(output: string): GitWorktreeInfo[] {
branch = line.slice('branch '.length)
} else if (line === 'bare') {
isBare = true
} else if (line === 'sparse') {
isSparse = true
}
}
if (path) {
// `git worktree list` always emits the main working tree first.
worktrees.push({ path, head, branch, isBare, isMainWorktree: worktrees.length === 0 })
worktrees.push({
path,
head,
branch,
isBare,
...(isSparse ? { isSparse } : {}),
isMainWorktree: worktrees.length === 0
})
}
}
@@ -71,14 +88,24 @@ export function parseWorktreeList(output: string): GitWorktreeInfo[] {
*/
export async function listWorktrees(repoPath: string): Promise<GitWorktreeInfo[]> {
try {
const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain'], {
const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain', '-z'], {
cwd: repoPath
})
// Why: when git runs inside WSL, worktree paths are Linux-native
// (e.g. /home/user/repo). Translate them back to Windows UNC paths
// so the rest of Orca can access them via Node fs APIs.
const translated = translateWslOutputPaths(stdout, repoPath)
return parseWorktreeList(translated)
// Why: WSL path translation is line-oriented, but `-z` porcelain output is
// NUL-delimited. Parse first so only complete path fields are translated.
const worktrees = parseWorktreeList(stdout).map((worktree) => {
const translatedPath = translateWorktreePath(worktree.path, repoPath)
return translatedPath === worktree.path ? worktree : { ...worktree, path: translatedPath }
})
return Promise.all(
worktrees.map(async (worktree) => {
if (worktree.isBare || worktree.isSparse) {
return worktree
}
const isSparse = await detectSparseCheckout(worktree.path)
return isSparse ? { ...worktree, isSparse } : worktree
})
)
} catch {
return []
}
@@ -96,7 +123,8 @@ export async function addWorktree(
worktreePath: string,
branch: string,
baseBranch?: string,
refreshLocalBaseRef = false
refreshLocalBaseRef = false,
noCheckout = false
): Promise<void> {
// Why: Some users want Orca-created worktrees to make plain commands like
// `git diff main...HEAD` work out of the box, while others do not want
@@ -152,13 +180,49 @@ export async function addWorktree(
}
}
const args = ['worktree', 'add', '-b', branch, worktreePath]
const args = ['worktree', 'add']
if (noCheckout) {
args.push('--no-checkout')
}
args.push('-b', branch, worktreePath)
if (baseBranch) {
args.push(baseBranch)
}
await gitExecFileAsync(args, { cwd: repoPath })
}
export async function addSparseWorktree(
repoPath: string,
worktreePath: string,
branch: string,
directories: string[],
baseBranch?: string,
refreshLocalBaseRef = false
): Promise<void> {
let created = false
try {
await addWorktree(repoPath, worktreePath, branch, baseBranch, refreshLocalBaseRef, true)
created = true
await gitExecFileAsync(['sparse-checkout', 'init', '--cone'], { cwd: worktreePath })
await gitExecFileAsync(['sparse-checkout', 'set', '--', ...directories], { cwd: worktreePath })
await gitExecFileAsync(['checkout', branch], { cwd: worktreePath })
} catch (error) {
const wrapped: SparseWorktreeCreateError =
error instanceof Error ? (error as SparseWorktreeCreateError) : new Error(String(error))
if (created) {
try {
await removeWorktree(repoPath, worktreePath, true)
} catch {
wrapped.cleanupFailed = true
// Why: the user needs to know that manual cleanup may be required —
// otherwise a half-created worktree silently lingers on disk.
wrapped.message = `${wrapped.message} (cleanup also failed — the partially created worktree at "${worktreePath}" may need manual removal)`
}
}
throw wrapped
}
}
/**
* Remove a worktree.
*/
@@ -208,3 +272,57 @@ export async function removeWorktree(
)
}
}
function parseNullDelimitedWorktreeBlocks(output: string): string[][] {
const blocks: string[][] = []
let current: string[] = []
for (const token of output.split('\0')) {
if (!token) {
if (current.length > 0) {
blocks.push(current)
current = []
}
continue
}
current.push(token)
}
if (current.length > 0) {
blocks.push(current)
}
return blocks
}
function translateWorktreePath(worktreePath: string, repoPath: string): string {
const prefix = 'worktree '
const translated = translateWslOutputPaths(`${prefix}${worktreePath}`, repoPath)
return translated.startsWith(prefix) ? translated.slice(prefix.length) : worktreePath
}
async function detectSparseCheckout(worktreePath: string): Promise<boolean> {
// Why: `listWorktrees` runs on every 3-second git-status poll and on every
// worktree refresh, so this probe fires N times per poll for N worktrees.
// The previous `git sparse-checkout list` subprocess made that N*poll extra
// git processes, which regressed app responsiveness on machines with many
// worktrees (see PR #1131 revert in #1290). A single fs.stat on the
// per-worktree sparse-checkout config file is ~two orders of magnitude
// cheaper and has the same truthiness semantics: Git writes this file when
// sparse checkout is enabled for the worktree and does not write it
// otherwise.
//
// Why per-worktree gitdir and not `<worktreePath>/.git/info/sparse-checkout`:
// linked worktrees have a `.git` file that points at
// `<repo>/.git/worktrees/<name>`, and that is where Git stores the
// worktree-local sparse-checkout config. `core.sparseCheckout` itself is
// shared across all worktrees, so the presence of the config file is the
// correct per-worktree signal.
try {
const gitDir = await resolveGitDir(worktreePath)
const stats = await stat(join(gitDir, 'info', 'sparse-checkout'))
return stats.isFile() && stats.size > 0
} catch {
return false
}
}