Skip to content
Open
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
15 changes: 5 additions & 10 deletions src/main/git/source-control/discard-changes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,16 @@ export async function discardChanges(

let tracked = false
try {
await gitExecFileAsync(
['ls-files', '--error-unmatch', '--', literalPathspec(filePath, options)],
{
...gitOptionsForWorktree(worktreePath, options)
}
)
await gitExecFileAsync(['ls-files', '--error-unmatch', '--', literalPathspec(filePath)], {
...gitOptionsForWorktree(worktreePath, options)
})
tracked = true
} catch {
// File is not tracked by git
}

if (tracked) {
await gitExecFileAsync(['restore', '--worktree', '--', literalPathspec(filePath, options)], {
await gitExecFileAsync(['restore', '--worktree', '--', literalPathspec(filePath)], {
...gitOptionsForWorktree(worktreePath, options)
})
await redoWriteForDriveCheckoutSuspects(worktreePath, [filePath], DISCARD_WRITE, options)
Expand Down Expand Up @@ -133,9 +130,7 @@ export async function bulkDiscardChanges(
['restore', '--worktree', '--pathspec-from-file=-', '--pathspec-file-nul'],
{
...gitOptionsForWorktree(worktreePath, options),
stdin: encodeGitPathspecs(
trackedPaths.map((filePath) => literalPathspec(filePath, options))
)
stdin: encodeGitPathspecs(trackedPaths.map(literalPathspec))
}
)
await redoWriteForDriveCheckoutSuspects(worktreePath, trackedPaths, DISCARD_WRITE, options)
Expand Down
9 changes: 4 additions & 5 deletions src/main/git/source-control/git-pathspec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ const BULK_CHUNK_SIZE = 100
*/
const POSIX_COMMAND_LINE_BUDGET = 128_000

export function literalPathspec(filePath: string, options: GitRuntimeOptions): string {
// Why: Git inside WSL needs POSIX paths, but host paths must stay literal, so convert backslashes only for WSL.
const runtimePath = options.wslDistro ? filePath.replace(/\\/g, '/') : filePath
return `:(literal)${runtimePath}`
// Why no separator rewrite: callers pass Git-spelled paths, so a `\` here is a POSIX filename character.
export function literalPathspec(filePath: string): string {
return `:(literal)${filePath}`
}

/**
Expand Down Expand Up @@ -76,7 +75,7 @@ export function bulkPathspecCommands(
let pathspecs: string[] = []
let length = baseLength
for (const filePath of filePaths) {
const pathspec = literalPathspec(filePath, options)
const pathspec = literalPathspec(filePath)
const cost =
finishedCommandLineLength([...leadingArgs, pathspec], worktreePath, options) - baseLength
if (pathspecs.length > 0 && (pathspecs.length >= BULK_CHUNK_SIZE || length + cost > budget)) {
Expand Down
8 changes: 4 additions & 4 deletions src/main/git/source-control/staging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function stageFile(
invalidateGitReadCaches()
try {
await gitExecFileAsync(
['add', '--', literalPathspec(filePath, options)],
['add', '--', literalPathspec(filePath)],
gitOptionsForWorktree(worktreePath, options)
)
await redoWriteForDriveCheckoutSuspects(worktreePath, [filePath], STAGE_WRITE, options)
Expand All @@ -45,7 +45,7 @@ export async function unstageFile(
invalidateGitReadCaches()
try {
// Reset treats an unborn HEAD as an empty tree, preserving the working file.
await gitExecFileAsync(['reset', '--quiet', '--', literalPathspec(filePath, options)], {
await gitExecFileAsync(['reset', '--quiet', '--', literalPathspec(filePath)], {
...gitOptionsForWorktree(worktreePath, options)
})
} finally {
Expand All @@ -68,7 +68,7 @@ export async function bulkStageFiles(
try {
await gitExecFileAsync(['add', '--pathspec-from-file=-', '--pathspec-file-nul'], {
...gitOptionsForWorktree(worktreePath, options),
stdin: encodeGitPathspecs(filePaths.map((filePath) => literalPathspec(filePath, options)))
stdin: encodeGitPathspecs(filePaths.map(literalPathspec))
})
await redoWriteForDriveCheckoutSuspects(worktreePath, filePaths, STAGE_WRITE, options)
} finally {
Expand Down Expand Up @@ -123,7 +123,7 @@ export async function bulkUnstageFiles(
try {
await gitExecFileAsync(['reset', '--quiet', '--pathspec-from-file=-', '--pathspec-file-nul'], {
...gitOptionsForWorktree(worktreePath, options),
stdin: encodeGitPathspecs(filePaths.map((filePath) => literalPathspec(filePath, options)))
stdin: encodeGitPathspecs(filePaths.map(literalPathspec))
})
} finally {
invalidateGitReadCaches()
Expand Down
38 changes: 21 additions & 17 deletions src/main/git/status-wsl-pathspecs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
} from './status'

const worktreePath = path.resolve('repo')
const windowsRelativePath = 'tests\\breakgit'
const gitRelativePath = 'tests/breakgit'
const wslOptions = { wslDistro: 'Ubuntu' }

describe('WSL git pathspecs', () => {
Expand All @@ -33,13 +33,13 @@ describe('WSL git pathspecs', () => {
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'tests/breakgit\0', stderr: '' })
})

it('uses POSIX separators for tracked file mutations executed inside WSL', async () => {
await stageFile(worktreePath, windowsRelativePath, wslOptions)
await unstageFile(worktreePath, windowsRelativePath, wslOptions)
await bulkStageFiles(worktreePath, [windowsRelativePath], wslOptions)
await bulkUnstageFiles(worktreePath, [windowsRelativePath], wslOptions)
await discardChanges(worktreePath, windowsRelativePath, wslOptions)
await bulkDiscardChanges(worktreePath, [windowsRelativePath], wslOptions)
it('passes Git-spelled paths to tracked file mutations executed inside WSL', async () => {
await stageFile(worktreePath, gitRelativePath, wslOptions)
await unstageFile(worktreePath, gitRelativePath, wslOptions)
await bulkStageFiles(worktreePath, [gitRelativePath], wslOptions)
await bulkUnstageFiles(worktreePath, [gitRelativePath], wslOptions)
await discardChanges(worktreePath, gitRelativePath, wslOptions)
await bulkDiscardChanges(worktreePath, [gitRelativePath], wslOptions)

const pathspecs = gitExecFileAsyncMock.mock.calls.flatMap(([args]) =>
(args as string[]).filter((arg) => arg.startsWith(':(literal)'))
Expand All @@ -51,17 +51,17 @@ describe('WSL git pathspecs', () => {
expect(inputs).toEqual(Array(3).fill(':(literal)tests/breakgit\0'))
})

it('uses POSIX separators when discarding untracked files inside WSL', async () => {
it('passes Git-spelled paths when discarding untracked files inside WSL', async () => {
const repo = await mkdtemp(path.join(tmpdir(), 'orca-wsl-pathspec-'))
const targetPath = path.resolve(repo, windowsRelativePath)
const targetPath = path.resolve(repo, gitRelativePath)
await mkdir(path.dirname(targetPath), { recursive: true })
await writeFile(targetPath, 'untracked')

try {
gitExecFileAsyncMock
.mockRejectedValueOnce(new Error('not tracked'))
.mockResolvedValue({ stdout: '', stderr: '' })
await discardChanges(repo, windowsRelativePath, wslOptions)
await discardChanges(repo, gitRelativePath, wslOptions)

expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([
['ls-files', '--error-unmatch', '--', ':(literal)tests/breakgit'],
Expand All @@ -70,7 +70,7 @@ describe('WSL git pathspecs', () => {

gitExecFileAsyncMock.mockReset()
gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
await bulkDiscardChanges(repo, [windowsRelativePath], wslOptions)
await bulkDiscardChanges(repo, [gitRelativePath], wslOptions)

expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([
['ls-files', '-z', '--', ':(literal)tests/breakgit'],
Expand All @@ -81,11 +81,15 @@ describe('WSL git pathspecs', () => {
}
})

it('preserves backslashes for host Git where they can be literal filename characters', async () => {
await stageFile(worktreePath, windowsRelativePath)
it.each([
['host Git', {}],
['WSL Git', wslOptions]
])('keeps a backslash literal for %s, where it is a filename character', async (_, options) => {
await stageFile(worktreePath, 'tests\\breakgit', options)

expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['add', '--', ':(literal)tests\\breakgit'], {
cwd: worktreePath
})
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
['add', '--', ':(literal)tests\\breakgit'],
expect.anything()
)
})
})
43 changes: 42 additions & 1 deletion src/main/ipc/filesystem-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,10 +377,19 @@ describe('filesystem-auth path containment', () => {

it('allows git-relative files under dotdot-prefixed child directories', () => {
expect(validateGitRelativeFilePath(resolve('/workspace/repo'), '..fixtures/file.ts')).toBe(
join('..fixtures', 'file.ts')
'..fixtures/file.ts'
)
})

it.skipIf(process.platform === 'win32')(
'keeps a backslash on POSIX, where it is a filename character',
() => {
expect(validateGitRelativeFilePath(resolve('/workspace/repo'), 'tests/a\\b.ts')).toBe(
'tests/a\\b.ts'
)
}
)

it('still rejects parent-directory escapes', () => {
const root = resolve('/workspace/repo')
const outside = resolve('/workspace/repo/../other/file.ts')
Expand Down Expand Up @@ -421,4 +430,36 @@ describe('filesystem-auth path containment', () => {
vi.resetModules()
}
})

// #28422: a `\\wsl.localhost` worktree runs Linux Git even when the project's runtime says Windows.
it('spells Windows git-relative paths with forward slashes', async () => {
vi.resetModules()
vi.doMock('path', async () => {
const path = await vi.importActual<typeof NodePath>('node:path')
return {
...path.win32,
default: path.win32
}
})

try {
const { validateGitRelativeFilePath: validateWithWinPath } =
await import('./filesystem-path-containment')

for (const host of ['wsl.localhost', 'wsl$']) {
expect(
validateWithWinPath(
String.raw`\\${host}\Ubuntu-24.04\home\dev\repo`,
String.raw`.claude\settings.json`
)
).toBe('.claude/settings.json')
}
expect(validateWithWinPath(String.raw`C:\repo`, String.raw`src\.\nested\app.ts`)).toBe(
'src/nested/app.ts'
)
} finally {
vi.doUnmock('path')
vi.resetModules()
}
})
})
6 changes: 2 additions & 4 deletions src/main/ipc/filesystem-branch-compare-diff.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,15 +226,13 @@ describe('registerFilesystemHandlers', () => {
oldPath: 'src/old-file.ts'
})

// Why: validateGitRelativeFilePath uses path.relative() which produces
// platform-specific separators (backslashes on Windows).
expect(getBranchDiffMock).toHaveBeenCalledWith(
WORKTREE_FEATURE_PATH,
{
headOid: 'head-oid',
mergeBase: 'merge-base-oid',
filePath: path.join('src', 'file.ts'),
oldPath: path.join('src', 'old-file.ts')
filePath: 'src/file.ts',
oldPath: 'src/old-file.ts'
},
{ admissionTier: 'interactive' }
)
Expand Down
12 changes: 5 additions & 7 deletions src/main/ipc/filesystem-git-status-staging.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { EventEmitter } from 'node:events'
import path from 'node:path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
handlers,
Expand Down Expand Up @@ -86,9 +85,8 @@ describe('registerFilesystemHandlers', () => {
filePath: './src/../src/file.ts'
})

// Why: validateGitRelativeFilePath uses path.relative() which produces
// platform-specific separators (backslashes on Windows).
expect(stageFileMock).toHaveBeenCalledWith(WORKTREE_FEATURE_PATH, path.join('src', 'file.ts'), {
// Why: Git spells paths with `/` on every host, so Windows separators must not leak through.
expect(stageFileMock).toHaveBeenCalledWith(WORKTREE_FEATURE_PATH, 'src/file.ts', {
admissionTier: 'interactive'
})
})
Expand Down Expand Up @@ -297,7 +295,7 @@ describe('registerFilesystemHandlers', () => {

expect(checkIgnoredPathsMock).toHaveBeenCalledWith(
WORKTREE_FEATURE_PATH,
[path.join('dist', 'bundle.js'), path.join('src', 'index.ts')],
['dist/bundle.js', 'src/index.ts'],
{}
)
})
Expand Down Expand Up @@ -380,7 +378,7 @@ describe('registerFilesystemHandlers', () => {

expect(bulkStageFilesMock).toHaveBeenCalledWith(
WORKTREE_FEATURE_PATH,
[path.join('src', 'file.ts'), path.join('nested', 'child.ts')],
['src/file.ts', 'nested/child.ts'],
{ admissionTier: 'interactive' }
)
})
Expand Down Expand Up @@ -438,7 +436,7 @@ describe('registerFilesystemHandlers', () => {

expect(bulkDiscardChangesMock).toHaveBeenCalledWith(
WORKTREE_FEATURE_PATH,
[path.join('src', 'file.ts'), path.join('nested', 'child.ts')],
['src/file.ts', 'nested/child.ts'],
{ admissionTier: 'interactive' }
)
})
Expand Down
5 changes: 4 additions & 1 deletion src/main/ipc/filesystem-path-containment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ export async function normalizeExistingPath(resolvedPath: string): Promise<strin
}
}

/** A worktree-relative path as Git spells it: `/`-separated on every host. */
export function validateGitRelativeFilePath(worktreePath: string, filePath: string): string {
if (!filePath || filePath.includes('\0') || resolve(filePath) === filePath) {
throw new Error('Access denied: invalid git file path')
Expand All @@ -149,7 +150,9 @@ export function validateGitRelativeFilePath(worktreePath: string, filePath: stri
throw new Error('Access denied: invalid git file path')
}

return normalizedRelativePath
// Why: a `\\wsl.localhost` worktree runs Linux Git whatever the project's runtime setting, and
// Linux Git reads `\` as a filename character. On Windows `\` can only be a separator.
return normalizedRelativePath.split(sep).join('/')
}

export function validateFullGitObjectId(value: string, label: string): string {
Expand Down
Loading