import { EventEmitter } from 'node:events' import { PassThrough } from 'node:stream' import { afterEach, describe, expect, it, vi } from 'vitest' const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })) vi.mock('node:child_process', () => ({ spawn: spawnMock })) import { currentBranch, isGitRepo, refusedRepository, repoRoots, runGit, status, worktrees, wslLaunch, wslRootSpelling, } from '../src/git.ts' afterEach(() => { spawnMock.mockReset() }) /** A fake spawned git that ends its streams and closes with `code`. */ function fakeGit(stdoutText = '', stderrText = '', code = 0): EventEmitter { const child = new EventEmitter() const stdout = new PassThrough() const stderr = new PassThrough() Object.assign(child, { stdout, stderr, kill: vi.fn() }) queueMicrotask(() => { stdout.end(stdoutText) stderr.end(stderrText) child.emit('close', code) }) return child } /** The `-c key=value` overrides runGit put in front of the subcommand. * Collected by name rather than by index: the flag set grows whenever a new * global `-c` lands (color.ui, core.quotePath, the per-invocation * safe.directory…), so a positional slice pins a shape nothing depends on. */ function configFlagsOf(args: string[] | undefined): string[] { const flags: string[] = [] for (let at = 0; at < (args?.length ?? 0); at += 1) { if (args?.[at] === '-c') flags.push(args[at + 1] ?? '') } return flags } /** git ≥ 2.35.2's refusal, verbatim (the hint text included). */ const DUBIOUS = "fatal: detected dubious ownership in repository at '/srv/site'\n" + 'To add an exception for this directory, call:\n\n' + '\tgit config --global --add safe.directory /srv/site\n' describe('dubious-ownership retry (issue #690)', () => { it('retries once, trusting only the repository git refused for this invocation', async () => { const calls: string[][] = [] spawnMock.mockImplementation((_file: string, args: string[]) => { calls.push(args) return calls.length === 1 ? fakeGit('', DUBIOUS, 128) : fakeGit('true\n') }) await expect(isGitRepo('/srv/site/wp-content')).resolves.toBe(true) expect(calls).toHaveLength(2) // The first attempt is the argv a healthy repository always got... expect(calls[0]).toEqual([ '-C', '/srv/site/wp-content', '--no-pager', '-c', 'color.ui=false', '-c', 'core.quotePath=false', 'rev-parse', '--is-inside-work-tree', ]) // ...and the retry trusts exactly what git named (the repository ROOT, not // the cwd — the refusal names the root) plus the cwd, and never '*'. expect(calls[1]).toEqual([ '-C', '/srv/site/wp-content', '--no-pager', '-c', 'color.ui=false', '-c', 'core.quotePath=false', '-c', 'safe.directory=/srv/site', '-c', 'safe.directory=/srv/site/wp-content', 'rev-parse', '--is-inside-work-tree', ]) }) it('runs git under a C locale so the refused path stays parseable', async () => { spawnMock.mockImplementation(() => fakeGit('true\n')) await isGitRepo('/srv/site') expect(spawnMock).toHaveBeenCalledWith( 'git', expect.anything(), expect.objectContaining({ env: expect.objectContaining({ GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' }), }), ) }) it('does not retry a failure that is not the ownership guard', async () => { spawnMock.mockImplementation(() => fakeGit('', 'fatal: not a git repository (or any of the parent directories): .git\n', 128)) await expect(isGitRepo('/tmp/plain')).resolves.toBe(false) expect(spawnMock).toHaveBeenCalledTimes(1) }) it('falls back to the cwd when the refusal names no directory', async () => { const calls: string[][] = [] spawnMock.mockImplementation((_file: string, args: string[]) => { calls.push(args) return calls.length === 1 ? fakeGit('', 'fatal: detected dubious ownership\n', 128) : fakeGit('true\n') }) await expect(isGitRepo('/srv/site')).resolves.toBe(true) expect(configFlagsOf(calls[1])).toContain('safe.directory=/srv/site') expect(calls[1]?.some(arg => arg.includes('safe.directory=*'))).toBe(false) }) it('reports a second refusal instead of retrying forever', async () => { const calls: string[][] = [] spawnMock.mockImplementation((_file: string, args: string[]) => { calls.push(args) return fakeGit('', DUBIOUS, 128) }) await expect(currentBranch('/srv/site')).rejects.toThrow(/dubious ownership/) expect(calls).toHaveLength(2) }) it('reads the refused path out of the git message', () => { expect(refusedRepository(DUBIOUS)).toBe('/srv/site') // Percent-escaped or otherwise unusual messages must simply yield nothing. expect(refusedRepository('fatal: detected dubious ownership\n')).toBeUndefined() expect(refusedRepository('')).toBeUndefined() }) }) describe('git subprocess spawning', () => { it('hides spawned git windows', async () => { spawnMock.mockImplementation(() => { const child = new EventEmitter() const stdout = new PassThrough() const stderr = new PassThrough() Object.assign(child, { stdout, stderr, kill: vi.fn() }) queueMicrotask(() => { stdout.end('true\n') stderr.end() child.emit('close', 0) }) return child }) await expect(isGitRepo('C:\\repo')).resolves.toBe(true) expect(spawnMock).toHaveBeenCalledTimes(1) expect(spawnMock).toHaveBeenCalledWith( 'git', ['-C', 'C:\\repo', '--no-pager', '-c', 'color.ui=false', '-c', 'core.quotePath=false', 'rev-parse', '--is-inside-work-tree'], expect.objectContaining({ windowsHide: true }), ) }) it('falls back when worktree list does not support -z', async () => { // The subcommand starts after runGit's own prefix (`-C // --no-pager` plus any number of `-c key=value` flags), so find it // instead of counting: pinning the count breaks on every added `-c`. const subcommandOf = (args: string[]): string[] => { let at = 0 while (at < args.length) { if (args[at] === '-C' || args[at] === '-c') { at += 2; continue } if (args[at] === '--no-pager') { at += 1; continue } break } return args.slice(at) } const gitChild = (stdoutText = '', stderrText = '', code = 0): EventEmitter => { const child = new EventEmitter() const stdout = new PassThrough() const stderr = new PassThrough() Object.assign(child, { stdout, stderr, kill: vi.fn() }) queueMicrotask(() => { stdout.end(stdoutText) stderr.end(stderrText) child.emit('close', code) }) return child } spawnMock.mockImplementation((_file: string, args: string[]) => { const command = subcommandOf(args) if (command[0] === 'rev-parse' && command[1] === '--is-inside-work-tree') return gitChild('true\n') if (command[0] === 'rev-parse' && command[1] === '--show-toplevel') return gitChild('C:\\repo\n') if (command[0] === 'rev-parse' && command[1] === '--abbrev-ref') return gitChild('main\n') if (command[0] === 'status') return gitChild('') if (command[0] === 'worktree' && command.includes('-z')) { return gitChild('', "error: unknown switch `z'\n", 129) } if (command[0] === 'worktree') { return gitChild([ 'worktree C:\\repo', 'HEAD abc', 'branch refs/heads/main', '', ].join('\n')) } throw new Error(`unexpected git command: ${command.join(' ')}`) }) await expect(worktrees('C:\\repo')).resolves.toEqual([ { path: 'C:\\repo', branch: 'main', current: true, changes: 0 }, ]) await expect(worktrees('C:\\repo')).resolves.toEqual([ { path: 'C:\\repo', branch: 'main', current: true, changes: 0 }, ]) const nulAttempts = spawnMock.mock.calls.filter((call) => { const args = call[1] as string[] return args.includes('worktree') && args.includes('-z') }) expect(nulAttempts).toHaveLength(1) }) }) /** * The two output caps, pinned against a MOCKED child — the only way to make * "production stopped" deterministic. Against a real `git` the answer is a * race: the killed child may already have written its whole output into the * pipe, so the retained text legitimately still contained every row (CI red: * a capped 2,500-row status returned all 2,500 fields). Here we control both * the crossing chunk AND the tail that arrives after the kill. */ describe('git output caps', () => { /** A child whose stdout is driven by the test, with a spy on `kill`. */ function controlledChild(script: (stdout: PassThrough, child: EventEmitter) => void): { spawn: () => EventEmitter kill: ReturnType } { const kill = vi.fn() return { kill, spawn: () => { const child = new EventEmitter() const stdout = new PassThrough() const stderr = new PassThrough() Object.assign(child, { stdout, stderr, kill }) queueMicrotask(() => { script(stdout, child) }) return child }, } } it('stops retaining output once the NUL field cap is reached', async () => { const field = (letter: string): string => `${letter.repeat(10)}\0` const child = controlledChild((stdout, proc) => { stdout.write(field('a').repeat(3)) // crosses the cap of 2 → kill // The killed child's already-buffered tail must NOT reach the caller. setImmediate(() => { stdout.write(field('b').repeat(50)) stdout.end() proc.emit('close', null) // killed by a signal, not a clean exit }) }) spawnMock.mockImplementation(child.spawn) const out = await runGit('/repo', ['status'], 30_000, { maxNulFields: 2 }) expect(child.kill).toHaveBeenCalledTimes(1) expect(out).toBe(field('a').repeat(3)) expect(out).not.toContain('bbbbbbbbbb') }) it('kills the child and rejects when stdout exceeds the byte cap', async () => { const child = controlledChild((stdout, proc) => { stdout.write(Buffer.alloc(64, 0x78)) stdout.end() proc.emit('close', 0) }) spawnMock.mockImplementation(child.spawn) await expect(runGit('/repo', ['log'], 30_000, { maxBytes: 32 })) .rejects.toThrow(/output exceeded 32 bytes/) 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) }) }) /** * `rev-parse --show-toplevel` answers from INSIDE the distribution, so it names * the repository with a POSIX path. That string is not a path this host can run * git in: `wslLaunch` only recognises the UNC spelling, so every later command * on the reported root silently fell through to the Windows git and died with * `exit 128: cannot change to '/home/...'` — the whole Git panel read as * "failed to load" (issue #1189). */ describe('a repository root reported from inside a WSL distribution (issue #1189)', () => { /** The UNC spelling of one distribution-side path. */ const unc = (distroPath: string): string => `\\\\wsl.localhost\\Ubuntu${distroPath.replace(/\//g, '\\')}` /** The subcommand, skipping the global `-C`/`--no-pager`/`-c` prefix that * differs between the plain and the `wsl.exe` argv shapes. */ function subcommandOf(args: string[]): string[] { let at = args.indexOf('--no-pager') if (at === -1) return args at += 1 while (args[at] === '-c') at += 2 return args.slice(at) } /** A fake git answering what discovery, `status` and `worktrees` ask for. */ function distributionGit(reportedRoot: string): void { spawnMock.mockImplementation((_file: string, args: string[]) => { const command = subcommandOf(args) if (command[0] === 'rev-parse' && command[1] === '--show-toplevel') return fakeGit(`${reportedRoot}\n`) if (command[0] === 'rev-parse' && command[1] === '--is-inside-work-tree') return fakeGit('true\n') if (command[0] === 'rev-parse' && command[1] === '--absolute-git-dir') return fakeGit(`${reportedRoot}/.git\n`) if (command[0] === 'status') return fakeGit('') if (command[0] === 'worktree') return fakeGit('') throw new Error(`unexpected git command: ${command.join(' ')}`) }) } it('re-spells the reported root through the cwd it was discovered from', () => { expect(wslRootSpelling(unc('/home/me/repo'), '/home/me/repo')).toBe(unc('/home/me/repo')) // The legacy share keeps its OWN spelling: a UNC path is only usable on the // share the cwd arrived through. expect(wslRootSpelling(String.raw`\\wsl$\Ubuntu\home\me\repo`, '/home/me/repo')) .toBe(String.raw`\\wsl$\Ubuntu\home\me\repo`) // The distribution root itself, and a trailing separator git never prints // but a caller might hand over. expect(wslRootSpelling(unc('/home/me/repo'), '/')).toBe(String.raw`\\wsl.localhost\Ubuntu`) expect(wslRootSpelling(unc('/home/me/repo'), '/home/me/repo/')).toBe(unc('/home/me/repo')) }) it('leaves every ordinary Windows and POSIX root alone', () => { expect(wslRootSpelling('C:\\repo', 'C:/repo')).toBe('C:/repo') expect(wslRootSpelling('C:\\repo', 'C:\\repo')).toBe('C:\\repo') expect(wslRootSpelling('/srv/site', '/srv/site')).toBe('/srv/site') // A root git already spelled as a host path must not be prefixed twice. expect(wslRootSpelling(unc('/home/me/repo'), unc('/home/me/repo'))).toBe(unc('/home/me/repo')) }) it('keeps the UNC spelling of the root it discovers', async () => { distributionGit('/home/me/discovered') await expect(repoRoots(unc('/home/me/discovered'))).resolves.toEqual([unc('/home/me/discovered')]) }) it('runs every later command inside the distribution, not through the Windows git', async () => { distributionGit('/home/me/panel') await status(unc('/home/me/panel')) const executables = spawnMock.mock.calls.map(call => call[0] as string) // The discovery probe always went through wsl.exe (its cwd is UNC); #1189 // is about the commands that FOLLOW it, which the POSIX root sent to the // Windows git. expect(executables.length).toBeGreaterThan(1) expect(executables.every(file => file === 'wsl.exe')).toBe(true) const statusCall = spawnMock.mock.calls.find(call => subcommandOf(call[1] as string[])[0] === 'status') expect(statusCall?.[0]).toBe('wsl.exe') // ...and it was pointed back at the path the distribution understands. const argv = statusCall?.[1] as string[] expect(argv[argv.indexOf('--cd') + 1]).toBe('/home/me/panel') }) it('still spawns plain git when discovery started from a Windows cwd', async () => { distributionGit('C:\\repo') await status('C:\\repo') expect(spawnMock.mock.calls.every(call => call[0] === 'git')).toBe(true) }) it('re-spells every linked checkout the distribution listed', async () => { spawnMock.mockImplementation((_file: string, args: string[]) => { const command = subcommandOf(args) if (command[0] === 'rev-parse' && command[1] === '--is-inside-work-tree') return fakeGit('true\n') if (command[0] === 'rev-parse' && command[1] === '--show-toplevel') return fakeGit('/home/me/linked\n') if (command[0] === 'worktree') { return fakeGit([ 'worktree /home/me/linked', 'HEAD abc', 'branch refs/heads/main', '', 'worktree /home/me/linked-feature', 'HEAD def', 'branch refs/heads/feature', '', ].join('\n')) } if (command[0] === 'status') return fakeGit('') throw new Error(`unexpected git command: ${command.join(' ')}`) }) // A POSIX-spelled checkout is not usable as a command target either: the // current one must still be recognised as current (it drives the selector) // and every entry must be a path this host can run git in. await expect(worktrees(unc('/home/me/linked'))).resolves.toEqual([ { path: unc('/home/me/linked'), branch: 'main', current: true, changes: 0 }, { path: unc('/home/me/linked-feature'), branch: 'feature', current: false, changes: 0 }, ]) }) })