From e0a578865fe67b976d149f8fb52f87306a8c9663 Mon Sep 17 00:00:00 2001 From: Sakana <15715093608@163.com> Date: Tue, 1 Dec 2026 22:11:29 +0800 Subject: [PATCH 1/4] fix(service-git)!: resolve selected files from the worktree root A dashboard started in a package directory lists paths from the worktree root. Passing those paths back to Git could preview or stage a different file with the same name. Run file operations with literal paths from the appropriate directory. Keep explicit cwd-relative paths in mixed requests and preserve the spelling of filenames in history and committed file reads. BREAKING CHANGE: Bare filenames in a nested Git service select files at the worktree root. Use ./ to select a file in the service directory. For multiple files, pass a directory or an explicit list of filenames instead of a Git pathspec pattern. --- docs/content/5.add-ons/2.services/2.git.md | 6 ++ services/git/src/git.ts | 43 ++++++++++ services/git/src/operations.ts | 55 +++++------- services/git/src/types.ts | 10 +-- services/git/test/_repo.ts | 22 ++++- services/git/test/git.test.ts | 97 +++++++++++++++++++++- 6 files changed, 192 insertions(+), 41 deletions(-) diff --git a/docs/content/5.add-ons/2.services/2.git.md b/docs/content/5.add-ons/2.services/2.git.md index d9414d6f3..cf6a45ee1 100644 --- a/docs/content/5.add-ons/2.services/2.git.md +++ b/docs/content/5.add-ons/2.services/2.git.md @@ -35,6 +35,12 @@ A hub installs a shared instance with `initHub({ services: [createGitService(opt |--------|------|-------------| | `cwd` | `string` | Repository directory to operate on. Defaults to the context's `cwd`; the repo root is discovered once (`rev-parse --show-toplevel`) and memoized. | +You can pass a path from `status` directly to `diff`, `log`, `readFile`, `stage`, or `unstage`. +The service treats each file or directory name literally, including brackets in names like `pages/[id].tsx`. +For example, when `cwd` is `packages/app`, `README.md` selects the README at the repository root. +Both `packages/app/README.md` and `./README.md` select the package README. +Pass `.` to `stage` or `unstage` to select the working directory and its contents. + ## RPC functions Registered under `devframes:service:git:*`. Reads are `query`; writes are `action`. Write ops are **always exposed**; authorization is the host's connection-trust boundary. The service defines no `dump`/`snapshot`; a devframe bakes what it needs via `snapshotRpc`. diff --git a/services/git/src/git.ts b/services/git/src/git.ts index 0855b2053..de496fc1d 100644 --- a/services/git/src/git.ts +++ b/services/git/src/git.ts @@ -1,4 +1,5 @@ import { execFile } from 'node:child_process' +import { isAbsolute, sep } from 'node:path' import process from 'node:process' import { promisify } from 'node:util' @@ -10,6 +11,45 @@ export const RECORD = '\x1E' const MAX_BUFFER = 1024 * 1024 * 64 +const CWD_RELATIVE = sep === '\\' + ? /^\.{1,2}(?:[/\\]|$)/ + : /^\.{1,2}(?:\/|$)/ + +/** Keep whole status lists and whole cwd-relative lists in their original spelling. */ +export function fileCommand(cwd: string, root: string, command: string[], paths: string[]) { + if (paths.length === 0) + return { cwd, args: command } + const fromCwd = cwd !== root && paths.some(path => CWD_RELATIVE.test(path)) + if (!fromCwd || paths.every(path => CWD_RELATIVE.test(path) || isAbsolute(path))) { + return { + cwd: fromCwd ? cwd : root, + args: [ + '--literal-pathspecs', + ...command, + '--', + ...paths, + ], + } + } + + // In a mixed request only root-relative names need an anchor. Keep cwd-relative names verbatim. + const pathspecs = paths.map((path) => { + if (!path || CWD_RELATIVE.test(path) || isAbsolute(path)) + return path + return `:(top)${path}` + }) + return { + cwd, + args: [ + '--no-literal-pathspecs', + '--noglob-pathspecs', + ...command, + '--', + ...pathspecs, + ], + } +} + export interface GitRunResult { stdout: string stderr: string @@ -20,6 +60,8 @@ export interface GitRunResult { * tolerate failure (e.g. "no upstream configured") should use {@link tryGit}. */ export async function runGit(cwd: string, args: string[]): Promise { + // Inherited glob and case-folding modes conflict with the service's exact file selections. + const selectingFiles = args[0] === '--literal-pathspecs' || args[0] === '--no-literal-pathspecs' const { stdout, stderr } = await execFileAsync('git', args, { cwd, maxBuffer: MAX_BUFFER, @@ -27,6 +69,7 @@ export async function runGit(cwd: string, args: string[]): Promise /** Force plain, locale-independent output so parsers stay stable. */ env: { ...process.env, + ...(selectingFiles && { GIT_GLOB_PATHSPECS: '0', GIT_ICASE_PATHSPECS: '0' }), GIT_PAGER: 'cat', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C', diff --git a/services/git/src/operations.ts b/services/git/src/operations.ts index e8f277ee7..5afc9100c 100644 --- a/services/git/src/operations.ts +++ b/services/git/src/operations.ts @@ -14,6 +14,7 @@ import type { Tag, } from './types' import { + fileCommand, gitErrorMessage, isSafeRevision, RECORD, @@ -387,6 +388,15 @@ export function createGitOps(cwd: string): GitServiceApi { return result } + async function updateIndex(command: string[], paths: string[]): Promise { + const root = await resolveRoot() + if (root && paths.length > 0) { + const selection = fileCommand(cwd, root, command, paths) + await runGit(selection.cwd, selection.args) + } + return status() + } + async function readCommit(hash: string, includePatch: boolean): Promise { if (!isSafeRevision(hash)) return { ...EMPTY_DETAIL, isRepo: true } @@ -508,13 +518,8 @@ export function createGitOps(cwd: string): GitServiceApi { } command.push('--end-of-options', ref) } - // Pathspec after `--`: everything past it is treated as a path, never - // an option, so client paths need no dash guard here. - const paths = (args.paths ?? []).map(p => p.trim()).filter(Boolean) - if (paths.length > 0) - command.push('--', ...paths) - - const raw = await tryGit(cwd, command) + const selection = fileCommand(cwd, root, command, (args.paths ?? []).filter(Boolean)) + const raw = await tryGit(selection.cwd, selection.args) const commits = raw ? parseLog(raw) : [] @@ -537,7 +542,7 @@ export function createGitOps(cwd: string): GitServiceApi { }, async readFile(args) { - const path = (args?.path ?? '').trim() + const path = args?.path ?? '' const ref = args?.ref?.trim() || 'HEAD' const root = await resolveRoot() const base: GitFile = { @@ -596,14 +601,11 @@ export function createGitOps(cwd: string): GitServiceApi { const base = staged ? ['diff', '--cached'] : ['diff'] - const scope = path - ? ['--', path] + const paths = path + ? [path] : [] - const numstatRaw = await tryGit(cwd, [ - ...base, - '--numstat', - ...scope, - ]) + const summary = fileCommand(cwd, root, [...base, '--numstat'], paths) + const numstatRaw = await tryGit(summary.cwd, summary.args) const files = numstatRaw ? parseNumstat(numstatRaw) : [] @@ -611,10 +613,8 @@ export function createGitOps(cwd: string): GitServiceApi { let patch: string | null = null let truncated = false if (path) { - const { stdout } = await runGit(cwd, [ - ...base, - ...scope, - ]) + const selection = fileCommand(cwd, root, base, paths) + const { stdout } = await runGit(selection.cwd, selection.args) ;({ patch, truncated } = clipPatch(stdout)) } @@ -685,21 +685,8 @@ export function createGitOps(cwd: string): GitServiceApi { return { isRepo: true, tags } }, - async stage(args) { - const paths = args?.paths ?? [] - const root = await resolveRoot() - if (root && paths.length > 0) - await runGit(cwd, ['add', '--', ...paths]) - return status() - }, - - async unstage(args) { - const paths = args?.paths ?? [] - const root = await resolveRoot() - if (root && paths.length > 0) - await runGit(cwd, ['restore', '--staged', '--', ...paths]) - return status() - }, + stage: args => updateIndex(['add'], args?.paths ?? []), + unstage: args => updateIndex(['restore', '--staged'], args?.paths ?? []), async commit(args) { const message = (args?.message ?? '').trim() diff --git a/services/git/src/types.ts b/services/git/src/types.ts index ff8b45bdc..a18d144a5 100644 --- a/services/git/src/types.ts +++ b/services/git/src/types.ts @@ -67,7 +67,7 @@ export interface LogArgs { skip?: number /** Optional ref/branch to read history from (default: current HEAD). */ ref?: string - /** Restrict history to commits that touched these repo-relative path(s). */ + /** Limit history to these files or directories. Paths start at the repo root, or at the service cwd with `./`. */ paths?: string[] } @@ -112,7 +112,7 @@ export interface GitTags { } export interface ReadFileArgs { - /** Repo-relative path to the file. */ + /** File path from the repo root, or from the service cwd with `./`. */ path: string /** Commit-ish to read the file from (default: current HEAD). */ ref?: string @@ -155,7 +155,7 @@ export interface GitDiff { } export interface DiffArgs { - /** Limit the diff to a single path; omit for the whole tree. */ + /** File path from the repo root, or from the service cwd with `./`. Omit for the whole tree. */ path?: string /** Diff the index against HEAD instead of the working tree. */ staged?: boolean @@ -206,12 +206,12 @@ export interface ShowArgs { } export interface StageArgs { - /** Paths to stage (`git add`). */ + /** Paths to stage from the repo root. Use `./` or `.` for the service cwd. */ paths: string[] } export interface UnstageArgs { - /** Paths to unstage (`git restore --staged`). */ + /** Paths to unstage from the repo root. Use `./` or `.` for the service cwd. */ paths: string[] } diff --git a/services/git/test/_repo.ts b/services/git/test/_repo.ts index 03e429a4f..aa77e1dd5 100644 --- a/services/git/test/_repo.ts +++ b/services/git/test/_repo.ts @@ -1,7 +1,7 @@ import { execFileSync } from 'node:child_process' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import process from 'node:process' export interface TempRepo { @@ -120,6 +120,26 @@ export function createPathRepo(): TempRepo { } } +/** Give each file its own commit and a distinguishable working-tree edit. */ +export function createEditedRepo(files: [string, string][]): TempRepo { + const repo = createTempDir() + git(repo.dir, ['init', '-b', 'main']) + git(repo.dir, ['config', 'diff.relative', 'false']) + for (const [file, label] of files) { + mkdirSync(dirname(join(repo.dir, file)), { recursive: true }) + write(repo.dir, file, `${label} committed\n`) + git(repo.dir, [ + '--literal-pathspecs', + 'add', + '--', + file, + ]) + git(repo.dir, ['commit', '-m', `add ${label}`]) + write(repo.dir, file, `${label} edited\n`) + } + return repo +} + /** Create an empty (non-git) temp directory. */ export function createTempDir(): TempRepo { const dir = mkdtempSync(join(tmpdir(), 'devframe-git-bare-')) diff --git a/services/git/test/git.test.ts b/services/git/test/git.test.ts index a50afe56f..2cb892029 100644 --- a/services/git/test/git.test.ts +++ b/services/git/test/git.test.ts @@ -5,9 +5,13 @@ import { join } from 'node:path' import { createHostContext } from 'devframe/node' import { afterEach, describe, expect, it } from 'vitest' import { createGitService } from '../src/index' -import { createPathRepo, createTempDir, createTempRepo } from './_repo' +import { createEditedRepo, createPathRepo, createTempDir, createTempRepo } from './_repo' const cleanups: (() => void)[] = [] +const readmes: [string, string][] = [ + ['README.md', 'root'], + ['packages/app/README.md', 'package'], +] afterEach(() => { for (const fn of cleanups.splice(0)) fn() @@ -231,6 +235,97 @@ describe('@devframes/service-git', () => { expect(log.commits[0].subject).toBe('test: commit from service') }) + it.each(['.', 'packages/app'])('previews and reads the selected file from %s', async (cwd) => { + const repo = createEditedRepo(readmes) + cleanups.push(repo.cleanup) + const git = await createGit(join(repo.dir, cwd)) + const paths = (await git.status()).unstaged.map(file => file.path) + expect(paths).toEqual(['README.md', 'packages/app/README.md']) + const root = { file: paths[0], location: 'root' } + const pkg = { file: paths[1], location: 'package' } + const selections = [ + { path: root.file, ...root }, + { path: pkg.file, ...pkg }, + { + path: './README.md', + ...(cwd === '.' + ? root + : pkg), + }, + ] + for (const { path, file, location } of selections) { + const diff = await git.diff({ path }) + expect(diff.files.map(f => f.path)).toEqual([file]) + expect(diff.patch).toContain(`+${location} edited`) + const log = await git.log({ + paths: [path], + }) + expect(log.commits.map(c => c.subject)).toEqual([`add ${location}`]) + expect((await git.readFile({ path })).content).toBe(`${location} committed\n`) + } + + await git.stage({ paths }) + for (const { path, file, location } of selections) { + const diff = await git.diff({ path, staged: true }) + expect(diff.files.map(f => f.path)).toEqual([file]) + expect(diff.patch).toContain(`+${location} edited`) + } + }) + + it('stages and unstages root and explicit package paths in the same request', async () => { + const repo = createEditedRepo(readmes) + cleanups.push(repo.cleanup) + const git = await createGit(join(repo.dir, 'packages/app')) + const root = 'README.md' + const pkg = 'packages/app/README.md' + async function stagedAfter(action: 'stage' | 'unstage', ...paths: string[]) { + const status = await git[action]({ paths }) + return status.staged.map(f => f.path) + } + + expect(await stagedAfter('stage', root)).toEqual([root]) + expect(await stagedAfter('stage', '.')).toEqual([root, pkg]) + expect(await stagedAfter('unstage', root)).toEqual([pkg]) + expect(await stagedAfter('unstage', pkg)).toEqual([]) + expect(await stagedAfter('stage', '.')).toEqual([pkg]) + expect(await stagedAfter('unstage', './README.md')).toEqual([]) + expect(await stagedAfter('stage', root, './README.md')).toEqual([root, pkg]) + expect(await stagedAfter('unstage', '.')).toEqual([root]) + expect(await stagedAfter('stage', pkg)).toEqual([root, pkg]) + expect(await stagedAfter('unstage', root, './README.md')).toEqual([]) + }) + + it('selects literal status paths for routes with brackets and names with spaces', async () => { + const route = 'pages/[id].tsx' + const space = ' note.md' + const repo = createEditedRepo([ + [route, 'route'], + ['pages/i.tsx', 'neighbor'], + [space, 'space'], + ['note.md', 'plain'], + ]) + cleanups.push(repo.cleanup) + const git = await createGit(join(repo.dir, 'pages')) + + expect((await git.diff({ path: route })).files.map(f => f.path)).toEqual([route]) + const log = await git.log({ + paths: ['./[id].tsx', space], + }) + expect(log.commits.map(c => c.subject)).toEqual(['add space', 'add route']) + expect((await git.readFile({ path: space })).content).toBe('space committed\n') + const staged = await git.stage({ + paths: [route, '../ note.md'], + }) + expect(staged.staged.map(f => f.path)).toEqual([space, route]) + await git.stage({ + paths: ['pages/i.tsx'], + }) + const remaining = await git.unstage({ + paths: [route, space], + }) + expect(remaining.staged.map(f => f.path)).toEqual(['pages/i.tsx']) + }) + it('rejects an empty commit message', async () => { const repo = createTempRepo() cleanups.push(repo.cleanup) From 040d9333e6156e90bc7ac41fed3ce4a1f705238f Mon Sep 17 00:00:00 2001 From: Sakana <15715093608@163.com> Date: Tue, 1 Dec 2026 22:20:37 +0800 Subject: [PATCH 2/4] fix(service-git): preserve the configured Git working directory Keep the Git subprocess in its original directory so relative worktree and index settings apply to the same repository. Anchor repository-relative filenames with Git pathspecs and preserve the configured diff headers for explicit and absolute package paths. --- services/git/src/git.ts | 58 +++++++++++++++++----------------- services/git/src/operations.ts | 19 +++++------ services/git/test/_repo.ts | 8 +++-- services/git/test/git.test.ts | 43 ++++++++++++++++++++++++- 4 files changed, 85 insertions(+), 43 deletions(-) diff --git a/services/git/src/git.ts b/services/git/src/git.ts index de496fc1d..854f4dc16 100644 --- a/services/git/src/git.ts +++ b/services/git/src/git.ts @@ -15,39 +15,39 @@ const CWD_RELATIVE = sep === '\\' ? /^\.{1,2}(?:[/\\]|$)/ : /^\.{1,2}(?:\/|$)/ -/** Keep whole status lists and whole cwd-relative lists in their original spelling. */ -export function fileCommand(cwd: string, root: string, command: string[], paths: string[]) { - if (paths.length === 0) - return { cwd, args: command } - const fromCwd = cwd !== root && paths.some(path => CWD_RELATIVE.test(path)) - if (!fromCwd || paths.every(path => CWD_RELATIVE.test(path) || isAbsolute(path))) { - return { - cwd: fromCwd ? cwd : root, - args: [ - '--literal-pathspecs', - ...command, - '--', - ...paths, - ], - } - } +function isRootPath(path: string): boolean { + return !!path && !CWD_RELATIVE.test(path) && !isAbsolute(path) +} - // In a mixed request only root-relative names need an anchor. Keep cwd-relative names verbatim. - const pathspecs = paths.map((path) => { - if (!path || CWD_RELATIVE.test(path) || isAbsolute(path)) - return path - return `:(top)${path}` - }) - return { - cwd, - args: [ - '--no-literal-pathspecs', - '--noglob-pathspecs', +/** Keep Git in the service cwd so relative Git settings still identify the same worktree and index. */ +export function fileArgs(cwd: string, root: string, command: string[], paths: string[]): string[] { + if (paths.length === 0) + return command + if (cwd === root || !paths.some(isRootPath)) { + return [ + '--literal-pathspecs', ...command, '--', - ...pathspecs, - ], + ...paths, + ] } + + // The top flag anchors only repo-relative names. Git still receives a single list of literal paths. + const pathspecs = paths.map(path => isRootPath(path) + ? `:(top)${path}` + : path) + // diff.relative can hide a selected root file outside the service directory. + const options = command[0] === 'diff' + ? ['--no-relative'] + : [] + return [ + '--no-literal-pathspecs', + '--noglob-pathspecs', + ...command, + ...options, + '--', + ...pathspecs, + ] } export interface GitRunResult { diff --git a/services/git/src/operations.ts b/services/git/src/operations.ts index 5afc9100c..55d289850 100644 --- a/services/git/src/operations.ts +++ b/services/git/src/operations.ts @@ -14,7 +14,7 @@ import type { Tag, } from './types' import { - fileCommand, + fileArgs, gitErrorMessage, isSafeRevision, RECORD, @@ -390,10 +390,8 @@ export function createGitOps(cwd: string): GitServiceApi { async function updateIndex(command: string[], paths: string[]): Promise { const root = await resolveRoot() - if (root && paths.length > 0) { - const selection = fileCommand(cwd, root, command, paths) - await runGit(selection.cwd, selection.args) - } + if (root && paths.length > 0) + await runGit(cwd, fileArgs(cwd, root, command, paths)) return status() } @@ -518,8 +516,8 @@ export function createGitOps(cwd: string): GitServiceApi { } command.push('--end-of-options', ref) } - const selection = fileCommand(cwd, root, command, (args.paths ?? []).filter(Boolean)) - const raw = await tryGit(selection.cwd, selection.args) + const paths = (args.paths ?? []).filter(Boolean) + const raw = await tryGit(cwd, fileArgs(cwd, root, command, paths)) const commits = raw ? parseLog(raw) : [] @@ -604,8 +602,8 @@ export function createGitOps(cwd: string): GitServiceApi { const paths = path ? [path] : [] - const summary = fileCommand(cwd, root, [...base, '--numstat'], paths) - const numstatRaw = await tryGit(summary.cwd, summary.args) + const summary = fileArgs(cwd, root, [...base, '--numstat'], paths) + const numstatRaw = await tryGit(cwd, summary) const files = numstatRaw ? parseNumstat(numstatRaw) : [] @@ -613,8 +611,7 @@ export function createGitOps(cwd: string): GitServiceApi { let patch: string | null = null let truncated = false if (path) { - const selection = fileCommand(cwd, root, base, paths) - const { stdout } = await runGit(selection.cwd, selection.args) + const { stdout } = await runGit(cwd, fileArgs(cwd, root, base, paths)) ;({ patch, truncated } = clipPatch(stdout)) } diff --git a/services/git/test/_repo.ts b/services/git/test/_repo.ts index aa77e1dd5..95b20c081 100644 --- a/services/git/test/_repo.ts +++ b/services/git/test/_repo.ts @@ -121,10 +121,14 @@ export function createPathRepo(): TempRepo { } /** Give each file its own commit and a distinguishable working-tree edit. */ -export function createEditedRepo(files: [string, string][]): TempRepo { +export function createEditedRepo(files: [string, string][], relativeDiff = false): TempRepo { const repo = createTempDir() git(repo.dir, ['init', '-b', 'main']) - git(repo.dir, ['config', 'diff.relative', 'false']) + git(repo.dir, [ + 'config', + 'diff.relative', + String(relativeDiff), + ]) for (const [file, label] of files) { mkdirSync(dirname(join(repo.dir, file)), { recursive: true }) write(repo.dir, file, `${label} committed\n`) diff --git a/services/git/test/git.test.ts b/services/git/test/git.test.ts index 2cb892029..6461914da 100644 --- a/services/git/test/git.test.ts +++ b/services/git/test/git.test.ts @@ -3,7 +3,7 @@ import type { GitServiceApi } from '../src/index' import { existsSync } from 'node:fs' import { join } from 'node:path' import { createHostContext } from 'devframe/node' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { createGitService } from '../src/index' import { createEditedRepo, createPathRepo, createTempDir, createTempRepo } from './_repo' @@ -326,6 +326,47 @@ describe('@devframes/service-git', () => { expect(remaining.staged.map(f => f.path)).toEqual(['pages/i.tsx']) }) + it('keeps relative Git settings bound to the service cwd', async () => { + const repo = createEditedRepo(readmes) + cleanups.push(repo.cleanup) + const cwd = join(repo.dir, 'packages/app') + vi.stubEnv('GIT_DIR', '../../.git') + vi.stubEnv('GIT_WORK_TREE', '../..') + try { + const git = await createGit(cwd) + const path = 'README.md' + expect((await git.diff({ path })).patch).toContain('+root edited') + const staged = await git.stage({ + paths: [path], + }) + expect(staged.staged.map(f => f.path)).toEqual([path]) + const log = await git.log({ + paths: [path], + }) + expect(log.commits.map(c => c.subject)).toEqual(['add root']) + expect((await git.unstage({ + paths: [path], + })).staged).toEqual([]) + } + finally { + vi.unstubAllEnvs() + } + }) + + it('preserves relative diff headers for an absolute package file', async () => { + const repo = createEditedRepo(readmes, true) + cleanups.push(repo.cleanup) + const cwd = join(repo.dir, 'packages/app') + const git = await createGit(cwd) + const path = join(cwd, 'README.md') + const header = 'diff --git a/README.md b/README.md' + expect((await git.diff({ path })).patch?.split('\n')[0]).toBe(header) + await git.stage({ + paths: [path], + }) + expect((await git.diff({ path, staged: true })).patch?.split('\n')[0]).toBe(header) + }) + it('rejects an empty commit message', async () => { const repo = createTempRepo() cleanups.push(repo.cleanup) From fbae4a23d349ede8d7ea0de4e509ce4a46b42bd9 Mon Sep 17 00:00:00 2001 From: Sakana <15715093608@163.com> Date: Tue, 1 Dec 2026 22:37:20 +0800 Subject: [PATCH 3/4] fix(service-git): keep bulk file arguments within native limits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pass groups from one directory to Git in their original spelling. For mixed groups, use Git’s own relative directory prefix and keep relative Git worktree and index settings bound to the service directory. Literal file arguments also retain Git’s normal handling of redundant path separators and dot components. --- services/git/src/git.ts | 90 +++++++++++++++++++++++----------- services/git/src/operations.ts | 22 ++++++--- services/git/test/git.test.ts | 6 +++ 3 files changed, 82 insertions(+), 36 deletions(-) diff --git a/services/git/src/git.ts b/services/git/src/git.ts index 854f4dc16..cdf267aee 100644 --- a/services/git/src/git.ts +++ b/services/git/src/git.ts @@ -19,35 +19,69 @@ function isRootPath(path: string): boolean { return !!path && !CWD_RELATIVE.test(path) && !isAbsolute(path) } -/** Keep Git in the service cwd so relative Git settings still identify the same worktree and index. */ -export function fileArgs(cwd: string, root: string, command: string[], paths: string[]): string[] { - if (paths.length === 0) - return command - if (cwd === root || !paths.some(isRootPath)) { - return [ - '--literal-pathspecs', - ...command, - '--', - ...paths, - ] +// Git resolves these paths against the directory where its process starts. +const GIT_PATH_SETTINGS = [ + 'GIT_DIR', + 'GIT_WORK_TREE', + 'GIT_INDEX_FILE', + 'GIT_COMMON_DIR', + 'GIT_OBJECT_DIRECTORY', + 'GIT_GRAFT_FILE', + 'GIT_SHALLOW_FILE', + 'GIT_CONFIG', + 'GIT_CONFIG_GLOBAL', + 'GIT_CONFIG_SYSTEM', +] + +function needsOriginalCwd(): boolean { + return GIT_PATH_SETTINGS.some((key) => { + const value = process.env[key] + return value && !isAbsolute(value) + }) || !!process.env.GIT_ALTERNATE_OBJECT_DIRECTORIES || !!process.env.GIT_CONFIG_PARAMETERS +} + +/** Run each list from its natural base. Git resolves dot segments in the literal filenames. */ +export async function fileSelection(cwd: string, root: string, paths: string[]) { + if (!paths.length || cwd === root) + return { cwd, paths, rootDiff: false } + const rootCount = paths.filter(isRootPath).length + if (!rootCount) + return { cwd, paths, rootDiff: false } + const cwdCount = paths.filter(path => CWD_RELATIVE.test(path)).length + const fromRoot = rootCount > cwdCount && !needsOriginalCwd() + if (fromRoot && !cwdCount) + return { cwd: root, paths, rootDiff: true } + + // Translate only paths from the other base. Git supplies its own worktree prefix even for a symlinked cwd. + const { stdout } = await runGit(cwd, [ + 'rev-parse', + fromRoot ? '--show-prefix' : '--show-cdup', + ]) + const prefix = stdout.replace(/\n$/, '') + const selected = paths.map((path) => { + const rebase = fromRoot + ? CWD_RELATIVE.test(path) + : isRootPath(path) + return rebase + ? prefix + path + : path + }) + return { + cwd: fromRoot ? root : cwd, + paths: selected, + rootDiff: true, } +} - // The top flag anchors only repo-relative names. Git still receives a single list of literal paths. - const pathspecs = paths.map(path => isRootPath(path) - ? `:(top)${path}` - : path) - // diff.relative can hide a selected root file outside the service directory. - const options = command[0] === 'diff' - ? ['--no-relative'] - : [] - return [ - '--no-literal-pathspecs', - '--noglob-pathspecs', - ...command, - ...options, - '--', - ...pathspecs, - ] +export function fileArgs(command: string[], paths: string[]): string[] { + return paths.length + ? [ + '--literal-pathspecs', + ...command, + '--', + ...paths, + ] + : command } export interface GitRunResult { @@ -61,7 +95,7 @@ export interface GitRunResult { */ export async function runGit(cwd: string, args: string[]): Promise { // Inherited glob and case-folding modes conflict with the service's exact file selections. - const selectingFiles = args[0] === '--literal-pathspecs' || args[0] === '--no-literal-pathspecs' + const selectingFiles = args[0] === '--literal-pathspecs' const { stdout, stderr } = await execFileAsync('git', args, { cwd, maxBuffer: MAX_BUFFER, diff --git a/services/git/src/operations.ts b/services/git/src/operations.ts index 55d289850..4078ab8e6 100644 --- a/services/git/src/operations.ts +++ b/services/git/src/operations.ts @@ -15,6 +15,7 @@ import type { } from './types' import { fileArgs, + fileSelection, gitErrorMessage, isSafeRevision, RECORD, @@ -390,8 +391,10 @@ export function createGitOps(cwd: string): GitServiceApi { async function updateIndex(command: string[], paths: string[]): Promise { const root = await resolveRoot() - if (root && paths.length > 0) - await runGit(cwd, fileArgs(cwd, root, command, paths)) + if (root && paths.length > 0) { + const selection = await fileSelection(cwd, root, paths) + await runGit(selection.cwd, fileArgs(command, selection.paths)) + } return status() } @@ -517,7 +520,8 @@ export function createGitOps(cwd: string): GitServiceApi { command.push('--end-of-options', ref) } const paths = (args.paths ?? []).filter(Boolean) - const raw = await tryGit(cwd, fileArgs(cwd, root, command, paths)) + const selection = await fileSelection(cwd, root, paths) + const raw = await tryGit(selection.cwd, fileArgs(command, selection.paths)) const commits = raw ? parseLog(raw) : [] @@ -599,11 +603,13 @@ export function createGitOps(cwd: string): GitServiceApi { const base = staged ? ['diff', '--cached'] : ['diff'] - const paths = path + const selection = await fileSelection(cwd, root, path ? [path] - : [] - const summary = fileArgs(cwd, root, [...base, '--numstat'], paths) - const numstatRaw = await tryGit(cwd, summary) + : []) + if (selection.rootDiff) + base.push('--no-relative') + const summary = fileArgs([...base, '--numstat'], selection.paths) + const numstatRaw = await tryGit(selection.cwd, summary) const files = numstatRaw ? parseNumstat(numstatRaw) : [] @@ -611,7 +617,7 @@ export function createGitOps(cwd: string): GitServiceApi { let patch: string | null = null let truncated = false if (path) { - const { stdout } = await runGit(cwd, fileArgs(cwd, root, base, paths)) + const { stdout } = await runGit(selection.cwd, fileArgs(base, selection.paths)) ;({ patch, truncated } = clipPatch(stdout)) } diff --git a/services/git/test/git.test.ts b/services/git/test/git.test.ts index 6461914da..c2544676b 100644 --- a/services/git/test/git.test.ts +++ b/services/git/test/git.test.ts @@ -270,6 +270,12 @@ describe('@devframes/service-git', () => { expect(diff.files.map(f => f.path)).toEqual([file]) expect(diff.patch).toContain(`+${location} edited`) } + const packagePath = 'packages//app/./README.md' + expect((await git.diff({ path: packagePath, staged: true })).patch).toContain('+package edited') + const remaining = await git.unstage({ + paths: [packagePath], + }) + expect(remaining.staged.map(f => f.path)).toEqual([root.file]) }) it('stages and unstages root and explicit package paths in the same request', async () => { From 0b5feb6a44004a0fc0496e04a5934cd36fbb8893 Mon Sep 17 00:00:00 2001 From: Sakana <15715093608@163.com> Date: Tue, 1 Dec 2026 22:49:37 +0800 Subject: [PATCH 4/4] fix(service-git): preserve repository identity for bulk selections Keep root-based selections in the Git directory discovered from the service directory when different indexes share a worktree. For mixed selections, choose the base that adds fewer bytes to the Git arguments. --- services/git/src/git.ts | 79 +++++++++++++++++++++------------- services/git/src/operations.ts | 8 ++-- services/git/test/_repo.ts | 15 +++++++ services/git/test/git.test.ts | 15 ++++++- 4 files changed, 82 insertions(+), 35 deletions(-) diff --git a/services/git/src/git.ts b/services/git/src/git.ts index cdf267aee..69fb509ea 100644 --- a/services/git/src/git.ts +++ b/services/git/src/git.ts @@ -1,3 +1,4 @@ +import { Buffer } from 'node:buffer' import { execFile } from 'node:child_process' import { isAbsolute, sep } from 'node:path' import process from 'node:process' @@ -40,48 +41,66 @@ function needsOriginalCwd(): boolean { }) || !!process.env.GIT_ALTERNATE_OBJECT_DIRECTORIES || !!process.env.GIT_CONFIG_PARAMETERS } -/** Run each list from its natural base. Git resolves dot segments in the literal filenames. */ -export async function fileSelection(cwd: string, root: string, paths: string[]) { +interface FileSelection { + cwd: string + paths: string[] + rootDiff: boolean + gitDir?: string +} + +/** Select the same repository and preserve Git's native interpretation of literal file paths. */ +export async function fileSelection(cwd: string, root: string, paths: string[]): Promise { if (!paths.length || cwd === root) return { cwd, paths, rootDiff: false } const rootCount = paths.filter(isRootPath).length if (!rootCount) return { cwd, paths, rootDiff: false } const cwdCount = paths.filter(path => CWD_RELATIVE.test(path)).length - const fromRoot = rootCount > cwdCount && !needsOriginalCwd() - if (fromRoot && !cwdCount) - return { cwd: root, paths, rootDiff: true } - - // Translate only paths from the other base. Git supplies its own worktree prefix even for a symlinked cwd. - const { stdout } = await runGit(cwd, [ - 'rev-parse', - fromRoot ? '--show-prefix' : '--show-cdup', - ]) - const prefix = stdout.replace(/\n$/, '') - const selected = paths.map((path) => { - const rebase = fromRoot - ? CWD_RELATIVE.test(path) - : isRootPath(path) - return rebase - ? prefix + path - : path - }) + let fromRoot = !needsOriginalCwd() + let selected = paths + if (cwdCount || !fromRoot) { + // --show-cdup contains only ../ components. The worktree prefix can itself contain newlines. + const { stdout } = await runGit(cwd, ['rev-parse', '--show-cdup', '--show-prefix']) + const end = stdout.indexOf('\n') + const toRoot = stdout.slice(0, end) + const toCwd = stdout.slice(end + 1, -1) + fromRoot = fromRoot && cwdCount * Buffer.byteLength(toCwd) < rootCount * Buffer.byteLength(toRoot) + selected = paths.map((path) => { + if (fromRoot) { + return CWD_RELATIVE.test(path) + ? toCwd + path + : path + } + return isRootPath(path) + ? toRoot + path + : path + }) + } + if (!fromRoot) + return { cwd, paths: selected, rootDiff: true } + // Two Git directories can share one working tree. Use the Git directory discovered by the service. + const { stdout } = await runGit(cwd, ['rev-parse', '--absolute-git-dir']) return { - cwd: fromRoot ? root : cwd, + cwd: root, paths: selected, rootDiff: true, + gitDir: stdout.replace(/\n$/, ''), } } -export function fileArgs(command: string[], paths: string[]): string[] { - return paths.length - ? [ - '--literal-pathspecs', - ...command, - '--', - ...paths, - ] - : command +export function fileArgs(command: string[], selection: FileSelection): string[] { + if (!selection.paths.length) + return command + const repo = selection.gitDir + ? [`--git-dir=${selection.gitDir}`, `--work-tree=${selection.cwd}`] + : [] + return [ + '--literal-pathspecs', + ...repo, + ...command, + '--', + ...selection.paths, + ] } export interface GitRunResult { diff --git a/services/git/src/operations.ts b/services/git/src/operations.ts index 4078ab8e6..1c82312a4 100644 --- a/services/git/src/operations.ts +++ b/services/git/src/operations.ts @@ -393,7 +393,7 @@ export function createGitOps(cwd: string): GitServiceApi { const root = await resolveRoot() if (root && paths.length > 0) { const selection = await fileSelection(cwd, root, paths) - await runGit(selection.cwd, fileArgs(command, selection.paths)) + await runGit(selection.cwd, fileArgs(command, selection)) } return status() } @@ -521,7 +521,7 @@ export function createGitOps(cwd: string): GitServiceApi { } const paths = (args.paths ?? []).filter(Boolean) const selection = await fileSelection(cwd, root, paths) - const raw = await tryGit(selection.cwd, fileArgs(command, selection.paths)) + const raw = await tryGit(selection.cwd, fileArgs(command, selection)) const commits = raw ? parseLog(raw) : [] @@ -608,7 +608,7 @@ export function createGitOps(cwd: string): GitServiceApi { : []) if (selection.rootDiff) base.push('--no-relative') - const summary = fileArgs([...base, '--numstat'], selection.paths) + const summary = fileArgs([...base, '--numstat'], selection) const numstatRaw = await tryGit(selection.cwd, summary) const files = numstatRaw ? parseNumstat(numstatRaw) @@ -617,7 +617,7 @@ export function createGitOps(cwd: string): GitServiceApi { let patch: string | null = null let truncated = false if (path) { - const { stdout } = await runGit(selection.cwd, fileArgs(base, selection.paths)) + const { stdout } = await runGit(selection.cwd, fileArgs(base, selection)) ;({ patch, truncated } = clipPatch(stdout)) } diff --git a/services/git/test/_repo.ts b/services/git/test/_repo.ts index 95b20c081..dac5e12d5 100644 --- a/services/git/test/_repo.ts +++ b/services/git/test/_repo.ts @@ -144,6 +144,21 @@ export function createEditedRepo(files: [string, string][], relativeDiff = false return repo } +/** Both Git directories inspect the outer worktree but have distinct history and indexes. */ +export function createSharedWorktreeRepo(): TempRepo { + const repo = createEditedRepo([ + ['README.md', 'outer'], + ]) + const nested = join(repo.dir, 'packages/app') + mkdirSync(nested, { recursive: true }) + git(nested, ['init', '-b', 'inner']) + git(nested, ['config', 'core.worktree', repo.dir]) + git(nested, ['add', '--', '../../README.md']) + git(nested, ['commit', '-m', 'inner README']) + write(repo.dir, 'README.md', 'inner change\n') + return repo +} + /** Create an empty (non-git) temp directory. */ export function createTempDir(): TempRepo { const dir = mkdtempSync(join(tmpdir(), 'devframe-git-bare-')) diff --git a/services/git/test/git.test.ts b/services/git/test/git.test.ts index c2544676b..bad979ff2 100644 --- a/services/git/test/git.test.ts +++ b/services/git/test/git.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { createHostContext } from 'devframe/node' import { afterEach, describe, expect, it, vi } from 'vitest' import { createGitService } from '../src/index' -import { createEditedRepo, createPathRepo, createTempDir, createTempRepo } from './_repo' +import { createEditedRepo, createPathRepo, createSharedWorktreeRepo, createTempDir, createTempRepo } from './_repo' const cleanups: (() => void)[] = [] const readmes: [string, string][] = [ @@ -359,6 +359,19 @@ describe('@devframes/service-git', () => { } }) + it('uses the selected Git directory when two indexes share a worktree', async () => { + const repo = createSharedWorktreeRepo() + cleanups.push(repo.cleanup) + const inner = await createGit(join(repo.dir, 'packages/app')) + const outer = await createGit(repo.dir) + const paths = ['README.md'] + const log = await inner.log({ paths }) + expect(log.commits.map(c => c.subject)).toEqual(['inner README']) + expect((await inner.stage({ paths })).staged.map(f => f.path)).toEqual(paths) + expect((await outer.status()).staged).toEqual([]) + expect((await inner.unstage({ paths })).staged).toEqual([]) + }) + it('preserves relative diff headers for an absolute package file', async () => { const repo = createEditedRepo(readmes, true) cleanups.push(repo.cleanup)