fix(git): cache unsupported capabilities per host (#8109)

* fix(git): cache unsupported capabilities per host

Old Git worktree, ref-search, and merge-tree fallbacks retried unsupported flags on recurring operations, flooding subprocess traces. Centralize capability probing per native, WSL, and SSH execution host, coalesce concurrent probes, and retry periodically for in-place Git upgrades.

* fix(git): recognize real old-Git merge-tree rejection

* test(git): enforce real binary compatibility matrix

* fix(ci): preserve Git compatibility test ownership

* fix(git): retain supported capability state
This commit is contained in:
Neil
2026-07-10 18:19:36 -07:00
committed by GitHub
parent 73e082b577
commit 533992bdda
38 changed files with 1467 additions and 382 deletions
+37
View File
@@ -0,0 +1,37 @@
import { beforeEach, describe, expect, it } from 'vitest'
import {
clearGitCapabilityStateForTests,
getLocalGitCapabilityCache,
getSshGitCapabilityCache
} from './git-capability-state'
describe('Git capability execution-host state', () => {
beforeEach(() => {
clearGitCapabilityStateForTests()
})
it('shares native state while isolating each WSL distro', () => {
expect(getLocalGitCapabilityCache({ cwd: '/repo-a' })).toBe(
getLocalGitCapabilityCache({ cwd: '/repo-b' })
)
expect(getLocalGitCapabilityCache({ wslDistro: 'Ubuntu' })).toBe(
getLocalGitCapabilityCache({ cwd: '\\\\wsl.localhost\\Ubuntu\\home\\repo' })
)
expect(getLocalGitCapabilityCache({ wslDistro: 'Ubuntu' })).not.toBe(
getLocalGitCapabilityCache({ wslDistro: 'Debian' })
)
expect(getLocalGitCapabilityCache()).not.toBe(
getLocalGitCapabilityCache({ wslDistro: 'Ubuntu' })
)
})
it('shares one SSH provider lifetime without leaking into a replacement provider', () => {
const provider = {}
const replacementProvider = {}
expect(getSshGitCapabilityCache(provider)).toBe(getSshGitCapabilityCache(provider))
expect(getSshGitCapabilityCache(provider)).not.toBe(
getSshGitCapabilityCache(replacementProvider)
)
})
})
+44
View File
@@ -0,0 +1,44 @@
import { GitCapabilityCache } from '../../shared/git-capability-cache'
import { parseWslUncPath } from '../../shared/wsl-paths'
type LocalGitCapabilityTarget = {
cwd?: string
wslDistro?: string
}
const localCapabilitiesByExecutionHost = new Map<string, GitCapabilityCache>()
// Why: reconnecting creates a new provider, while concurrent IPC/runtime users
// of one SSH connection must share the same remote Git capability results.
let sshCapabilitiesByProvider = new WeakMap<object, GitCapabilityCache>()
function getLocalGitExecutionHostKey(target: LocalGitCapabilityTarget): string {
const wslDistro =
target.wslDistro ?? (target.cwd ? parseWslUncPath(target.cwd)?.distro : undefined)
return wslDistro ? `wsl:${wslDistro}` : 'local'
}
export function getLocalGitCapabilityCache(
target: LocalGitCapabilityTarget = {}
): GitCapabilityCache {
const executionHost = getLocalGitExecutionHostKey(target)
let cache = localCapabilitiesByExecutionHost.get(executionHost)
if (!cache) {
cache = new GitCapabilityCache()
localCapabilitiesByExecutionHost.set(executionHost, cache)
}
return cache
}
export function getSshGitCapabilityCache(provider: object): GitCapabilityCache {
let cache = sshCapabilitiesByProvider.get(provider)
if (!cache) {
cache = new GitCapabilityCache()
sshCapabilitiesByProvider.set(provider, cache)
}
return cache
}
export function clearGitCapabilityStateForTests(): void {
localCapabilitiesByExecutionHost.clear()
sshCapabilitiesByProvider = new WeakMap()
}
+6
View File
@@ -32,6 +32,8 @@ vi.mock('fs/promises', async () => {
return { ...actual, stat: statMock }
})
import { clearGitCapabilityStateForTests } from './git-capability-state'
import {
addSparseWorktree,
assertWorktreeCleanForRemoval,
@@ -40,6 +42,10 @@ import {
removeWorktree
} from './worktree'
beforeEach(() => {
clearGitCapabilityStateForTests()
})
type MockResult = {
error?: Error
stdout?: string
+5 -1
View File
@@ -9,10 +9,12 @@ vi.mock('./runner', () => ({
gitExecFileSync: vi.fn()
}))
import { clearGitCapabilityStateForTests } from './git-capability-state'
import { searchBaseRefs } from './repo'
describe('searchBaseRefs git compatibility', () => {
afterEach(() => {
clearGitCapabilityStateForTests()
gitExecFileAsyncMock.mockReset()
})
@@ -35,13 +37,15 @@ describe('searchBaseRefs git compatibility', () => {
}
})
await expect(searchBaseRefs('/repo', '', 1)).resolves.toEqual(['origin/main'])
await expect(searchBaseRefs('/repo', '', 1)).resolves.toEqual(['origin/main'])
const forEachRefCalls = gitExecFileAsyncMock.mock.calls.filter(
(call) => (call[0] as string[])[0] === 'for-each-ref'
)
expect(forEachRefCalls).toHaveLength(2)
expect(forEachRefCalls).toHaveLength(3)
expect(forEachRefCalls[0][0]).toContain('--exclude=refs/remotes/**/HEAD')
expect(forEachRefCalls[1][0]).not.toContain('--exclude=refs/remotes/**/HEAD')
expect(forEachRefCalls[1][0]).toContain('--count=104')
expect(forEachRefCalls[2][0]).not.toContain('--exclude=refs/remotes/**/HEAD')
})
})
+24 -32
View File
@@ -5,9 +5,11 @@ import { gitExecFileSync, gitExecFileAsync } from './runner'
import type { BaseRefSearchResult } from '../../shared/types'
import { parseGitRevListAheadBehindCounts } from '../../shared/git-rev-list-output'
import { normalizeRuntimePathSeparators } from '../../shared/cross-platform-path'
import { isForEachRefExcludeUnsupportedError } from '../../shared/git-ref-command-capabilities'
import { parseWslUncPath } from '../../shared/wsl-paths'
import { toWindowsWslPath } from '../wsl'
import { buildHostedRemoteCommitUrl, buildHostedRemoteFileUrl } from './hosted-remote-url'
import { getLocalGitCapabilityCache } from './git-capability-state'
type LocalGitExecOptions = {
wslDistro?: string
@@ -788,27 +790,27 @@ async function runSearchBaseRefsGit(
limit: number,
options: { remoteNames: readonly string[]; patternGroup?: RefSearchPatternGroup }
): Promise<{ stdout: string }> {
try {
return await gitExecFileAsync(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
remoteNames: options.remoteNames,
patternGroup: options.patternGroup
}),
{ cwd: path }
)
} catch (err) {
if (!isForEachRefExcludeUnsupportedError(err)) {
throw err
}
return gitExecFileAsync(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
excludeRemoteHead: false,
remoteNames: options.remoteNames,
patternGroup: options.patternGroup
}),
{ cwd: path }
)
}
return getLocalGitCapabilityCache({ cwd: path }).runWithFallback(
'for-each-ref-exclude',
() =>
gitExecFileAsync(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
remoteNames: options.remoteNames,
patternGroup: options.patternGroup
}),
{ cwd: path }
),
() =>
gitExecFileAsync(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
excludeRemoteHead: false,
remoteNames: options.remoteNames,
patternGroup: options.patternGroup
}),
{ cwd: path }
),
isForEachRefExcludeUnsupportedError
)
}
export function mergeBaseRefSearchResultGroups(
@@ -834,17 +836,7 @@ export function mergeBaseRefSearchResultGroups(
return merged
}
export function isForEachRefExcludeUnsupportedError(error: unknown): boolean {
if (!error || typeof error !== 'object') {
return false
}
const maybe = error as { message?: unknown; stderr?: unknown; stdout?: unknown }
const text = [maybe.message, maybe.stderr, maybe.stdout]
.filter((value): value is string => typeof value === 'string')
.join('\n')
.toLowerCase()
return text.includes('unknown option') && text.includes('exclude')
}
export { isForEachRefExcludeUnsupportedError } from '../../shared/git-ref-command-capabilities'
/**
* Resolve the default push remote for a repo.
@@ -0,0 +1,138 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { gitExecFileAsyncMock } = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn()
}))
vi.mock('./runner', () => ({
gitExecFileAsync: gitExecFileAsyncMock,
gitExecFileSync: vi.fn(),
translateWslOutputPaths: (output: string) => output
}))
import { clearGitCapabilityStateForTests } from './git-capability-state'
import { listWorktrees } from './worktree'
const WORKTREE_LIST_OUTPUT = `worktree /repo
HEAD abc123
branch refs/heads/main
`
describe('worktree Git capabilities', () => {
beforeEach(() => {
clearGitCapabilityStateForTests()
gitExecFileAsyncMock.mockReset()
})
it('does not repeat a known-unsupported -z probe on later scans', async () => {
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args.includes('-z')) {
return Promise.reject(
Object.assign(new Error('git usage error'), {
code: 129,
stderr: 'usage: git worktree list [<options>]\n'
})
)
}
return Promise.resolve({ stdout: WORKTREE_LIST_OUTPUT })
})
await listWorktrees('/repo')
await listWorktrees('/repo')
expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([
['worktree', 'list', '--porcelain', '-z'],
['worktree', 'list', '--porcelain'],
['worktree', 'list', '--porcelain']
])
})
it('keeps native and WSL Git capability results separate', async () => {
gitExecFileAsyncMock.mockImplementation(
(args: string[], options: { cwd: string; wslDistro?: string }) => {
if (args.includes('-z') && !options.wslDistro) {
return Promise.reject(
Object.assign(new Error('git usage error'), {
code: 129,
stderr: 'usage: git worktree list [<options>]\n'
})
)
}
return Promise.resolve({
stdout: `worktree ${options.cwd}\nHEAD abc123\nbranch refs/heads/main\n`
})
}
)
await listWorktrees('/native-repo')
await listWorktrees('/wsl-repo', { wslDistro: 'Ubuntu' })
expect(
gitExecFileAsyncMock.mock.calls.map(([args, options]) => ({
args,
wslDistro: options.wslDistro
}))
).toEqual([
{ args: ['worktree', 'list', '--porcelain', '-z'], wslDistro: undefined },
{ args: ['worktree', 'list', '--porcelain'], wslDistro: undefined },
{ args: ['worktree', 'list', '--porcelain', '-z'], wslDistro: 'Ubuntu' }
])
})
it('does not repeat a known-unsupported rev-parse --path-format probe', async () => {
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args[0] === 'worktree') {
return Promise.resolve({
stdout: 'worktree /git-store/project.git\nHEAD abc123\nbranch refs/heads/main\n'
})
}
if (args.includes('--path-format=absolute')) {
return Promise.reject(
Object.assign(new Error('unknown option: --path-format=absolute'), {
stderr: 'error: unknown option `path-format=absolute`\n'
})
)
}
return Promise.resolve({ stdout: '/repo\n/git-store/project.git\n' })
})
await listWorktrees('/repo')
await listWorktrees('/repo')
const revParseCalls = gitExecFileAsyncMock.mock.calls.filter(
([args]) => (args as string[])[0] === 'rev-parse'
)
expect(revParseCalls.map(([args]) => args)).toEqual([
['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'],
['rev-parse', '--show-toplevel', '--git-common-dir'],
['rev-parse', '--show-toplevel', '--git-common-dir']
])
})
it('remembers old Git that echoes --path-format while exiting successfully', async () => {
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args[0] === 'worktree') {
return Promise.resolve({
stdout: 'worktree /git-store/project.git\nHEAD abc123\nbranch refs/heads/main\n'
})
}
if (args.includes('--path-format=absolute')) {
return Promise.resolve({
stdout: '--path-format=absolute\n/repo\n/git-store/project.git\n'
})
}
return Promise.resolve({ stdout: '/repo\n/git-store/project.git\n' })
})
await listWorktrees('/repo')
await listWorktrees('/repo')
const revParseCalls = gitExecFileAsyncMock.mock.calls.filter(
([args]) => (args as string[])[0] === 'rev-parse'
)
expect(revParseCalls.map(([args]) => args)).toEqual([
['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'],
['rev-parse', '--show-toplevel', '--git-common-dir']
])
})
})
+6
View File
@@ -18,6 +18,8 @@ vi.mock('./runner', () => ({
translateWslOutputPaths: translateWslOutputPathsMock
}))
import { clearGitCapabilityStateForTests } from './git-capability-state'
import {
addSparseWorktree,
addWorktree,
@@ -29,6 +31,10 @@ import {
WORKTREE_ADD_TIMEOUT_MS
} from './worktree'
beforeEach(() => {
clearGitCapabilityStateForTests()
})
describe('listWorktrees in-flight sharing', () => {
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
+66 -54
View File
@@ -17,6 +17,12 @@ import { assertWorktreeUnlockedForRemoval } from '../../shared/worktree-removal'
import { decodeGitCQuotedPath } from '../../shared/git-cquoted-path'
import { parseGitRevListAheadBehindCounts } from '../../shared/git-rev-list-output'
import { parseWslUncPath } from '../../shared/wsl-paths'
import {
hasUnsupportedRevParsePathFormatEcho,
isUnsupportedRevParsePathFormatError,
isUnsupportedWorktreeListZError
} from '../../shared/git-worktree-command-capabilities'
import { getLocalGitCapabilityCache } from './git-capability-state'
import { gitExecFileAsync, translateWslOutputPaths } from './runner'
import { resolveGitDir } from './status'
import { hasWorktreeBaseCommitRef } from './worktree-base-ref-probe'
@@ -111,22 +117,6 @@ function isNotGitRepositoryError(error: unknown): boolean {
return /not a git repository/i.test(getErrorText(error))
}
function isUnsupportedWorktreeListZError(error: unknown): boolean {
// `-z` is this command's only flag older Git (<2.36) lacks, so its usage
// exit 129 signals the rejection in any locale; stderr match is a fallback.
if (getErrorCode(error) === '129') {
return true
}
return /(?:unknown|invalid|unrecognized) (?:switch|option).*`?-?z'?/i.test(getErrorText(error))
}
function isUnsupportedRevParsePathFormatError(error: unknown): boolean {
return /(?:unknown|invalid|unrecognized).*(?:--path-format|path-format)/i.test(
getErrorText(error)
)
}
function isBranchCheckedOutInWorktreeError(error: unknown): boolean {
return /cannot delete branch .*(?:used by worktree|checked out)|branch .*is checked out/i.test(
getErrorText(error)
@@ -410,24 +400,34 @@ async function readRepoLocation(
resolveBasePath: string,
options: GitWorktreeExecOptions = {}
): Promise<RepoLocation | undefined> {
const capabilities = getLocalGitCapabilityCache({
cwd: repoPath,
wslDistro: options.wslDistro
})
try {
const { stdout } = await gitExecFileAsync(
['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'],
gitExecOptions(repoPath, options)
return await capabilities.runWithFallback(
'rev-parse-path-format',
async () => {
const { stdout } = await gitExecFileAsync(
['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'],
gitExecOptions(repoPath, options)
)
if (hasUnsupportedRevParsePathFormatEcho(stdout)) {
// Why: some old Git versions echo the unknown option and exit zero;
// remember that compatibility signal even though parsing can recover.
capabilities.rememberUnsupported('rev-parse-path-format')
}
return parseRepoLocation(resolveBasePath, stdout)
},
async () => {
const { stdout } = await gitExecFileAsync(
['rev-parse', '--show-toplevel', '--git-common-dir'],
gitExecOptions(repoPath, options)
)
return parseRepoLocation(resolveBasePath, stdout)
},
isUnsupportedRevParsePathFormatError
)
return parseRepoLocation(resolveBasePath, stdout)
} catch (error) {
if (!isUnsupportedRevParsePathFormatError(error)) {
return undefined
}
}
try {
const { stdout } = await gitExecFileAsync(
['rev-parse', '--show-toplevel', '--git-common-dir'],
gitExecOptions(repoPath, options)
)
return parseRepoLocation(resolveBasePath, stdout)
} catch {
return undefined
}
@@ -565,29 +565,34 @@ async function readWorktreeList(
repoPath: string,
options: GitWorktreeExecOptions = {}
): Promise<GitWorktreeInfo[]> {
try {
const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain', '-z'], {
cwd: repoPath,
...options
})
return normalizeMainWorktreePath(
repoPath,
parseWorktreeList(stdout, { nulDelimited: true }),
options
)
} catch (error) {
if (!isUnsupportedWorktreeListZError(error)) {
throw error
}
}
// Why: `-z` is required to preserve worktree paths containing newlines, but
// Git <2.36 rejects it. Keep the old parser as a compatibility fallback.
const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain'], {
const capabilities = getLocalGitCapabilityCache({
cwd: repoPath,
...options
wslDistro: options.wslDistro
})
return normalizeMainWorktreePath(repoPath, parseWorktreeList(stdout), options)
return capabilities.runWithFallback(
'worktree-list-z',
async () => {
const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain', '-z'], {
cwd: repoPath,
...options
})
return normalizeMainWorktreePath(
repoPath,
parseWorktreeList(stdout, { nulDelimited: true }),
options
)
},
async () => {
// Why: `-z` is required to preserve worktree paths containing newlines,
// but Git <2.36 rejects it. Keep the line parser as the fallback.
const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain'], {
cwd: repoPath,
...options
})
return normalizeMainWorktreePath(repoPath, parseWorktreeList(stdout), options)
},
isUnsupportedWorktreeListZError
)
}
async function readTranslatedWorktreeGraph(
@@ -1210,7 +1215,14 @@ async function deleteAlreadyMergedBranchAfterSafeDeleteFailure(
// Why: squash merges rewrite commit IDs, so `branch -d` can reject a branch
// whose changes are already on the base ref. Delete only when Git can prove
// the branch contributes no tree changes to that base.
if (!(await branchHasNoUnmergedChangesOnAnyTarget(runGit, branchName, targetRefs))) {
if (
!(await branchHasNoUnmergedChangesOnAnyTarget(
runGit,
branchName,
targetRefs,
getLocalGitCapabilityCache({ cwd: repoPath, wslDistro: options.wslDistro })
))
) {
return false
}
await forceDeleteLocalBranch(repoPath, branchName, branchHead, (args, cwd) =>