From 130d45dbc7f47717139ba401c8d1c084f194aa87 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 01:30:34 +0800 Subject: [PATCH] =?UTF-8?q?fix(git):=20git.diff/git.discard=20=E6=8C=89?= =?UTF-8?q?=E4=BB=93=E5=BA=93=E6=A0=B9=E8=A7=A3=E6=9E=90=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E8=A1=8C=E8=B7=AF=E5=BE=84=EF=BC=8C=E4=B8=8D=E5=86=8D=E6=89=93?= =?UTF-8?q?=E4=B8=AD=E5=AD=90=E7=9B=AE=E5=BD=95=E5=90=8C=E5=90=8D=E6=96=87?= =?UTF-8?q?=E4=BB=B6=EF=BC=88#765=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:`resolveGitPath` 对相对路径先试「会话相对」(`join(cwd, raw)` 存在即采用), 仓库根只作兜底;而变更树的行携带的本来就是**仓库根相对**路径(`git status` 原样 透传)。于是会话 cwd 位于仓库子目录、且该子目录里恰有同名文件时,`git.discard` 还原的是子目录那份(issue 的「还原错文件」),`git.diff` 预览的也是子目录那份 (「预览错内容」)——`git -C checkout -- <解析结果>` 按其自身基准执行, 与「会话相对」这个猜出来的基准不一致。 只改这两条路由:它们是**状态行驱动**的路径,基准由 git 自己给定(仓库根),新增 `resolveStatusPath` 显式按仓库根判定,与后面 spawn 的 `git -C ` 同基准。 `fs.read` 的会话相对优先语义**保持原样**:编辑器 / 文件树的相对路径本就是会话相对 的(`tests/smoke.spec.ts` 的 `src/git.ts` 一类契约),改成仓库根优先会推翻既有 语义;未跟踪文件的 diff 回退本就送绝对路径,不受影响。`src/git.ts` 零改动。 测试:`tests/smoke.spec.ts` 新增「子目录同名文件」用例(会话 cwd=/pkg, `git.discard {path:'README.md'}` 命中仓库根那份、子目录那份仍脏;`git.diff` 预览 仓库根那份),修复前两条均红、修复后全绿。 Refs #765 --- src/index.ts | 33 +++++++++--- tests/smoke.spec.ts | 119 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 122 insertions(+), 30 deletions(-) diff --git a/src/index.ts b/src/index.ts index bdd7d83d..94b67b5f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -165,11 +165,12 @@ function selectedRepoOf(payload: unknown): string | undefined { } /** - * Resolve a path that a git command reported — `git status`/`git diff` - * print paths RELATIVE TO THE REPO TOP LEVEL, which may sit above the - * session cwd (a session inside a subdirectory of a repository). Absolute - * paths pass through; relative ones join the repo root (falling back to the - * cwd when the root cannot be resolved, e.g. a bare directory). + * Resolve a relative path an EDITOR surface carried (the file tree, the + * editor buffer, and `fs.read`, which the untracked-diff fallback reads + * through): the session-relative interpretation wins when it names an + * existing path, with the repository root as the fallback. Git's + * status/diff ROWS deliberately do NOT come through here — they are + * repository-root-relative by construction, see {@link resolveStatusPath}. */ async function resolveGitPath(cwd: string, raw: string, selected?: string): Promise { if (isAbsolute(raw)) return requireAbsolute(resolveSessionPath(cwd, raw)) @@ -183,6 +184,24 @@ async function resolveGitPath(cwd: string, raw: string, selected?: string): Prom return requireAbsolute(join(root, raw)) } +/** + * Resolve a path a git status/diff ROW carried: the changes tree's rows and + * every action they offer (the inline diff preview, and the destructive + * discard). Git prints those paths RELATIVE TO THE REPO TOP LEVEL, which may + * sit above the session cwd, and the client forwards them verbatim — so a + * relative name ALWAYS joins the repository root. Joining the session cwd + * first instead hit a same-named file in the subdirectory the session sits + * in (#765: `git.discard` on the row `README.md` restored the `pkg/README.md` + * one level down and left the root `README.md` — the file the row names — + * dirty). Absolute paths pass through; a cwd outside any repository falls + * back to itself, where the git command fails exactly as it did before. + */ +async function resolveStatusPath(cwd: string, raw: string, selected?: string): Promise { + if (isAbsolute(raw)) return requireAbsolute(resolveSessionPath(cwd, raw)) + const root = await git.repoRoot(cwd, selected).catch(() => cwd) + return requireAbsolute(join(root, raw)) +} + /** How many leading bytes a binary read returns for client-side detect sniffing. */ const READ_HEAD_LIMIT = 4096 @@ -431,7 +450,7 @@ function buildApi( const { cwd } = await gitCwdOf(payload) const record = payload as { path?: unknown; staged?: unknown } const repoRoot = selectedRepoOf(payload) - const path = record.path === undefined ? undefined : await resolveGitPath(cwd, requireString(payload, 'path'), repoRoot) + const path = record.path === undefined ? undefined : await resolveStatusPath(cwd, requireString(payload, 'path'), repoRoot) return { diff: await git.diff(cwd, path, record.staged === true, repoRoot) } }, 'git.stage': async (payload) => { @@ -481,7 +500,7 @@ function buildApi( 'git.discard': async (payload) => { const { cwd } = await gitCwdOf(payload) const repoRoot = selectedRepoOf(payload) - await git.discard(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), repoRoot), repoRoot) + await git.discard(cwd, await resolveStatusPath(cwd, requireString(payload, 'path'), repoRoot), repoRoot) return { ok: true } }, 'git.revert': async (payload) => { diff --git a/tests/smoke.spec.ts b/tests/smoke.spec.ts index 5db78145..23523f6b 100644 --- a/tests/smoke.spec.ts +++ b/tests/smoke.spec.ts @@ -193,33 +193,60 @@ describe('host plugin smoke', () => { }) }) +/** + * Scratch-repository harness shared by the git tests. The fixture's commit + * identity comes from the GIT_AUTHOR / GIT_COMMITTER environment variables, + * confined to the fixture process: no git config is touched anywhere (the + * plugin never sets an identity, and neither does its test fixture). + */ +const FIXTURE_IDENTITY = { + GIT_AUTHOR_NAME: 'dsh-better-sidebar-test', + GIT_AUTHOR_EMAIL: 'test@dsh.invalid', + GIT_COMMITTER_NAME: 'dsh-better-sidebar-test', + GIT_COMMITTER_EMAIL: 'test@dsh.invalid', +} + +/** Run one git command inside a fixture repository (throws on a non-zero exit). */ +const gitRun = (cwd: string, args: string[]): string => { + const result = spawnSync('git', ['-C', cwd, '--no-pager', '-c', 'color.ui=false', '-c', 'core.quotePath=false', ...args], { + encoding: 'utf8', + env: { ...process.env, ...FIXTURE_IDENTITY }, + }) + if (result.status !== 0) { + throw new Error(result.stderr || `git ${args[0] ?? ''} exited with ${String(result.status)}`) + } + return result.stdout +} + +/** + * A fresh repo on branch `main` holding the SAME file name at two levels: + * `README.md` and `pkg/README.md`, committed at `root-v1` / `pkg-v1` and then + * dirtied to `root-DIRTY` / `pkg-DIRTY`. This is the #765 collision — a + * session whose cwd is `/pkg` sends the repository-root-relative status + * path `README.md`, which also names a file one level below it. + */ +const makeNestedScratchRepo = (): string => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-git-nested-')) + gitRun(dir, ['init', '-q']) + // The same eol pin `makeScratchRepo` documents: the content assertions in + // the nested-cwd tests are byte-exact too. + gitRun(dir, ['config', 'core.autocrlf', 'false']) + gitRun(dir, ['checkout', '-q', '-b', 'main']) + writeFileSync(join(dir, 'README.md'), 'root-v1\n') + mkdirSync(join(dir, 'pkg')) + writeFileSync(join(dir, 'pkg', 'README.md'), 'pkg-v1\n') + gitRun(dir, ['add', '-A']) + gitRun(dir, ['commit', '-q', '-m', 'base']) + writeFileSync(join(dir, 'README.md'), 'root-DIRTY\n') + writeFileSync(join(dir, 'pkg', 'README.md'), 'pkg-DIRTY\n') + return dir +} + /** * Destructive git operations (discard / revert / cherry-pick) run against a - * throwaway repository under the OS temp dir — never the plugin repo. The - * fixture's commit identity comes from the GIT_AUTHOR / GIT_COMMITTER - * environment variables, confined to the fixture process: no git config is - * touched anywhere (the plugin never sets an identity, and neither does its - * test fixture). + * throwaway repository under the OS temp dir — never the plugin repo. */ describe('git destructive operations (scratch repository)', () => { - const FIXTURE_IDENTITY = { - GIT_AUTHOR_NAME: 'dsh-better-sidebar-test', - GIT_AUTHOR_EMAIL: 'test@dsh.invalid', - GIT_COMMITTER_NAME: 'dsh-better-sidebar-test', - GIT_COMMITTER_EMAIL: 'test@dsh.invalid', - } - - const gitRun = (cwd: string, args: string[]): string => { - const result = spawnSync('git', ['-C', cwd, '--no-pager', '-c', 'color.ui=false', '-c', 'core.quotePath=false', ...args], { - encoding: 'utf8', - env: { ...process.env, ...FIXTURE_IDENTITY }, - }) - if (result.status !== 0) { - throw new Error(result.stderr || `git ${args[0] ?? ''} exited with ${String(result.status)}`) - } - return result.stdout - } - /** A fresh repo on branch `main` with one committed file `a.txt`. */ const makeScratchRepo = (): string => { const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-git-')) @@ -259,6 +286,30 @@ describe('git destructive operations (scratch repository)', () => { } }) + it('discards the repo-root file, not the same-named one under the session cwd (#765)', async () => { + // The changes tree's rows carry REPOSITORY-root-relative paths, so a + // session whose cwd is `/pkg` still means `/README.md` when + // its row says `README.md`. Resolving that name session-relative first + // restored the same-named file one level down and left the file the row + // actually named dirty (the destructive half of #765). + const dir = makeNestedScratchRepo() + try { + const route = mountWithSettings() + const result = await invoke(route, 'git.discard', { + sessionId: 's-nested', + cwd: join(dir, 'pkg'), + path: 'README.md', + }) + expect(result.ok).toBe(true) + expect(readFileSync(join(dir, 'README.md'), 'utf8')).toBe('root-v1\n') + // The same-named file under the session cwd was never the target. + expect(readFileSync(join(dir, 'pkg', 'README.md'), 'utf8')).toBe('pkg-DIRTY\n') + expect(gitRun(dir, ['status', '--porcelain'])).toBe(' M pkg/README.md\n') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + it('revert creates a revert commit', async () => { const dir = makeScratchRepo() try { @@ -538,6 +589,28 @@ describe('session cwd resolution over the API route', () => { expect(typeof value.value?.diff).toBe('string') }) + it('git.diff previews the repo-root file when the session cwd holds a same-named one (#765)', async () => { + // Same rows, but the collision is real: `/pkg/README.md` EXISTS, so + // a session-relative first resolution previewed that file's change while + // the row named `/README.md` (the preview half of #765). + const dir = makeNestedScratchRepo() + try { + const route = mount({ + sessions: { + get: () => ({ header: { cwd: join(dir, 'pkg') } }), + }, + }) + const result = await invoke(route, 'git.diff', { sessionId: 's-nested', path: 'README.md', staged: false }) + expect(result.ok).toBe(true) + const diff = (result as unknown as { value?: { diff: string } }).value?.diff ?? '' + expect(diff).toContain('a/README.md b/README.md') + expect(diff).toContain('+root-DIRTY') + expect(diff).not.toContain('pkg-DIRTY') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + it('fs.read resolves repo-relative paths (untracked diff fallback)', async () => { const route = mount({ sessions: {