Skip to content

Commit 0b5feb6

Browse files
committed
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.
1 parent fbae4a2 commit 0b5feb6

4 files changed

Lines changed: 82 additions & 35 deletions

File tree

‎services/git/src/git.ts‎

Lines changed: 49 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { Buffer } from 'node:buffer'
12
import { execFile } from 'node:child_process'
23
import { isAbsolute, sep } from 'node:path'
34
import process from 'node:process'
@@ -40,48 +41,66 @@ function needsOriginalCwd(): boolean {
4041
}) || !!process.env.GIT_ALTERNATE_OBJECT_DIRECTORIES || !!process.env.GIT_CONFIG_PARAMETERS
4142
}
4243

43-
/** Run each list from its natural base. Git resolves dot segments in the literal filenames. */
44-
export async function fileSelection(cwd: string, root: string, paths: string[]) {
44+
interface FileSelection {
45+
cwd: string
46+
paths: string[]
47+
rootDiff: boolean
48+
gitDir?: string
49+
}
50+
51+
/** Select the same repository and preserve Git's native interpretation of literal file paths. */
52+
export async function fileSelection(cwd: string, root: string, paths: string[]): Promise<FileSelection> {
4553
if (!paths.length || cwd === root)
4654
return { cwd, paths, rootDiff: false }
4755
const rootCount = paths.filter(isRootPath).length
4856
if (!rootCount)
4957
return { cwd, paths, rootDiff: false }
5058
const cwdCount = paths.filter(path => CWD_RELATIVE.test(path)).length
51-
const fromRoot = rootCount > cwdCount && !needsOriginalCwd()
52-
if (fromRoot && !cwdCount)
53-
return { cwd: root, paths, rootDiff: true }
54-
55-
// Translate only paths from the other base. Git supplies its own worktree prefix even for a symlinked cwd.
56-
const { stdout } = await runGit(cwd, [
57-
'rev-parse',
58-
fromRoot ? '--show-prefix' : '--show-cdup',
59-
])
60-
const prefix = stdout.replace(/\n$/, '')
61-
const selected = paths.map((path) => {
62-
const rebase = fromRoot
63-
? CWD_RELATIVE.test(path)
64-
: isRootPath(path)
65-
return rebase
66-
? prefix + path
67-
: path
68-
})
59+
let fromRoot = !needsOriginalCwd()
60+
let selected = paths
61+
if (cwdCount || !fromRoot) {
62+
// --show-cdup contains only ../ components. The worktree prefix can itself contain newlines.
63+
const { stdout } = await runGit(cwd, ['rev-parse', '--show-cdup', '--show-prefix'])
64+
const end = stdout.indexOf('\n')
65+
const toRoot = stdout.slice(0, end)
66+
const toCwd = stdout.slice(end + 1, -1)
67+
fromRoot = fromRoot && cwdCount * Buffer.byteLength(toCwd) < rootCount * Buffer.byteLength(toRoot)
68+
selected = paths.map((path) => {
69+
if (fromRoot) {
70+
return CWD_RELATIVE.test(path)
71+
? toCwd + path
72+
: path
73+
}
74+
return isRootPath(path)
75+
? toRoot + path
76+
: path
77+
})
78+
}
79+
if (!fromRoot)
80+
return { cwd, paths: selected, rootDiff: true }
81+
// Two Git directories can share one working tree. Use the Git directory discovered by the service.
82+
const { stdout } = await runGit(cwd, ['rev-parse', '--absolute-git-dir'])
6983
return {
70-
cwd: fromRoot ? root : cwd,
84+
cwd: root,
7185
paths: selected,
7286
rootDiff: true,
87+
gitDir: stdout.replace(/\n$/, ''),
7388
}
7489
}
7590

76-
export function fileArgs(command: string[], paths: string[]): string[] {
77-
return paths.length
78-
? [
79-
'--literal-pathspecs',
80-
...command,
81-
'--',
82-
...paths,
83-
]
84-
: command
91+
export function fileArgs(command: string[], selection: FileSelection): string[] {
92+
if (!selection.paths.length)
93+
return command
94+
const repo = selection.gitDir
95+
? [`--git-dir=${selection.gitDir}`, `--work-tree=${selection.cwd}`]
96+
: []
97+
return [
98+
'--literal-pathspecs',
99+
...repo,
100+
...command,
101+
'--',
102+
...selection.paths,
103+
]
85104
}
86105

87106
export interface GitRunResult {

‎services/git/src/operations.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,7 @@ export function createGitOps(cwd: string): GitServiceApi {
393393
const root = await resolveRoot()
394394
if (root && paths.length > 0) {
395395
const selection = await fileSelection(cwd, root, paths)
396-
await runGit(selection.cwd, fileArgs(command, selection.paths))
396+
await runGit(selection.cwd, fileArgs(command, selection))
397397
}
398398
return status()
399399
}
@@ -521,7 +521,7 @@ export function createGitOps(cwd: string): GitServiceApi {
521521
}
522522
const paths = (args.paths ?? []).filter(Boolean)
523523
const selection = await fileSelection(cwd, root, paths)
524-
const raw = await tryGit(selection.cwd, fileArgs(command, selection.paths))
524+
const raw = await tryGit(selection.cwd, fileArgs(command, selection))
525525
const commits = raw
526526
? parseLog(raw)
527527
: []
@@ -608,7 +608,7 @@ export function createGitOps(cwd: string): GitServiceApi {
608608
: [])
609609
if (selection.rootDiff)
610610
base.push('--no-relative')
611-
const summary = fileArgs([...base, '--numstat'], selection.paths)
611+
const summary = fileArgs([...base, '--numstat'], selection)
612612
const numstatRaw = await tryGit(selection.cwd, summary)
613613
const files = numstatRaw
614614
? parseNumstat(numstatRaw)
@@ -617,7 +617,7 @@ export function createGitOps(cwd: string): GitServiceApi {
617617
let patch: string | null = null
618618
let truncated = false
619619
if (path) {
620-
const { stdout } = await runGit(selection.cwd, fileArgs(base, selection.paths))
620+
const { stdout } = await runGit(selection.cwd, fileArgs(base, selection))
621621
;({ patch, truncated } = clipPatch(stdout))
622622
}
623623

‎services/git/test/_repo.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,21 @@ export function createEditedRepo(files: [string, string][], relativeDiff = false
144144
return repo
145145
}
146146

147+
/** Both Git directories inspect the outer worktree but have distinct history and indexes. */
148+
export function createSharedWorktreeRepo(): TempRepo {
149+
const repo = createEditedRepo([
150+
['README.md', 'outer'],
151+
])
152+
const nested = join(repo.dir, 'packages/app')
153+
mkdirSync(nested, { recursive: true })
154+
git(nested, ['init', '-b', 'inner'])
155+
git(nested, ['config', 'core.worktree', repo.dir])
156+
git(nested, ['add', '--', '../../README.md'])
157+
git(nested, ['commit', '-m', 'inner README'])
158+
write(repo.dir, 'README.md', 'inner change\n')
159+
return repo
160+
}
161+
147162
/** Create an empty (non-git) temp directory. */
148163
export function createTempDir(): TempRepo {
149164
const dir = mkdtempSync(join(tmpdir(), 'devframe-git-bare-'))

‎services/git/test/git.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { join } from 'node:path'
55
import { createHostContext } from 'devframe/node'
66
import { afterEach, describe, expect, it, vi } from 'vitest'
77
import { createGitService } from '../src/index'
8-
import { createEditedRepo, createPathRepo, createTempDir, createTempRepo } from './_repo'
8+
import { createEditedRepo, createPathRepo, createSharedWorktreeRepo, createTempDir, createTempRepo } from './_repo'
99

1010
const cleanups: (() => void)[] = []
1111
const readmes: [string, string][] = [
@@ -359,6 +359,19 @@ describe('@devframes/service-git', () => {
359359
}
360360
})
361361

362+
it('uses the selected Git directory when two indexes share a worktree', async () => {
363+
const repo = createSharedWorktreeRepo()
364+
cleanups.push(repo.cleanup)
365+
const inner = await createGit(join(repo.dir, 'packages/app'))
366+
const outer = await createGit(repo.dir)
367+
const paths = ['README.md']
368+
const log = await inner.log({ paths })
369+
expect(log.commits.map(c => c.subject)).toEqual(['inner README'])
370+
expect((await inner.stage({ paths })).staged.map(f => f.path)).toEqual(paths)
371+
expect((await outer.status()).staged).toEqual([])
372+
expect((await inner.unstage({ paths })).staged).toEqual([])
373+
})
374+
362375
it('preserves relative diff headers for an absolute package file', async () => {
363376
const repo = createEditedRepo(readmes, true)
364377
cleanups.push(repo.cleanup)

0 commit comments

Comments
 (0)