merge pr-909 (#909 fix(changes): 变更面板两侧行数不再相加,各分组各读自己那一侧) into dev(@UNscientific-9)

冲突解决:删除 addLineCounts,状态读数改为分侧(staged/unstaged 各自一张表),
保留 dev 的 pathspec 化 numstat 读取(--literal-pathspecs + 原路径 + 行/字段上限)。
同批带上 #607 落地后暴露的两处适配:
- discoverRepoRoots 的 BFS 发现根改走 realpath(macOS tmpdir 的 /var → /private/var 别名,
  否则 rev-parse 的根与扫描根是同一仓库的两种拼法,dev 的 canonical() 断言当场红);
- tests/git-worktree 的 numstat pathspec 用例按分侧形状断言(合计仍为 +3/−0)。
This commit is contained in:
Menghuan1918 committed 2026-10-16 16:35:59 +08:00
commit 5b6f7319f9
11 files changed
+269 -139

No files matched your search

+7 -4
View File
@@ -70,10 +70,13 @@ export type GitLineCounts = { additions: number; deletions: number } | { binary:
export interface GitStatusEntry {
path: string
xy: string
/** Lines gained/lost, index and worktree sides summed. ABSENT when git has
* no numstat row for the path — untracked files never have one — so the row
* must not read that absence as `0`. */
counts?: GitLineCounts
/** Lines gained/lost on the INDEX side (index vs HEAD). ABSENT when git has
* no numstat row for the path on that side — an untracked file has none — so
* the row must not read that absence as `0`. */
staged?: GitLineCounts
/** Lines gained/lost on the WORKTREE side (worktree vs index) — a separate
* reading, never one summed number. */
unstaged?: GitLineCounts
}
/** Git status snapshot. */
+11 -6
View File
@@ -194,15 +194,18 @@ const NO_ENTRIES: readonly GitStatusEntry[] = []
function entriesKey(entries: readonly GitStatusEntry[]): string {
let key = ''
for (const entry of entries) {
const counts = entry.counts
const lines = counts === undefined
? ''
: 'additions' in counts ? `${counts.additions}/${counts.deletions}` : 'binary'
const lines = `${sideKey(entry.staged)}/${sideKey(entry.unstaged)}`
key += `${entry.xy}\u0000${entry.path}\u0000${lines}\n`
}
return key
}
/** One side's counts as a key fragment ('' when that side has none). */
function sideKey(counts: GitLineCounts | undefined): string {
if (counts === undefined) return ''
return 'additions' in counts ? `${counts.additions}/${counts.deletions}` : 'binary'
}
/** The `+N` / `−M` pair, ink and sign included: shared by a file row and its
* group header so the two can never drift apart. A zero side is omitted (the
* diff pane's own convention), and both numbers stay on the element as
@@ -881,8 +884,10 @@ export function GitLens(props: GitLensProps) {
return {
stagedEntries: staged,
unstagedEntries: unstaged,
stagedTree: buildChangeTree(staged),
unstagedTree: buildChangeTree(unstaged),
// Each band's rows carry THAT band's reading: a path changed on both
// sides sits in both trees, and neither may see the other's number.
stagedTree: buildChangeTree(staged, 'staged'),
unstagedTree: buildChangeTree(unstaged, 'unstaged'),
}
// The key stands in for `entries`: same content ⇒ same tree objects ⇒ the
// memoized rows below keep their props and never re-render.
+15 -4
View File
@@ -15,6 +15,10 @@
import type { GitLineCounts, GitStatusEntry } from '../api.ts'
import { statusOfXY, type GitFileStatus } from '../ui/index.ts'
/** Which band's reading a tree carries: the index side or the worktree side.
* Named after `GitStatusEntry`'s own fields so `entry[side]` is the reading. */
export type ChangeSide = 'staged' | 'unstaged'
/** One changed file (a leaf), carrying its porcelain status. */
export interface ChangeFile {
kind: 'file'
@@ -23,8 +27,11 @@ export interface ChangeFile {
/** The repo-relative path exactly as git reported it (the row's identity). */
path: string
status: GitFileStatus
/** The path's line counts from the SAME status answer (#131). Absent when
* git has no numstat row for the path — untracked files never have one. */
/** THIS GROUP's line counts for the path (#131) — the index side inside the
* staged group, the worktree side inside the unstaged one, so a path changed
* on both sides lands in both groups with a reading of its own each. Absent
* when git has no numstat row for the path on this side — untracked files
* never have one. */
counts?: GitLineCounts
}
@@ -110,9 +117,12 @@ function finishChildren(draft: DirDraft): ChangeNode[] {
* Rows without a porcelain status (clean, ignored) are skipped, a repeated
* path counts once, and an empty input yields an empty list.
* @param entries - the group's `git status` entries.
* @param side - which band's reading to put on the leaves. The entries carry
* both sides (a path can be in both groups), so the tree must be told which
* one its rows stand for.
* @returns the tree's roots, ready to render in order.
*/
export function buildChangeTree(entries: readonly GitStatusEntry[]): ChangeNode[] {
export function buildChangeTree(entries: readonly GitStatusEntry[], side: ChangeSide): ChangeNode[] {
const root: DirDraft = { name: '', path: '', dirs: new Map(), files: [] }
const seen = new Set<string>()
for (const entry of entries) {
@@ -135,12 +145,13 @@ export function buildChangeTree(entries: readonly GitStatusEntry[]): ChangeNode[
}
// The FILE keeps git's own spelling (the lane previews, copies and menus
// all resolve this path); only the directory rows use the split form.
const counts = entry[side]
at.files.push({
kind: 'file',
name: segments[segments.length - 1]!,
path: entry.path,
status,
...(entry.counts !== undefined ? { counts: entry.counts } : {}),
...(counts !== undefined ? { counts } : {}),
})
}
return finishChildren(root)
+10 -6
View File
@@ -131,11 +131,8 @@ function joinRoot(root: string, rel: string): string {
}
/**
* Whether two entries carry the same line counts. A numstat-only change — an
* edit that adds lines without touching either porcelain letter, e.g. more
* lines appended to an already-modified file — must still publish a NEW
* snapshot: keeping the previous identity would freeze the row's numbers at
* their first reading for as long as the porcelain codes stay put.
* Whether two sides carry the same line counts (both absent counts as equal —
* the entry simply has no reading on that side).
*/
function sameCounts(left: GitLineCounts | undefined, right: GitLineCounts | undefined): boolean {
if (left === right) return true
@@ -150,6 +147,12 @@ function sameCounts(left: GitLineCounts | undefined, right: GitLineCounts | unde
* Whether two status snapshots carry the same information. Compared field by
* field (never by serializing the whole object): the entries are the payload
* and their order is stable, so a length + pairwise compare is enough.
*
* Both sides' counts are compared, each on its own: a numstat-only change — an
* edit that adds lines without touching either porcelain letter, e.g. more
* lines appended to an already-modified file — must still publish a NEW
* snapshot, because keeping the previous identity would freeze the row's
* numbers at their first reading for as long as the porcelain codes stay put.
*/
function sameStatus(a: GitStatusResult, b: GitStatusResult): boolean {
if (a === b) return true
@@ -160,7 +163,8 @@ function sameStatus(a: GitStatusResult, b: GitStatusResult): boolean {
&& a.repositories.some((root, index) => root !== b.repositories![index])) return false
return a.entries.every((entry, index) => {
const other = b.entries[index]!
return entry.path === other.path && entry.xy === other.xy && sameCounts(entry.counts, other.counts)
return entry.path === other.path && entry.xy === other.xy
&& sameCounts(entry.staged, other.staged) && sameCounts(entry.unstaged, other.unstaged)
})
}
+40 -38
View File
@@ -11,7 +11,7 @@
* Commits use the user's git global identity untouched (never sets
* user.name/user.email).
*/
import { readdir } from 'node:fs/promises'
import { readdir, realpath } from 'node:fs/promises'
import { join } from 'node:path'
import { spawn } from 'node:child_process'
import { resolve } from 'node:path'
@@ -21,11 +21,21 @@ export interface GitStatusEntry {
path: string
/** Two-letter index/worktree status (X Y), e.g. 'M ', ' M', 'A ', '??'. */
xy: string
/** How many lines this path gained and lost, index and worktree sides
* SUMMED (both are measured against HEAD). Absent when git has no numstat
* row for the path — an untracked file never gets one — so "no counts" is
* never rendered as a fabricated `0`. */
counts?: GitLineCounts
/** How many lines the INDEX side gained and lost (`git diff --cached`, index
* against HEAD). Absent when git has no numstat row for the path on that
* side — an untracked file has none — so "no counts" is never rendered as a
* fabricated `0`. */
staged?: GitLineCounts
/** How many lines the WORKTREE side gained and lost (`git diff`, worktree
* against the index). Absent for the same reason as {@link staged}.
*
* The two sides are kept APART, never added up: a path can hold a change on
* each side ('MM'), and the change panel renders such a path once per band
* with that band's own reading. Summing the two readings would double-count
* every line both diffs see — e.g. stage a line and keep editing the same
* region, and `1 + 1` lines would be reported as a 2-line change on BOTH
* the staged row and the unstaged one. */
unstaged?: GitLineCounts
}
/** One path's line-count summary from `git diff --numstat`. A binary change is
@@ -602,7 +612,15 @@ async function discoverRepoRoots(cwd: string): Promise<string[]> {
subdirs.push(entry.name)
}
}
if (hasGit && dir !== cwd && !roots.some(existing => pathIdentity(existing) === pathIdentity(dir))) roots.push(dir)
if (hasGit && dir !== cwd) {
// Symlink-resolved form, because the scan builds paths by joining
// dirent names while `rev-parse --show-toplevel` reports the real one:
// on macOS every tmpdir lives under `/var`, a symlink to `/private/var`
// (and the panel would otherwise show the same repository twice in two
// spellings). Unresolvable names keep the joined path.
const root = await realpath(dir).catch(() => dir)
if (!roots.some(existing => pathIdentity(existing) === pathIdentity(root))) roots.push(root)
}
for (const name of subdirs.sort((left, right) => left.localeCompare(right))) next.push(join(dir, name))
}
level = next
@@ -646,30 +664,6 @@ const GIT_STATUS_LIMIT = 2_000
*/
const GIT_STATUS_MAX_FIELDS = (GIT_STATUS_LIMIT + 1) * 2
/**
* Fold one path's counts from both numstat sides into a running map. A file
* changed in the index AND in the worktree is measured on each side against
* HEAD, so the two readings ADD UP; a binary reading on either side wins,
* because then there is no line count to add.
*/
function addLineCounts(into: Map<string, GitLineCounts>, from: Map<string, GitLineCounts>): void {
for (const [path, counts] of from) {
const previous = into.get(path)
if (previous === undefined) {
into.set(path, counts)
continue
}
if (!('additions' in previous) || !('additions' in counts)) {
into.set(path, { binary: true })
continue
}
into.set(path, {
additions: previous.additions + counts.additions,
deletions: previous.deletions + counts.deletions,
})
}
}
/** Byte budget one numstat pathspec may carry (well under every platform's
* command-line cap, so a repository with thousands of tracked modifications
* falls back to the whole-repo diff instead of failing to spawn). */
@@ -741,6 +735,9 @@ function numstatPathsof(porcelainZ: string): string[] | undefined {
* 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.
*
* Each side's reading lands on its own field of the entry
* ({@link GitStatusEntry} documents why the two are never summed).
*/
export async function status(cwd: string, selected?: string): Promise<GitStatusResult> {
const repositories = await repoRoots(cwd)
@@ -776,19 +773,24 @@ export async function status(cwd: string, selected?: string): Promise<GitStatusR
stagedNumstat = staged
}
const branch = await branchPromise
const lineCounts = new Map<string, GitLineCounts>()
addLineCounts(lineCounts, parseNumstat(stagedNumstat))
addLineCounts(lineCounts, parseNumstat(unstagedNumstat))
const stagedCounts = parseNumstat(stagedNumstat)
const unstagedCounts = parseNumstat(unstagedNumstat)
const truncated = parsed.length > GIT_STATUS_LIMIT
const bounded = truncated ? parsed.slice(0, GIT_STATUS_LIMIT) : parsed
return {
isRepo: true,
branch,
// Paths git has no numstat row for (untracked files) keep their entry
// untouched: the absence IS the information.
// Paths git has no numstat row for on either side (untracked files) keep
// their entry untouched: the absence IS the information.
entries: bounded.map((entry): GitStatusEntry => {
const counts = lineCounts.get(entry.path)
return counts === undefined ? entry : { ...entry, counts }
const staged = stagedCounts.get(entry.path)
const unstaged = unstagedCounts.get(entry.path)
if (staged === undefined && unstaged === undefined) return entry
return {
...entry,
...(staged !== undefined ? { staged } : {}),
...(unstaged !== undefined ? { unstaged } : {}),
}
}),
truncated,
root,
+50 -24
View File
@@ -1,20 +1,22 @@
/**
* Line counts in the change tree (#131).
*
* The status answer carries each path's added/deleted lines; the tree keeps
* them on its leaves so a row prints its own numbers, and a group's header
* total is the sum of exactly those leaves. Binary rows and rows without
* counts (untracked files — git diffs nothing for them) contribute NOTHING:
* the alternative, counting them as 0, would make the header disagree with the
* numbers printed under it.
* The status answer carries each path's added/deleted lines PER SIDE; the tree
* is built once per band and keeps that band's reading on its leaves, so a row
* prints its own numbers and a band's header total is the sum of exactly those
* leaves. Binary rows and rows without counts (untracked files — git diffs
* nothing for them) contribute NOTHING: the alternative, counting them as 0,
* would make the header disagree with the numbers printed under it.
*/
import { describe, expect, it } from 'vitest'
import { buildChangeTree, sumLineCounts } from '../src/client/changes/change-tree.ts'
import type { GitStatusEntry } from '../src/client/api.ts'
import { buildChangeTree, sumLineCounts, type ChangeSide } from '../src/client/changes/change-tree.ts'
import type { GitLineCounts, GitStatusEntry } from '../src/client/api.ts'
/** One status entry with counts. */
function entry(path: string, xy: string, counts?: GitStatusEntry['counts']): GitStatusEntry {
return counts === undefined ? { path, xy } : { path, xy, counts }
/** One status entry carrying a reading on ONE side (the worktree by default).
* `xy` decides which bands the entry lands in; each band's tree reads its own
* side off the entry. */
function entry(path: string, xy: string, counts?: GitLineCounts, side: ChangeSide = 'unstaged'): GitStatusEntry {
return counts === undefined ? { path, xy } : { path, xy, [side]: counts }
}
describe('change tree line counts', () => {
@@ -23,7 +25,7 @@ describe('change tree line counts', () => {
entry('src/a.ts', ' M', { additions: 4, deletions: 2 }),
entry('src/deep/b.ts', ' M', { binary: true }),
entry('new.txt', '??'),
])
], 'unstaged')
const src = tree.find(node => node.kind === 'dir' && node.path === 'src')!
expect(src.kind).toBe('dir')
const leaves = src.kind === 'dir' ? src.children : []
@@ -38,12 +40,33 @@ describe('change tree line counts', () => {
expect(untracked.kind === 'file' && 'counts' in untracked).toBe(false)
})
it('reads ONLY the band\'s own side off a path that changed on both sides', () => {
// The double-count regression (#131): the two diffs have different bases,
// so `MM` carries two readings. Each band's tree must print its own, not
// the sum — summing reported the same edited line as `+2 −2` in BOTH bands.
// The two readings differ, so a band reading the WRONG side fails too.
const both: GitStatusEntry = {
path: 'a.txt',
xy: 'MM',
staged: { additions: 1, deletions: 1 },
unstaged: { additions: 5, deletions: 0 },
}
expect(sumLineCounts(buildChangeTree([both], 'staged')))
.toEqual({ additions: 1, deletions: 1, files: 1 })
expect(sumLineCounts(buildChangeTree([both], 'unstaged')))
.toEqual({ additions: 5, deletions: 0, files: 1 })
// A side with no reading stays count-less in that band only.
const stagedOnly = entry('b.txt', 'M ', { additions: 3, deletions: 0 }, 'staged')
expect(buildChangeTree([stagedOnly], 'unstaged')[0]).not.toHaveProperty('counts')
expect(buildChangeTree([stagedOnly], 'staged')[0]).toMatchObject({ counts: { additions: 3, deletions: 0 } })
})
it('sums a group to exactly the numbers its members carry', () => {
const tree = buildChangeTree([
entry('src/a.ts', ' M', { additions: 4, deletions: 2 }),
entry('src/b.ts', ' M', { additions: 1, deletions: 0 }),
entry('docs/c.md', ' M', { additions: 3, deletions: 3 }),
])
], 'unstaged')
expect(sumLineCounts(tree)).toEqual({ additions: 8, deletions: 5, files: 3 })
})
@@ -52,12 +75,13 @@ describe('change tree line counts', () => {
entry('src/a.ts', ' M', { additions: 4, deletions: 2 }),
entry('blob.bin', ' M', { binary: true }),
entry('new.txt', '??'),
])
], 'unstaged')
// 4/2 — not 4/2 plus a fabricated zero from either count-less row.
expect(sumLineCounts(tree)).toEqual({ additions: 4, deletions: 2, files: 1 })
// A group with nothing to sum reports zero files, so its header stays bare.
expect(sumLineCounts(buildChangeTree([entry('blob.bin', ' M', { binary: true }), entry('n.txt', '??')])))
.toEqual({ additions: 0, deletions: 0, files: 0 })
expect(sumLineCounts(buildChangeTree([
entry('blob.bin', ' M', { binary: true }), entry('n.txt', '??'),
], 'unstaged'))).toEqual({ additions: 0, deletions: 0, files: 0 })
})
it('counts only the rows that PRINT numbers: a 0/0 rename has none to sum (#131)', () => {
@@ -65,15 +89,17 @@ describe('change tree line counts', () => {
// reads the same way): its row prints nothing at all, so it must not make
// a group's total claim it contributed numbers — otherwise a group holding
// nothing but renames renders an empty `+N −M` cluster in its header.
expect(sumLineCounts(buildChangeTree([entry('renamed.ts', 'R ', { additions: 0, deletions: 0 })])))
.toEqual({ additions: 0, deletions: 0, files: 0 })
expect(sumLineCounts(buildChangeTree([entry('mode-only.ts', ' M', { additions: 0, deletions: 0 })])))
.toEqual({ additions: 0, deletions: 0, files: 0 })
expect(sumLineCounts(buildChangeTree([
entry('renamed.ts', 'R ', { additions: 0, deletions: 0 }, 'staged'),
], 'staged'))).toEqual({ additions: 0, deletions: 0, files: 0 })
expect(sumLineCounts(buildChangeTree([
entry('mode-only.ts', ' M', { additions: 0, deletions: 0 }),
], 'unstaged'))).toEqual({ additions: 0, deletions: 0, files: 0 })
// A rename that DID move lines keeps contributing them...
expect(sumLineCounts(buildChangeTree([
entry('edited.ts', 'R ', { additions: 2, deletions: 1 }),
entry('renamed.ts', 'R ', { additions: 0, deletions: 0 }),
]))).toEqual({ additions: 2, deletions: 1, files: 1 })
entry('edited.ts', 'R ', { additions: 2, deletions: 1 }, 'staged'),
entry('renamed.ts', 'R ', { additions: 0, deletions: 0 }, 'staged'),
], 'staged'))).toEqual({ additions: 2, deletions: 1, files: 1 })
})
it('counts every member regardless of how deep the directory chain folds', () => {
@@ -82,7 +108,7 @@ describe('change tree line counts', () => {
const tree = buildChangeTree([
entry('src/client/changes/a.ts', ' M', { additions: 2, deletions: 1 }),
entry('src/client/changes/b.ts', ' M', { additions: 5, deletions: 0 }),
])
], 'unstaged')
expect(tree).toHaveLength(1)
expect(tree[0]).toMatchObject({ kind: 'dir', name: 'src/client/changes' })
expect(sumLineCounts(tree)).toEqual({ additions: 7, deletions: 1, files: 2 })
+16 -12
View File
@@ -164,19 +164,23 @@ describe('change tree (the Git lens reads its groups through it)', () => {
/** One `git status` row from a path and its porcelain code. */
const entry = (path: string, xy = ' M'): GitStatusEntry => ({ path, xy })
/** The tree of one band. These cases exercise the SHAPE only, so the side is
* fixed; the per-side readings have their own suite. */
const band = (entries: readonly GitStatusEntry[]): ChangeNode[] => buildChangeTree(entries, 'unstaged')
/** A compact, assertion-friendly projection of one tree. */
const shape = (nodes: readonly ChangeNode[]): unknown[] => nodes.map(node => node.kind === 'dir'
? { dir: node.name, path: node.path, changes: node.changes, children: shape(node.children) }
: { file: node.name, path: node.path, letter: node.status.letter, tone: node.status.tone })
it('keeps a single root-level file as one leaf', () => {
expect(shape(buildChangeTree([entry('readme.md')]))).toEqual([
expect(shape(band([entry('readme.md')]))).toEqual([
{ file: 'readme.md', path: 'readme.md', letter: 'M', tone: 'modified' },
])
})
it('nests a deep path and compresses its single-child chain into one row', () => {
const tree = buildChangeTree([entry('src/client/changes/a.ts')])
const tree = band([entry('src/client/changes/a.ts')])
expect(shape(tree)).toEqual([
{
dir: 'src/client/changes',
@@ -189,7 +193,7 @@ describe('change tree (the Git lens reads its groups through it)', () => {
it('stops compressing where the path branches or a directory holds its own file', () => {
// Two child directories: 'src' keeps its own row.
expect(shape(buildChangeTree([entry('src/a/x.ts'), entry('src/b/y.ts')]))).toEqual([
expect(shape(band([entry('src/a/x.ts'), entry('src/b/y.ts')]))).toEqual([
{
dir: 'src',
path: 'src',
@@ -201,7 +205,7 @@ describe('change tree (the Git lens reads its groups through it)', () => {
},
])
// A file AT this level: 'a' keeps its own row (and its file leads the child).
expect(shape(buildChangeTree([entry('a/x.ts'), entry('a/b/y.ts')]))).toEqual([
expect(shape(band([entry('a/x.ts'), entry('a/b/y.ts')]))).toEqual([
{
dir: 'a',
path: 'a',
@@ -215,7 +219,7 @@ describe('change tree (the Git lens reads its groups through it)', () => {
})
it('orders directories before files, each by name case-insensitively', () => {
const tree = buildChangeTree([
const tree = band([
entry('Zed.ts'), entry('B.ts'), entry('a.ts'), entry('zdir/f.ts'), entry('Adir/f.ts'),
])
expect(shape(tree).map(node => (node as { dir?: string; file?: string }).dir ?? (node as { file: string }).file))
@@ -223,7 +227,7 @@ describe('change tree (the Git lens reads its groups through it)', () => {
})
it('mixes root-level files with nested paths and keeps same-named files apart', () => {
expect(shape(buildChangeTree([
expect(shape(band([
entry('b/index.ts'), entry('index.ts'), entry('a/index.ts'),
]))).toEqual([
{ dir: 'a', path: 'a', changes: 1, children: [{ file: 'index.ts', path: 'a/index.ts', letter: 'M', tone: 'modified' }] },
@@ -233,7 +237,7 @@ describe('change tree (the Git lens reads its groups through it)', () => {
})
it('carries every file porcelain status and counts the files under each row', () => {
const tree = buildChangeTree([
const tree = band([
entry('src/a.ts', ' M'), entry('src/new.ts', '??'), entry('src/gone.ts', ' D'), entry('src/kept.ts', ' '),
])
expect(shape(tree)).toEqual([
@@ -257,14 +261,14 @@ describe('change tree (the Git lens reads its groups through it)', () => {
// reorder the same change list on another machine.
const names = ['b.ts', 'A.ts', 'ä.ts', 'Z.ts', 'a.ts', 'Ä.ts', '_x.ts', '1.ts']
const order = (list: readonly string[]): string[] =>
buildChangeTree(list.map(path => entry(path))).map(node => node.name)
band(list.map(path => entry(path))).map(node => node.name)
expect(order(names)).toEqual(['_x.ts', '1.ts', 'A.ts', 'a.ts', 'Ä.ts', 'ä.ts', 'b.ts', 'Z.ts'])
// …and it is a TOTAL order: reversing the input cannot move a row.
expect(order([...names].reverse())).toEqual(order(names))
const dirs = ['Zdir/f.ts', 'adir/f.ts', 'Ädir/f.ts', '_dir/f.ts']
const dirOrder = (list: readonly string[]): string[] =>
buildChangeTree(list.map(path => entry(path))).map(node => node.name)
band(list.map(path => entry(path))).map(node => node.name)
expect(dirOrder(dirs)).toEqual(['_dir', 'adir', 'Ädir', 'Zdir'])
expect(dirOrder([...dirs].reverse())).toEqual(dirOrder(dirs))
@@ -276,12 +280,12 @@ describe('change tree (the Git lens reads its groups through it)', () => {
})
it('returns no nodes for an empty or all-clean list', () => {
expect(buildChangeTree([])).toEqual([])
expect(buildChangeTree([entry('a.ts', ' '), entry('b.ts', '!!')])).toEqual([])
expect(band([])).toEqual([])
expect(band([entry('a.ts', ' '), entry('b.ts', '!!')])).toEqual([])
})
it('counts a repeated path once', () => {
expect(shape(buildChangeTree([entry('a.ts'), entry('a.ts', '??')]))).toEqual([
expect(shape(band([entry('a.ts'), entry('a.ts', '??')]))).toEqual([
{ file: 'a.ts', path: 'a.ts', letter: 'M', tone: 'modified' },
])
})
+4 -4
View File
@@ -206,8 +206,8 @@ describe('ChangesTab', () => {
*/
it('renders no count cluster for a group whose only changes are pure renames (#131)', async () => {
mockGit([
{ path: 'renamed.ts', xy: 'R ', counts: { additions: 0, deletions: 0 } },
{ path: 'moved.md', xy: ' R', counts: { additions: 0, deletions: 0 } },
{ path: 'renamed.ts', xy: 'R ', staged: { additions: 0, deletions: 0 } },
{ path: 'moved.md', xy: ' R', unstaged: { additions: 0, deletions: 0 } },
])
const container = document.createElement('div')
@@ -236,8 +236,8 @@ describe('ChangesTab', () => {
it('keeps the group total when a row in the group really has numbers (#131)', async () => {
mockGit([
{ path: 'mode-only.ts', xy: ' M', counts: { additions: 0, deletions: 0 } },
{ path: 'edited.ts', xy: ' M', counts: { additions: 3, deletions: 1 } },
{ path: 'mode-only.ts', xy: ' M', unstaged: { additions: 0, deletions: 0 } },
{ path: 'edited.ts', xy: ' M', unstaged: { additions: 3, deletions: 1 } },
])
const container = document.createElement('div')
+37 -7
View File
@@ -455,7 +455,7 @@ describe('GitLens (changes tab, git lens) change tree', () => {
async function mountTree(
container: HTMLElement,
root: Root,
entries: Array<{ path: string; xy: string; counts?: GitStatusEntry['counts'] }>,
entries: GitStatusEntry[],
): Promise<void> {
const changes = entries.filter(row => row.xy !== ' ').length
vi.spyOn(api, 'gitWorktrees').mockResolvedValue([{ path: MAIN, branch: 'main', current: true, changes }])
@@ -708,9 +708,9 @@ describe('GitLens (changes tab, git lens) change tree', () => {
const { container, root } = makeRoot()
try {
await mountTree(container, root, [
{ path: 'src/a.ts', xy: ' M', counts: { additions: 4, deletions: 2 } },
{ path: 'src/b.ts', xy: ' M', counts: { additions: 1, deletions: 0 } },
{ path: 'docs/c.md', xy: 'M ', counts: { additions: 3, deletions: 3 } },
{ path: 'src/a.ts', xy: ' M', unstaged: { additions: 4, deletions: 2 } },
{ path: 'src/b.ts', xy: ' M', unstaged: { additions: 1, deletions: 0 } },
{ path: 'docs/c.md', xy: 'M ', staged: { additions: 3, deletions: 3 } },
])
expect(counted(container, '[data-path="src/a.ts"] [data-lines="count"]'))
@@ -744,7 +744,7 @@ describe('GitLens (changes tab, git lens) change tree', () => {
try {
await mountTree(container, root, [
{ path: 'new.txt', xy: '??' },
{ path: 'blob.bin', xy: ' M', counts: { binary: true } },
{ path: 'blob.bin', xy: ' M', unstaged: { binary: true } },
])
expect(container.querySelector('[data-path="new.txt"] [data-lines="new"]')?.textContent)
@@ -773,10 +773,10 @@ describe('GitLens (changes tab, git lens) change tree', () => {
// line counts moved (more lines appended to an already-modified file).
vi.spyOn(api, 'gitStatus')
.mockResolvedValueOnce({
isRepo: true, branch: 'main', entries: [{ path: 'src/a.ts', xy: ' M', counts: { additions: 1, deletions: 0 } }],
isRepo: true, branch: 'main', entries: [{ path: 'src/a.ts', xy: ' M', unstaged: { additions: 1, deletions: 0 } }],
})
.mockResolvedValue({
isRepo: true, branch: 'main', entries: [{ path: 'src/a.ts', xy: ' M', counts: { additions: 7, deletions: 0 } }],
isRepo: true, branch: 'main', entries: [{ path: 'src/a.ts', xy: ' M', unstaged: { additions: 7, deletions: 0 } }],
})
vi.spyOn(api, 'gitBranch').mockResolvedValue({ current: 'main', names: ['main'] })
vi.spyOn(api, 'gitLog').mockResolvedValue([])
@@ -801,6 +801,36 @@ describe('GitLens (changes tab, git lens) change tree', () => {
vi.useRealTimers()
}
})
it('gives each band its OWN side of a file changed on both sides, never the sum (#131 regression)', async () => {
const { container, root } = makeRoot()
try {
// One file changed on both sides ('MM'): a one-line rewrite staged,
// then five lines appended in the worktree. Each band must show its own
// reading — summing them printed `+6 −1` on BOTH bands.
await mountTree(container, root, [
{
path: 'a.txt',
xy: 'MM',
staged: { additions: 1, deletions: 1 },
unstaged: { additions: 5, deletions: 0 },
},
])
expect(counted(container, '[data-group="unstaged"] [data-lines="group"]'))
.toEqual({ added: '5', deleted: '0', text: '+5' })
expect(counted(container, '[data-group="staged"] [data-lines="group"]'))
.toEqual({ added: '1', deleted: '1', text: '+1−1' })
// The path really is listed in both bands, each row printing its own
// side's numbers (unstaged band first, staged second).
const rows = [...container.querySelectorAll<HTMLElement>('button[data-path="a.txt"] [data-lines="count"]')]
expect(rows.map(node => `${node.getAttribute('data-added')}/${node.getAttribute('data-deleted')}`))
.toEqual(['5/0', '1/1'])
} finally {
act(() => { root.unmount() })
container.remove()
}
})
})
})
+22 -13
View File
@@ -81,9 +81,10 @@ describe('linked Git worktrees', () => {
expect(listed.find(entry => !entry.current)).toMatchObject({ branch: 'agent', changes: 1 })
expect(resolve(await resolveWorktree(main, agentPath))).toBe(resolve(agentPath))
// The line counts ride the same status answer (#131): 'base' →
// 'changed by agent' is exactly one line replaced.
// 'changed by agent' is exactly one line replaced, on the worktree side
// (nothing is staged here, so the index side has no reading at all).
expect((await status(await resolveWorktree(main, agentPath))).entries).toEqual([
{ path: 'tracked.txt', xy: ' M', counts: { additions: 1, deletions: 1 } },
{ path: 'tracked.txt', xy: ' M', unstaged: { additions: 1, deletions: 1 } },
])
await expect(resolveWorktree(main, root)).rejects.toThrow('unknown linked worktree')
@@ -159,8 +160,8 @@ describe('linked Git worktrees', () => {
git(main, ['add', '-A'])
git(main, ['commit', '-q', '-m', 'base'])
// One file changed on BOTH sides (their counts add up), one changed in
// the worktree only, a staged rename, and an untracked file.
// One file changed on BOTH sides (each side keeps its OWN reading), one
// changed in the worktree only, a staged rename, and an untracked file.
writeFileSync(join(main, 'both-sides.txt'), 'one\ntwo\nthree\n')
git(main, ['add', 'both-sides.txt'])
writeFileSync(join(main, 'both-sides.txt'), 'one\ntwo\nthree\nfour\n')
@@ -170,20 +171,28 @@ describe('linked Git worktrees', () => {
const result = await status(main)
const byPath = new Map(result.entries.map(entry => [entry.path, entry]))
expect(byPath.get('both-sides.txt')).toMatchObject({ xy: 'MM', counts: { additions: 2, deletions: 0 } })
expect(byPath.get('worktree-only.txt')).toMatchObject({ xy: ' M', counts: { additions: 1, deletions: 0 } })
expect(byPath.get('both-sides.txt')).toMatchObject({
xy: 'MM',
staged: { additions: 1, deletions: 0 },
unstaged: { additions: 1, deletions: 0 },
})
expect(byPath.get('worktree-only.txt')).toMatchObject({ xy: ' M', unstaged: { additions: 1, deletions: 0 } })
// A rename that loses its origin from the pathspec reports `1 0` here.
expect(byPath.get('renamed.txt')).toMatchObject({ xy: 'R ', counts: { additions: 0, deletions: 0 } })
expect(byPath.get('renamed.txt')).toMatchObject({ xy: 'R ', staged: { additions: 0, deletions: 0 } })
// No numstat row exists for an untracked file, pathspec or not.
expect(byPath.get('untracked.txt')).toEqual({ path: 'untracked.txt', xy: '??' })
// The group total the changes tree sums: dropping ANY of the paths above
// (or the rename origin) changes this number.
// The group totals the changes tree sums, each group reading its own
// side: dropping ANY of the paths above (or the rename origin) changes
// one of these numbers.
const totals = result.entries.reduce((sum, entry) => {
const counts = entry.counts
return counts !== undefined && 'additions' in counts
? { additions: sum.additions + counts.additions, deletions: sum.deletions + counts.deletions }
: sum
for (const counts of [entry.staged, entry.unstaged]) {
if (counts !== undefined && 'additions' in counts) {
sum.additions += counts.additions
sum.deletions += counts.deletions
}
}
return sum
}, { additions: 0, deletions: 0 })
expect(totals).toEqual({ additions: 3, deletions: 0 })
} finally {
+57 -21
View File
@@ -445,23 +445,31 @@ describe('numstat line counts (#131)', () => {
expect(parseNumstat('not a numstat record\nanother one\n')).toEqual(new Map())
})
it('carries counts, the binary marker and the untracked absence through status()', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-git-counts-'))
try {
execFileSync('git', ['init', '-q'], { cwd: root })
execFileSync('git', ['config', 'user.email', 't@t'], { cwd: root })
execFileSync('git', ['config', 'user.name', 't'], { cwd: root })
// Rename detection is a user config (diff.renames / status.renames);
// pin it so this fixture means the same thing on every machine.
execFileSync('git', ['config', 'diff.renames', 'true'], { cwd: root })
execFileSync('git', ['config', 'status.renames', 'true'], { cwd: root })
writeFileSync(join(root, 'tracked.txt'), 'one\ntwo\n')
writeFileSync(join(root, 'renamed.txt'), 'same\n')
execFileSync('git', ['add', '-A'], { cwd: root })
execFileSync('git', ['commit', '-q', '-m', 'init'], { cwd: root })
/** A fresh repo whose `files` (path → content) are committed as the baseline.
* `config` entries are applied before that first commit. */
function mkRepo(files: Record<string, string | Buffer>, config: Record<string, string> = {}): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-git-repo-'))
execFileSync('git', ['init', '-q'], { cwd: root })
execFileSync('git', ['config', 'user.email', 't@t'], { cwd: root })
execFileSync('git', ['config', 'user.name', 't'], { cwd: root })
for (const [key, value] of Object.entries(config)) execFileSync('git', ['config', key, value], { cwd: root })
for (const [name, content] of Object.entries(files)) writeFileSync(join(root, name), content)
execFileSync('git', ['add', '-A'], { cwd: root })
execFileSync('git', ['commit', '-q', '-m', 'init'], { cwd: root })
return root
}
// ONE path changed on BOTH sides: one line staged, then one more in the
// worktree — the entry must report the sum of the two readings.
it('carries each side\'s counts, the binary marker and the untracked absence through status()', async () => {
// Rename detection is a user config (diff.renames / status.renames); pin it
// so this fixture means the same thing on every machine.
const root = mkRepo(
{ 'tracked.txt': 'one\ntwo\n', 'renamed.txt': 'same\n' },
{ 'diff.renames': 'true', 'status.renames': 'true' },
)
try {
// ONE path changed on BOTH sides (porcelain 'MM'): one line staged, then
// one more in the worktree. The two diffs have different bases, so the
// entry carries two readings — never one number that adds them up.
writeFileSync(join(root, 'tracked.txt'), 'one\ntwo\nthree\n')
execFileSync('git', ['add', 'tracked.txt'], { cwd: root })
writeFileSync(join(root, 'tracked.txt'), 'one\ntwo\nthree\nfour\n')
@@ -475,20 +483,48 @@ describe('numstat line counts (#131)', () => {
const result = await status(root)
const byPath = new Map(result.entries.map(entry => [entry.path, entry]))
expect(byPath.get('tracked.txt')).toEqual({
path: 'tracked.txt', xy: 'MM', counts: { additions: 2, deletions: 0 },
path: 'tracked.txt',
xy: 'MM',
staged: { additions: 1, deletions: 0 },
unstaged: { additions: 1, deletions: 0 },
})
expect(byPath.get('moved.txt')).toEqual({
path: 'moved.txt', xy: 'R ', counts: { additions: 0, deletions: 0 },
path: 'moved.txt', xy: 'R ', staged: { additions: 0, deletions: 0 },
})
expect(byPath.get('blob.bin')).toEqual({
path: 'blob.bin', xy: 'A ', counts: { binary: true },
path: 'blob.bin', xy: 'A ', staged: { binary: true },
})
// No numstat row exists for an untracked file: the entry keeps no counts
// at all, which is what the row renders as "new file".
// No numstat row exists for an untracked file on either side: the entry
// keeps no counts at all, which is what the row renders as "new file".
expect(byPath.get('untracked.txt')).toEqual({ path: 'untracked.txt', xy: '??' })
expect(byPath.has('renamed.txt')).toBe(false)
} finally {
removeTree(root)
}
})
it('never adds the two sides up: a line both diffs see is counted once per side', async () => {
// The double-count regression. Editing the SAME line twice — staged once,
// then edited again in the worktree — makes both numstat sides report the
// same single line; summing them reported a 2-line change on BOTH rows.
const root = mkRepo({ 'a.txt': 'one\ntwo\nthree\n' })
try {
writeFileSync(join(root, 'a.txt'), 'one\nTWO\nthree\n')
execFileSync('git', ['add', 'a.txt'], { cwd: root })
writeFileSync(join(root, 'a.txt'), 'one\nTwo\nthree\n')
const result = await status(root)
expect(result.entries).toEqual([{
path: 'a.txt',
xy: 'MM',
staged: { additions: 1, deletions: 1 },
unstaged: { additions: 1, deletions: 1 },
}])
// The reading the panel must never print: the sum of two diffs that saw
// the same line.
expect(JSON.stringify(result.entries)).not.toContain('"additions":2')
} finally {
removeTree(root)
}
})
})