fix(git): 路径按字面匹配,防「丢弃改动」误伤同名文件

This commit is contained in:
unsc9 committed 2026-11-06 12:38:22 +08:00
1 parent 6e0ea81663
commit 5cdf7e0ea2
3 files changed
+200 -14

No files matched your search

+20 -13
View File
@@ -538,6 +538,13 @@ export function runGit(cwd: string, args: string[], timeoutMs = 30_000, options:
})
}
/** 路径是用户给的字面文件名:不加这个全局选项,git 会把 `a[1].txt` 里的
* `[1]` 当 pathspec 通配符,连 `a1.txt` 一起丢弃/暂存(改动不可恢复)。
* 选项必须前置在子命令前才是 git 全局选项。 */
function literalPathspec(path: string | undefined): string[] {
return path === undefined ? [] : ['--literal-pathspecs']
}
/** One parsed `git blame --porcelain` row (the editor's hover blame). */
export interface GitBlameLine {
/** 1-based line number in the file as it exists in the worktree. */
@@ -633,7 +640,7 @@ export async function blame(
try {
const root = await repoRoot(cwd, selected)
const output = await runGit(root, [
'blame', '--porcelain', '-L', `${String(startLine)},${String(endLine)}`, '--', path,
...literalPathspec(path), 'blame', '--porcelain', '-L', `${String(startLine)},${String(endLine)}`, '--', path,
])
return parseBlamePorcelain(output)
} catch {
@@ -860,9 +867,7 @@ function numstatPathsof(porcelainZ: string): string[] | undefined {
* both numstat diffs: the counts only ever ride rows the status read itself
* reports, and limiting the diffs to those paths is what keeps an unignored
* nested `node_modules` (59 631 entries / 9.24 MB of numstat) out of the two
* whole-repo walks. `--literal-pathspecs` is required: porcelain paths are
* literal file names, and without it a name like `:colon.txt` is parsed as
* pathspec magic and silently loses its counts.
* whole-repo walks. 两条 numstat 也要字面 pathspec,理由见 literalPathspec()。
*
* Each side's reading lands on its own field of the entry
* ({@link GitStatusEntry} documents why the two are never summed).
@@ -891,9 +896,6 @@ export async function status(cwd: string, selected?: string): Promise<GitStatusR
// to the whole-repo diff); `[]` = no tracked change at all, so both diffs are
// known empty and neither process is spawned.
if (pathspec === undefined || pathspec.length > 0) {
// `--literal-pathspecs` must precede the subcommand (`git <flag> diff …`).
// Porcelain paths are literal file names, and without it a name like
// `:colon.txt` is parsed as pathspec magic and silently loses its counts.
const literal = pathspec === undefined ? [] : ['--literal-pathspecs']
const paths = pathspec === undefined ? [] : ['--', ...pathspec]
const [unstaged, staged] = await Promise.all([
@@ -1009,7 +1011,7 @@ export async function resolveWorktree(cwd: string, requested?: string): Promise<
/** Diff text of the worktree (unstaged) or the index (staged). */
export async function diff(cwd: string, path: string | undefined, staged: boolean, selected?: string): Promise<string> {
const root = await repoRoot(cwd, selected)
const args = ['diff', '--no-ext-diff', '--no-color', '-U3']
const args = [...literalPathspec(path), 'diff', '--no-ext-diff', '--no-color', '-U3']
if (staged) args.push('--cached')
if (path !== undefined) args.push('--', path)
return runGit(root, args)
@@ -1027,22 +1029,27 @@ export async function diff(cwd: string, path: string | undefined, staged: boolea
*/
export async function diffHead(cwd: string, path: string | undefined, selected?: string): Promise<string> {
const root = await repoRoot(cwd, selected)
const literal = literalPathspec(path)
const tail = path !== undefined ? ['--', path] : []
try {
return await runGit(root, ['diff', '--no-ext-diff', '--no-color', '-U3', 'HEAD', ...tail])
return await runGit(root, [...literal, 'diff', '--no-ext-diff', '--no-color', '-U3', 'HEAD', ...tail])
} catch {
return runGit(root, ['diff', '--no-ext-diff', '--no-color', '-U3', '--cached', ...tail])
return runGit(root, [...literal, 'diff', '--no-ext-diff', '--no-color', '-U3', '--cached', ...tail])
}
}
/** Stage paths (all when path is undefined). */
export async function stage(cwd: string, path: string | undefined, selected?: string): Promise<void> {
await runGit(await repoRoot(cwd, selected), ['add', '-A', ...(path !== undefined ? ['--', path] : [])])
await runGit(await repoRoot(cwd, selected), [
...literalPathspec(path), 'add', '-A', ...(path !== undefined ? ['--', path] : []),
])
}
/** Unstage paths (all when path is undefined). */
export async function unstage(cwd: string, path: string | undefined, selected?: string): Promise<void> {
await runGit(await repoRoot(cwd, selected), ['reset', '-q', ...(path !== undefined ? ['--', path] : [])])
await runGit(await repoRoot(cwd, selected), [
...literalPathspec(path), 'reset', '-q', ...(path !== undefined ? ['--', path] : []),
])
}
/** Commit the staged changes with a message (global identity untouched). */
@@ -1110,7 +1117,7 @@ export async function commitDiff(cwd: string, hash: string, selected?: string):
/** Discard the worktree changes of one path (`git checkout -- <path>`; the index is untouched). */
export async function discard(cwd: string, path: string, selected?: string): Promise<void> {
await runGit(await repoRoot(cwd, selected), ['checkout', '--', path])
await runGit(await repoRoot(cwd, selected), [...literalPathspec(path), 'checkout', '--', path])
}
/** Revert one commit onto the current branch with an auto-generated message.
+91
View File
@@ -0,0 +1,91 @@
/**
* 用户给的路径是字面文件名:git 默认把 `a[1].txt` 里的 `[1]` 当 pathspec
* 通配符,会连 `a1.txt` 一起命中——丢弃改动不可恢复。这里钉住每个吃路径的
* 子命令都把 `--literal-pathspecs` 作为全局选项前置在子命令前,且原有的
* `--` 分隔与字面路径原样保留。
*
* 与 git-spawn.spec.ts 一样 mock 掉 spawn:只有拿到 argv 才能断言全局选项的
* 顺序,真实 git 只会把结果返回来。
*/
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 { blame, diff, diffHead, discard, stage, unstage } from '../src/git.ts'
/** `a[1].txt` 是两平台都合法的良构方括号名;`a1.txt` 是它会被误伤的同伴。 */
const LITERAL = 'a[1].txt'
const PLAIN = 'a1.txt'
const CWD = '/repo'
afterEach(() => {
spawnMock.mockReset()
})
/** 假的 git 子进程:`rev-parse --show-toplevel` 回填仓库根,其余返回空。 */
function fakeGit(_file: string, args: string[]): EventEmitter {
const child = new EventEmitter()
const stdout = new PassThrough()
const stderr = new PassThrough()
Object.assign(child, { stdout, stderr, kill: vi.fn() })
const cwd = args[args.indexOf('-C') + 1] ?? ''
queueMicrotask(() => {
stdout.end(args.includes('rev-parse') ? `${cwd}\n` : '')
stderr.end()
child.emit('close', 0)
})
return child
}
const cases: { name: string; subcommand: string; run: () => Promise<unknown> }[] = [
{ name: 'discard', subcommand: 'checkout', run: () => discard(CWD, LITERAL) },
{ name: 'stage', subcommand: 'add', run: () => stage(CWD, LITERAL) },
{ name: 'unstage', subcommand: 'reset', run: () => unstage(CWD, LITERAL) },
{ name: 'diff (unstaged)', subcommand: 'diff', run: () => diff(CWD, LITERAL, false) },
{ name: 'diff (staged)', subcommand: 'diff', run: () => diff(CWD, LITERAL, true) },
{ name: 'diffHead', subcommand: 'diff', run: () => diffHead(CWD, LITERAL) },
{ name: 'blame', subcommand: 'blame', run: () => blame(CWD, LITERAL, 1, 1) },
]
describe('字面 pathspec(防止误伤同名文件)', () => {
for (const { name, subcommand, run } of cases) {
it(`${name}:--literal-pathspecs 前置在子命令前,且只带字面路径`, async () => {
spawnMock.mockImplementation(fakeGit)
await run()
// 目标命令是唯一带用户路径的那次 spawn(其余是仓库发现的 rev-parse)。
const argv = spawnMock.mock.calls
.map(call => call[1] as string[])
.find(args => args.includes(LITERAL))
expect(argv).toBeDefined()
const full = argv!
expect(full).toContain('--literal-pathspecs')
// 必须排在子命令之前,否则 git 把它当子命令参数、全局选项不生效。
expect(full.indexOf('--literal-pathspecs')).toBeLessThan(full.indexOf(subcommand))
// 原有的 `--` 分隔与字面路径不变,且路径是最后一个操作数。
expect(full).toContain('--')
expect(full.indexOf('--')).toBeLessThan(full.indexOf(LITERAL))
expect(full.at(-1)).toBe(LITERAL)
// 从未把 `a[1].txt` 展开/替换成 `a1.txt`。
expect(full).not.toContain(PLAIN)
})
}
it('全量操作(path 为 undefined)不引入多余的全局选项', async () => {
spawnMock.mockImplementation(fakeGit)
await Promise.all([
stage(CWD, undefined),
unstage(CWD, undefined),
diff(CWD, undefined, false),
diffHead(CWD, undefined),
])
for (const call of spawnMock.mock.calls) {
expect(call[1] as string[]).not.toContain('--literal-pathspecs')
}
})
})
+89 -1
View File
@@ -6,7 +6,7 @@ import { join } from 'node:path'
import { promisify } from 'node:util'
import { describe, expect, it } from 'vitest'
import { parseUnifiedDiff } from '../src/client/diff/rows.ts'
import { branches, checkout, currentBranch, log, parseLogLines, parseNumstat, parsePorcelainZ, parseStatusPorcelainV2Z, repoRoots, status } from '../src/git.ts'
import { branches, checkout, currentBranch, diff, discard, log, parseLogLines, parseNumstat, parsePorcelainZ, parseStatusPorcelainV2Z, repoRoots, stage, status, unstage } from '../src/git.ts'
import { removeTree } from './temp-tree.ts'
const execFileAsync = promisify(execFile)
@@ -685,3 +685,91 @@ describe('numstat line counts (#131)', () => {
}
})
})
/**
* 数据防误伤:`a[1].txt` 与 `a1.txt` 在 Windows / Linux 都是合法文件名,而
* git 默认把前者里的 `[1]` 当 pathspec 通配符,后者会被一起选中。丢弃改动
* 不可恢复,所以这里用真实 git 钉住「只动目标文件」。
*/
describe('字面 pathspec 不误伤同名文件', () => {
function repo(): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-git-literal-'))
execFileSync('git', ['init', '-q'], { cwd: root })
execFileSync('git', ['config', 'user.email', 't@t'], { cwd: root })
execFileSync('git', ['config', 'user.name', 't'], { cwd: root })
// Windows 上默认 autocrlf 会把 checkout 回来的内容换成 CRLF。
execFileSync('git', ['config', 'core.autocrlf', 'false'], { cwd: root })
writeFileSync(join(root, 'a[1].txt'), 'base-A\n')
writeFileSync(join(root, 'a1.txt'), 'base-B\n')
execFileSync('git', ['add', '-A'], { cwd: root })
execFileSync('git', ['commit', '-q', '-m', 'base'], { cwd: root })
return root
}
const statusLines = (root: string): string => execFileSync(
'git', ['-c', 'core.quotePath=false', 'status', '--porcelain=v1'], { cwd: root, encoding: 'utf8' },
)
it('discard 只还原 a[1].txt,a1.txt 的改动保留', async () => {
const root = repo()
try {
writeFileSync(join(root, 'a[1].txt'), 'EDIT-A\n')
writeFileSync(join(root, 'a1.txt'), 'EDIT-B\n')
await discard(root, 'a[1].txt')
expect(readFileSync(join(root, 'a[1].txt'), 'utf8')).toBe('base-A\n')
expect(readFileSync(join(root, 'a1.txt'), 'utf8')).toBe('EDIT-B\n')
} finally {
removeTree(root)
}
})
it('stage 只暂存 a[1].txt', async () => {
const root = repo()
try {
writeFileSync(join(root, 'a[1].txt'), 'EDIT-A\n')
writeFileSync(join(root, 'a1.txt'), 'EDIT-B\n')
await stage(root, 'a[1].txt')
const rows = statusLines(root)
expect(rows).toContain('M a[1].txt')
expect(rows).toContain(' M a1.txt')
} finally {
removeTree(root)
}
})
it('unstage 只取消 a[1].txt 的暂存', async () => {
const root = repo()
try {
writeFileSync(join(root, 'a[1].txt'), 'EDIT-A\n')
writeFileSync(join(root, 'a1.txt'), 'EDIT-B\n')
execFileSync('git', ['add', '-A'], { cwd: root })
await unstage(root, 'a[1].txt')
const rows = statusLines(root)
expect(rows).toContain(' M a[1].txt')
expect(rows).toContain('M a1.txt')
} finally {
removeTree(root)
}
})
it('diff 只输出 a[1].txt 的补丁', async () => {
const root = repo()
try {
writeFileSync(join(root, 'a[1].txt'), 'EDIT-A\n')
writeFileSync(join(root, 'a1.txt'), 'EDIT-B\n')
const patch = await diff(root, 'a[1].txt', false)
expect(patch).toContain('a[1].txt')
expect(patch).not.toContain('a1.txt')
} finally {
removeTree(root)
}
})
})