fix(git): git.diff/git.discard 按仓库根解析状态行路径,不再打中子目录同名文件(#765)
根因:`resolveGitPath` 对相对路径先试「会话相对」(`join(cwd, raw)` 存在即采用),
仓库根只作兜底;而变更树的行携带的本来就是**仓库根相对**路径(`git status` 原样
透传)。于是会话 cwd 位于仓库子目录、且该子目录里恰有同名文件时,`git.discard`
还原的是子目录那份(issue 的「还原错文件」),`git.diff` 预览的也是子目录那份
(「预览错内容」)——`git -C <repoRoot> checkout -- <解析结果>` 按其自身基准执行,
与「会话相对」这个猜出来的基准不一致。
只改这两条路由:它们是**状态行驱动**的路径,基准由 git 自己给定(仓库根),新增
`resolveStatusPath` 显式按仓库根判定,与后面 spawn 的 `git -C <repoRoot>` 同基准。
`fs.read` 的会话相对优先语义**保持原样**:编辑器 / 文件树的相对路径本就是会话相对
的(`tests/smoke.spec.ts` 的 `src/git.ts` 一类契约),改成仓库根优先会推翻既有
语义;未跟踪文件的 diff 回退本就送绝对路径,不受影响。`src/git.ts` 零改动。
测试:`tests/smoke.spec.ts` 新增「子目录同名文件」用例(会话 cwd=<repo>/pkg,
`git.discard {path:'README.md'}` 命中仓库根那份、子目录那份仍脏;`git.diff` 预览
仓库根那份),修复前两条均红、修复后全绿。
Refs #765
This commit is contained in:
1 parent
1da9e92f79
commit
130d45dbc7
2 files changed
+122
-30
No files matched your search
+26
-7
@@ -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<string> {
|
||||
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<string> {
|
||||
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) => {
|
||||
|
||||
+96
-23
@@ -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 `<repo>/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 `<repo>/pkg` still means `<repo>/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: `<repo>/pkg/README.md` EXISTS, so
|
||||
// a session-relative first resolution previewed that file's change while
|
||||
// the row named `<repo>/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: {
|
||||
|
||||
Reference in new issue
Block a user