From 9789f48695f96a602d6f7ec150a296c0d237cc6e Mon Sep 17 00:00:00 2001 From: stallenlu Date: Thu, 5 Nov 2026 22:28:56 +0800 Subject: [PATCH] fix(git): run git inside the distribution for a \wsl.localhost workspace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The git binary on the Windows PATH is a Windows build. Pointed at a `\wsl.localhost\\…` worktree it reaches every file through the 9P file server, one `stat` per worktree file. Measured on a 3 102-file repository: `git status` did not finish in 180 s, `git diff --numstat` did not finish in 25 s — while the SAME argv inside the distribution answered in 0.47 s. The panel retried on timeout, and each retry left an orphaned `git.exe` behind, so the source-control tab never loaded. `spawnGit` now reads the distribution and POSIX path out of a UNC cwd (`wslLaunch`, accepting `\wsl.localhost\`, the legacy `\wsl$\` share and the forward-slash spelling) and, for those cwds only, launches `wsl.exe -d --cd -e git …` with the `-C ` prefix replaced by `--cd`. `-e`, not `--`: the `--` form re-parses the tail as a shell command line, which mangles `%(refname:short)` and anything else carrying `()`/`[]`. `WSLENV` carries `LC_ALL`/`GIT_OPTIONAL_LOCKS` across the boundary, which wsl.exe otherwise drops. Everything else is untouched and shares one code path: the timeout, the stdout/stderr byte caps, the NUL field cap, `killTree()` (which reaps the distribution-side process too), the error strings and the dubious-ownership retry. A non-UNC cwd spawns exactly the argv it always did. --- src/git.ts | 59 +++++++++++++++++++++++++++++--- tests/git-spawn.spec.ts | 76 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 129 insertions(+), 6 deletions(-) diff --git a/src/git.ts b/src/git.ts index 140568a6..c107f53d 100644 --- a/src/git.ts +++ b/src/git.ts @@ -395,6 +395,44 @@ export interface RunGitOptions { maxNulFields?: number } +/** + * `\\wsl.localhost\\` — the cwd of a WSL workspace session as + * the Windows host sees it. The legacy `\\wsl$\\…` share and the + * forward-slash spelling (`//wsl.localhost/…`, which a POSIX-ish caller + * hands over) both name the same tree, so all three are accepted. + */ +const WSL_UNC_ROOT = /^[/\\]{2}wsl(?:\.localhost|\$)[/\\]([^/\\]+)(?:[/\\](.*))?$/i + +/** Where one git command must run when the cwd lives in a distribution. */ +export interface WslLaunch { + /** The distribution to enter — the share's first segment. */ + distro: string + /** The cwd as the distribution sees it, `/`-separated. */ + path: string +} + +/** + * The distribution-side launch a UNC workspace cwd calls for, or undefined + * when the cwd is an ordinary Windows path. + * + * The git binary named on the Windows PATH is a Windows build, and running it + * against a `\\wsl.localhost` tree goes through the 9P file server one `stat` + * per worktree file: measured on a 3 102-file repository, `status` alone did + * not finish in 180 s, while the SAME argv inside the distribution answered in + * 0.47 s. Every command that walks the worktree (`status`, `diff --numstat`) + * therefore timed out, the panel retried, and the retries piled up as orphaned + * `git.exe` processes. Entering the distribution to run its own git removes + * the file server from the path entirely. + */ +export function wslLaunch(cwd: string): WslLaunch | undefined { + const match = WSL_UNC_ROOT.exec(cwd) + if (match === null) return undefined + const distro = match[1] + if (distro === undefined || distro === '') return undefined + const rest = (match[2] ?? '').replace(/[/\\]+$/, '') + return { distro, path: rest === '' ? '/' : `/${rest.replace(/[\\/]+/g, '/')}` } +} + /** Count the NUL bytes of one stdout chunk (the `-z` field separator). */ function countNulFields(chunk: Buffer): number { let count = 0 @@ -425,12 +463,23 @@ function spawnGit( ] const maxBytes = options.maxBytes ?? GIT_OUTPUT_MAX_BYTES const maxNulFields = options.maxNulFields + const launch = wslLaunch(cwd) return new Promise((resolvePromise, reject) => { - const child = spawn('git', full, { - stdio: ['ignore', 'pipe', 'pipe'], - windowsHide: true, - env: { ...process.env, ...GIT_ENV }, - }) + const child = launch === undefined + ? spawn('git', full, { + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true, + env: { ...process.env, ...GIT_ENV }, + }) + : spawn('wsl.exe', ['-d', launch.distro, '--cd', launch.path, '-e', 'git', ...full.slice(2)], { + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true, + // `wsl.exe` does not forward the caller's environment: only the names + // listed in WSLENV cross the boundary, and `LC_ALL`/`GIT_OPTIONAL_LOCKS` + // are load-bearing here (a C locale keeps a refused path parseable, and + // the read-only panel must not take write locks). + env: { ...process.env, ...GIT_ENV, WSLENV: 'LC_ALL:GIT_OPTIONAL_LOCKS' }, + }) let stdout = '' let outBytes = 0 let outFields = 0 diff --git a/tests/git-spawn.spec.ts b/tests/git-spawn.spec.ts index 4b1ac5f4..e4f5d870 100644 --- a/tests/git-spawn.spec.ts +++ b/tests/git-spawn.spec.ts @@ -6,7 +6,7 @@ const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })) vi.mock('node:child_process', () => ({ spawn: spawnMock })) -import { currentBranch, isGitRepo, refusedRepository, runGit, worktrees } from '../src/git.ts' +import { currentBranch, isGitRepo, refusedRepository, runGit, worktrees, wslLaunch } from '../src/git.ts' afterEach(() => { spawnMock.mockReset() @@ -275,3 +275,77 @@ describe('git output caps', () => { expect(child.kill).toHaveBeenCalledTimes(1) }) }) + +describe('git inside a WSL distribution', () => { + it('reads the distribution and path out of a UNC workspace cwd', () => { + expect(wslLaunch(String.raw`\\wsl.localhost\Ubuntu\home\me\repo`)) + .toEqual({ distro: 'Ubuntu', path: '/home/me/repo' }) + // The legacy `\\wsl$\` share and the forward-slash spelling name the same + // tree, and a POSIX-ish caller hands over either one. + expect(wslLaunch(String.raw`\\wsl$\Ubuntu\home\me\repo`)) + .toEqual({ distro: 'Ubuntu', path: '/home/me/repo' }) + expect(wslLaunch('//wsl.localhost/Ubuntu/home/me/repo')) + .toEqual({ distro: 'Ubuntu', path: '/home/me/repo' }) + // The distribution root itself, with and without a trailing separator. + expect(wslLaunch(String.raw`\\wsl.localhost\Ubuntu`)) + .toEqual({ distro: 'Ubuntu', path: '/' }) + expect(wslLaunch('//wsl.localhost/Ubuntu/')) + .toEqual({ distro: 'Ubuntu', path: '/' }) + }) + + it('leaves every ordinary Windows and POSIX cwd alone', () => { + expect(wslLaunch('C:\\repo')).toBeUndefined() + expect(wslLaunch('/srv/site/wp-content')).toBeUndefined() + // A directory that merely has `wsl` in its name is not the share. + expect(wslLaunch(String.raw`\\server\share\wsl.localhost\Ubuntu`)).toBeUndefined() + expect(wslLaunch('')).toBeUndefined() + }) + + it('runs git through wsl.exe with the -C prefix replaced by --cd', async () => { + spawnMock.mockImplementation(() => fakeGit('true\n')) + + await isGitRepo(String.raw`\\wsl.localhost\Ubuntu\home\me\repo`) + + // `-e`, never `--`: the `--` form re-parses the tail as a shell command + // line, which mangles `%(refname:short)` and anything else with `()`/`[]` + // in it; `-e` execs the argv verbatim. + expect(spawnMock).toHaveBeenCalledWith( + 'wsl.exe', + [ + '-d', 'Ubuntu', '--cd', '/home/me/repo', '-e', 'git', + '--no-pager', '-c', 'color.ui=false', '-c', 'core.quotePath=false', + 'rev-parse', '--is-inside-work-tree', + ], + expect.objectContaining({ windowsHide: true }), + ) + }) + + it('carries the child environment across the boundary, which wsl.exe does not', async () => { + spawnMock.mockImplementation(() => fakeGit('true\n')) + + await isGitRepo('//wsl.localhost/Ubuntu/home/me/repo') + + // Only the names listed in WSLENV cross into the distribution; without it + // the C locale and the no-locks flag silently stayed on the Windows side. + expect(spawnMock).toHaveBeenCalledWith( + 'wsl.exe', + expect.anything(), + expect.objectContaining({ + env: expect.objectContaining({ + GIT_OPTIONAL_LOCKS: '0', + LC_ALL: 'C', + WSLENV: 'LC_ALL:GIT_OPTIONAL_LOCKS', + }), + }), + ) + }) + + it('still spawns plain git for a Windows cwd', async () => { + spawnMock.mockImplementation(() => fakeGit('true\n')) + + await isGitRepo('C:\\repo') + + expect(spawnMock).toHaveBeenCalledWith('git', expect.anything(), expect.anything()) + expect(spawnMock.mock.calls.every(call => call[0] === 'git')).toBe(true) + }) +})