From 99eb9190e091655eb2ea57e3894df1e2a5e353c5 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 22:19:26 +0800 Subject: [PATCH] =?UTF-8?q?feat(git-lens):=20=E5=8F=98=E6=9B=B4=E8=A1=8C?= =?UTF-8?q?=E6=95=B0=E7=BB=9F=E8=AE=A1=EF=BC=88numstat=20=E9=9A=8F?= =?UTF-8?q?=E6=97=A2=E6=9C=89=20status=20=E4=B8=80=E6=AC=A1=E5=8F=96?= =?UTF-8?q?=E5=9B=9E=EF=BC=8C=E5=88=86=E7=BB=84=E5=A4=B4=E5=90=88=E8=AE=A1?= =?UTF-8?q?=20+=20=E6=96=87=E4=BB=B6=E8=A1=8C=E5=A2=9E=E5=88=A0=EF=BC=8C?= =?UTF-8?q?=E6=9C=AA=E8=B7=9F=E8=B8=AA=E6=98=BE=E7=A4=BA=E6=96=B0=E6=96=87?= =?UTF-8?q?=E4=BB=B6=EF=BC=89=EF=BC=88#131=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/client/api.ts | 9 ++ src/client/changes/GitLens.tsx | 65 +++++++++++-- src/client/changes/change-tree.ts | 46 ++++++++- src/client/changes/changes.module.css | 22 +++++ src/client/locales-ar.ts | 1 + src/client/locales-de.ts | 1 + src/client/locales-fr.ts | 1 + src/client/locales-hi.ts | 1 + src/client/locales-id.ts | 1 + src/client/locales-it.ts | 1 + src/client/locales-ja.ts | 1 + src/client/locales-ko.ts | 1 + src/client/locales-nl.ts | 1 + src/client/locales-pl.ts | 1 + src/client/locales-pt.ts | 1 + src/client/locales-ru.ts | 1 + src/client/locales-sv.ts | 1 + src/client/locales-th.ts | 1 + src/client/locales-tr.ts | 1 + src/client/locales-vi.ts | 1 + src/client/locales-zh-HK.ts | 1 + src/client/locales-zh-MO.ts | 1 + src/client/locales-zh-TW.ts | 1 + src/client/locales.ts | 2 + src/client/ui/git-status.ts | 20 +++- src/git.ts | 130 +++++++++++++++++++++++++- tests/change-tree-counts.spec.ts | 74 +++++++++++++++ tests/git-view-worktree.spec.tsx | 118 ++++++++++++++++++++++- tests/git-worktree.spec.ts | 4 +- tests/git.spec.ts | 112 +++++++++++++++++++++- 30 files changed, 605 insertions(+), 16 deletions(-) create mode 100644 tests/change-tree-counts.spec.ts diff --git a/src/client/api.ts b/src/client/api.ts index b7e7bc9d..09a9732d 100644 --- a/src/client/api.ts +++ b/src/client/api.ts @@ -54,10 +54,19 @@ export interface FsLevel { error?: string } +/** One changed path's line-count summary (host git shape, mirroring + * `GitLineCounts` in `src/git.ts`). A binary change is its own variant: git + * reports `-`/`-` for it, so there are no counts to show. */ +export type GitLineCounts = { additions: number; deletions: number } | { binary: true } + /** Git status entry (host git shape). */ 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 } /** Git status snapshot. */ diff --git a/src/client/changes/GitLens.tsx b/src/client/changes/GitLens.tsx index 85191738..0309c778 100644 --- a/src/client/changes/GitLens.tsx +++ b/src/client/changes/GitLens.tsx @@ -32,7 +32,7 @@ import { IconSparkleRegular, IconTrashOutlineRegular, Menu, writeClipboard, } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from '../../context-types.ts' -import type { GitLogEntry, GitStatusEntry, GitStatusResult, GitWorktree, SessionScope } from '../api.ts' +import type { GitLineCounts, GitLogEntry, GitStatusEntry, GitStatusResult, GitWorktree, SessionScope } from '../api.ts' import { api, SidebarApiError } from '../api.ts' import { builtinFileIcon, builtinFolderIcon } from '../file-icons.tsx' import { usePolling } from '../use-polling.ts' @@ -44,7 +44,8 @@ import { ConfirmDialog, IconButton, Notice, SectionHeader, StatusBadge, invalidateGitStatus, statusOfXY, useGitStatus, type GitFileStatus, type GitTone, type StatusTone, } from '../ui/index.ts' -import { buildChangeTree, type ChangeDir, type ChangeFile, type ChangeNode } from './change-tree.ts' +import { buildChangeTree, sumLineCounts, type ChangeDir, type ChangeFile, type ChangeNode } from './change-tree.ts' +import diffCss from '../diff/diff.module.css' import css from './changes.module.css' /** Whether the entry carries STAGED (index) changes — the X letter is set. */ @@ -135,16 +136,54 @@ const NO_ENTRIES: readonly GitStatusEntry[] = [] * A CONTENT key for one status answer. The shared store mints a brand-new * entries array for every poll — idle polls with byte-identical content * included — so array identity cannot decide whether the tree must be rebuilt. - * This string can: the same paths and porcelain codes always produce the same - * key, and a key change is exactly when the tree, its counts and the row - * objects need to be recomputed. + * This string can: the same paths, porcelain codes and line counts always + * produce the same key, and a key change is exactly when the tree, its totals + * and the row objects need to be recomputed. The counts belong in the key + * because an edit that only moves lines leaves `xy` alone (#131): without them + * the memoized rows would keep printing their first reading. */ function entriesKey(entries: readonly GitStatusEntry[]): string { let key = '' - for (const entry of entries) key += `${entry.xy}\u0000${entry.path}\n` + for (const entry of entries) { + const counts = entry.counts + const lines = counts === undefined + ? '' + : 'additions' in counts ? `${counts.additions}/${counts.deletions}` : 'binary' + key += `${entry.xy}\u0000${entry.path}\u0000${lines}\n` + } return key } +/** 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 + * `data-` attributes for the row's tests. */ +function PlusMinus(props: { additions: number; deletions: number; note?: string }): ReactNode { + return ( + + {props.additions > 0 && +{props.additions}} + {props.deletions > 0 && −{props.deletions}} + + ) +} + +/** One row's line counts (#131): the numbers for a text change, the binary + * mark when git has none for a blob, and "new file" for an untracked entry — + * git never diffs those, so there is no numstat row and `+0 −0` would be an + * invented number. An entry with no counts that is NOT untracked (a status + * answer whose numstat read failed) shows nothing at all. */ +function LineCounts(props: { counts?: GitLineCounts; untracked: boolean }): ReactNode { + const { counts } = props + if (counts === undefined) { + return props.untracked + ? {t('changesNewFile')} + : null + } + if (!('additions' in counts)) return {t('diffBinary')} + return +} + /** The preview ref for one changed file (one ref per path+side). */ function worktreeRefOf( path: string, @@ -189,6 +228,9 @@ const FileRow = memo(function FileRow(props: { {node.status.letter} {node.name} + {/* The row's own line counts (#131): read straight off the node, so a + poll that answered different numbers re-renders this row with them. */} + sumLineCounts(unstagedTree), [unstagedTree]) + const stagedTotal = useMemo(() => sumLineCounts(stagedTree), [stagedTree]) const isRepo = snapshot?.isRepo === true const branch = snapshot?.branch ?? '' const branchOptions = branch === '' ? branchNames : [branch, ...branchNames.filter(name => name !== branch)] @@ -945,6 +991,10 @@ export function GitLens(props: GitLensProps) { : undefined} > {unstagedEntries.length} + {/* The group's line total (#131): the sum of its file rows. */} + {unstagedTotal.files > 0 && ( + + )} {renderTree(unstagedTree, false)} @@ -966,6 +1016,9 @@ export function GitLens(props: GitLensProps) { : undefined} > {stagedEntries.length} + {stagedTotal.files > 0 && ( + + )} {renderTree(stagedTree, true)} diff --git a/src/client/changes/change-tree.ts b/src/client/changes/change-tree.ts index 20f6ec83..15c7e678 100644 --- a/src/client/changes/change-tree.ts +++ b/src/client/changes/change-tree.ts @@ -12,7 +12,7 @@ * Pure — no React, no DOM. `buildChangeTree` runs once per group per fold; * the renderer only walks the result. */ -import type { GitStatusEntry } from '../api.ts' +import type { GitLineCounts, GitStatusEntry } from '../api.ts' import { statusOfXY, type GitFileStatus } from '../ui/index.ts' /** One changed file (a leaf), carrying its porcelain status. */ @@ -23,6 +23,9 @@ 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. */ + counts?: GitLineCounts } /** One directory row: its children plus the number of changed files beneath. */ @@ -132,7 +135,46 @@ 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. - at.files.push({ kind: 'file', name: segments[segments.length - 1]!, path: entry.path, status }) + at.files.push({ + kind: 'file', + name: segments[segments.length - 1]!, + path: entry.path, + status, + ...(entry.counts !== undefined ? { counts: entry.counts } : {}), + }) } return finishChildren(root) } + +/** One group's summed line counts, plus how many rows contributed them. */ +export interface ChangeLineTotals { + additions: number + deletions: number + /** Rows that actually carry counts. 0 means the group has nothing to sum + * (e.g. only untracked files), so the header must show no total at all. */ + files: number +} + +/** + * Sum one group tree's line counts (#131): the group header's total is exactly + * the sum of the numbers its own file rows print. Binary rows and rows without + * counts (untracked files) contribute nothing — never a fabricated 0 — and + * folding a directory is a view state, so every member counts either way. + */ +export function sumLineCounts(nodes: readonly ChangeNode[]): ChangeLineTotals { + const totals: ChangeLineTotals = { additions: 0, deletions: 0, files: 0 } + for (const node of nodes) { + if (node.kind === 'dir') { + const inner = sumLineCounts(node.children) + totals.additions += inner.additions + totals.deletions += inner.deletions + totals.files += inner.files + continue + } + if (node.counts === undefined || !('additions' in node.counts)) continue + totals.additions += node.counts.additions + totals.deletions += node.counts.deletions + totals.files += 1 + } + return totals +} diff --git a/src/client/changes/changes.module.css b/src/client/changes/changes.module.css index 859c0d21..f1a45cf3 100644 --- a/src/client/changes/changes.module.css +++ b/src/client/changes/changes.module.css @@ -196,6 +196,28 @@ .rowName { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--dsw-font-xxs-12); color: var(--dsw-alias-label-primary); } +/* A row's / band's line counts (#131): `+N −M` in the diff pane's own ink (the + `.statAdd` / `.statDel` atoms of `diff.module.css`, reused rather than + re-coloured here). Tabular figures keep the column from shifting between + readings, and the code face matches every other number in the tab. */ +.lineCounts { + flex: none; + display: inline-flex; + gap: 5px; + font-family: var(--ds-font-family-code, monospace); + font-size: 10px; + font-variant-numeric: tabular-nums; +} + +/* The stand-ins for "no numbers exist": a binary change and an untracked (new) + file. Quiet tertiary ink — they are a state, not a measurement. */ +.lineNote { + flex: none; + font: var(--dsw-font-xxxs-11); + color: var(--dsw-alias-label-tertiary); + white-space: nowrap; +} + /* The row action is invisible until its row is hovered or holds focus (a keyboard tab lands on it and reveals it). The three-class form outranks the kit's own disabled rule, which would otherwise pin every button to a dim but diff --git a/src/client/locales-ar.ts b/src/client/locales-ar.ts index f70778f2..e28c7c33 100644 --- a/src/client/locales-ar.ts +++ b/src/client/locales-ar.ts @@ -111,6 +111,7 @@ export const ar: Record = { gitStatusConflict: 'تعارض', changesClean: 'لا توجد تغييرات في مساحة العمل', changesNoHistory: 'لا يوجد سجل إيداعات بعد', + changesNewFile: 'ملف جديد', changesStageFailed: 'فشل الإدراج: {message}', changesOpGone: 'لم تعد هذه العملية في سجل الجلسة', newTab: 'تبويب جديد', diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts index d72040c9..f9ad4d0e 100644 --- a/src/client/locales-de.ts +++ b/src/client/locales-de.ts @@ -96,6 +96,7 @@ export const de: Record = { gitStatusConflict: 'Konflikt', changesClean: 'Keine Änderungen im Arbeitsbereich', changesNoHistory: 'Noch keine Commit-Historie', + changesNewFile: 'Neue Datei', changesStageFailed: 'Staging fehlgeschlagen: {message}', changesOpGone: 'Dieser Vorgang ist nicht mehr im Sitzungsprotokoll', newTab: 'Neuer Tab', diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts index e0158e9f..cb6095e0 100644 --- a/src/client/locales-fr.ts +++ b/src/client/locales-fr.ts @@ -103,6 +103,7 @@ export const fr: Record = { gitStatusConflict: 'En conflit', changesClean: 'Aucune modification dans le workspace', changesNoHistory: 'Aucun commit pour l’instant', + changesNewFile: 'Nouveau fichier', changesStageFailed: 'Échec de l’indexation : {message}', changesOpGone: 'Cette opération n’est plus dans le journal de la session', newTab: 'Nouvel onglet', diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts index 8dbd3283..a4ecd266 100644 --- a/src/client/locales-hi.ts +++ b/src/client/locales-hi.ts @@ -110,6 +110,7 @@ export const hi: Record = { gitStatusConflict: 'टकराव', changesClean: 'वर्कस्पेस में कोई बदलाव नहीं', changesNoHistory: 'अभी कोई कमिट इतिहास नहीं', + changesNewFile: 'नई फ़ाइल', changesStageFailed: 'स्टेज विफल: {message}', changesOpGone: 'यह कार्रवाई अब सत्र लॉग में नहीं है', newTab: 'नया टैब', diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts index 49113aa3..fc703602 100644 --- a/src/client/locales-id.ts +++ b/src/client/locales-id.ts @@ -108,6 +108,7 @@ export const id: Record = { gitStatusConflict: 'Konflik', changesClean: 'Tidak ada perubahan di workspace', changesNoHistory: 'Belum ada riwayat commit', + changesNewFile: 'File baru', changesStageFailed: 'Gagal melakukan stage: {message}', changesOpGone: 'Operasi ini tidak lagi ada di log sesi', newTab: 'Tab baru', diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts index 25040b7a..373ce3c5 100644 --- a/src/client/locales-it.ts +++ b/src/client/locales-it.ts @@ -101,6 +101,7 @@ export const it: Record = { gitStatusConflict: 'In conflitto', changesClean: 'Nessuna modifica nel workspace', changesNoHistory: 'Nessun commit per ora', + changesNewFile: 'Nuovo file', changesStageFailed: 'Staging non riuscito: {message}', changesOpGone: 'Questa operazione non è più nel registro della sessione', newTab: 'Nuova scheda', diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts index aae4e720..8abb7332 100644 --- a/src/client/locales-ja.ts +++ b/src/client/locales-ja.ts @@ -110,6 +110,7 @@ export const ja: Record = { gitStatusConflict: '競合', changesClean: 'ワークスペースに変更はありません', changesNoHistory: 'コミット履歴がまだありません', + changesNewFile: '新規ファイル', changesStageFailed: 'ステージに失敗しました:{message}', changesOpGone: 'この操作はセッションログに残っていません', newTab: '新しいタブ', diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts index ce9fe17c..631a8a53 100644 --- a/src/client/locales-ko.ts +++ b/src/client/locales-ko.ts @@ -102,6 +102,7 @@ export const ko: Record = { gitStatusConflict: '충돌', changesClean: '워크스페이스에 변경 사항이 없습니다', changesNoHistory: '아직 커밋 기록이 없습니다', + changesNewFile: '새 파일', changesStageFailed: '스테이징 실패: {message}', changesOpGone: '이 작업은 더 이상 세션 로그에 없습니다', newTab: '새 탭', diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts index 3e1b7954..5a0961e1 100644 --- a/src/client/locales-nl.ts +++ b/src/client/locales-nl.ts @@ -108,6 +108,7 @@ export const nl: Record = { gitStatusConflict: 'Conflict', changesClean: 'Geen wijzigingen in de workspace', changesNoHistory: 'Nog geen commitgeschiedenis', + changesNewFile: 'Nieuw bestand', changesStageFailed: 'Stagen mislukt: {message}', changesOpGone: 'Deze bewerking staat niet meer in het sessielogboek', newTab: 'Nieuw tabblad', diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts index 222875ed..e052095f 100644 --- a/src/client/locales-pl.ts +++ b/src/client/locales-pl.ts @@ -112,6 +112,7 @@ export const pl: Record = { gitStatusConflict: 'Konflikt', changesClean: 'Brak zmian w obszarze roboczym', changesNoHistory: 'Brak historii commitów', + changesNewFile: 'Nowy plik', changesStageFailed: 'Nie udało się wykonać stage: {message}', changesOpGone: 'Tej operacji nie ma już w dzienniku sesji', newTab: 'Nowa karta', diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts index cab81a1e..c4eea00c 100644 --- a/src/client/locales-pt.ts +++ b/src/client/locales-pt.ts @@ -93,6 +93,7 @@ export const pt: Record = { gitStatusConflict: 'Em conflito', changesClean: 'Nenhuma alteração no workspace', changesNoHistory: 'Ainda não há histórico de commits', + changesNewFile: 'Novo arquivo', changesStageFailed: 'Falha ao preparar: {message}', changesOpGone: 'Esta operação não está mais no registro da sessão', newTab: 'Nova aba', diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts index 714456a5..5b4b34ea 100644 --- a/src/client/locales-ru.ts +++ b/src/client/locales-ru.ts @@ -106,6 +106,7 @@ export const ru: Record = { gitStatusConflict: 'Конфликт', changesClean: 'В рабочей области нет изменений', changesNoHistory: 'Истории коммитов пока нет', + changesNewFile: 'Новый файл', changesStageFailed: 'Ошибка индексирования: {message}', changesOpGone: 'Этой операции больше нет в журнале сессии', newTab: 'Новая вкладка', diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts index 4cef3392..05d94322 100644 --- a/src/client/locales-sv.ts +++ b/src/client/locales-sv.ts @@ -93,6 +93,7 @@ export const sv: Record = { gitStatusConflict: 'Konflikt', changesClean: 'Inga ändringar i arbetsytan', changesNoHistory: 'Ingen commit-historik ännu', + changesNewFile: 'Ny fil', changesStageFailed: 'Kunde inte köa: {message}', changesOpGone: 'Åtgärden finns inte längre i sessionsloggen', newTab: 'Ny flik', diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts index 6636f732..f6cd4481 100644 --- a/src/client/locales-th.ts +++ b/src/client/locales-th.ts @@ -110,6 +110,7 @@ export const th: Record = { gitStatusConflict: 'มีความขัดแย้ง', changesClean: 'ไม่มีการเปลี่ยนแปลงในเวิร์กสเปซ', changesNoHistory: 'ยังไม่มีประวัติการ commit', + changesNewFile: 'ไฟล์ใหม่', changesStageFailed: 'stage ไม่สำเร็จ: {message}', changesOpGone: 'การดำเนินการนี้ไม่อยู่ในบันทึกเซสชันแล้ว', newTab: 'Tab ใหม่', diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts index 70321507..9cc6ab02 100644 --- a/src/client/locales-tr.ts +++ b/src/client/locales-tr.ts @@ -110,6 +110,7 @@ export const tr: Record = { gitStatusConflict: 'Çakışma', changesClean: 'Çalışma alanında değişiklik yok', changesNoHistory: 'Henüz commit geçmişi yok', + changesNewFile: 'Yeni dosya', changesStageFailed: 'Sahneleme başarısız: {message}', changesOpGone: 'Bu işlem artık oturum günlüğünde değil', newTab: 'Yeni sekme', diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts index 58ecb9d8..bc65e3ec 100644 --- a/src/client/locales-vi.ts +++ b/src/client/locales-vi.ts @@ -110,6 +110,7 @@ export const vi: Record = { gitStatusConflict: 'Xung đột', changesClean: 'Không có thay đổi trong workspace', changesNoHistory: 'Chưa có lịch sử commit', + changesNewFile: 'Tệp mới', changesStageFailed: 'Stage thất bại: {message}', changesOpGone: 'Thao tác này không còn trong nhật ký phiên', newTab: 'Tab mới', diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts index 104261ab..38c747f6 100644 --- a/src/client/locales-zh-HK.ts +++ b/src/client/locales-zh-HK.ts @@ -125,6 +125,7 @@ export const zhHK: Record = { gitStatusConflict: '有衝突', changesClean: '工作區沒有變更', changesNoHistory: '還沒有提交歷史', + changesNewFile: '新文件', changesStageFailed: '暫存失敗:{message}', changesOpGone: '此操作已不在工作階段記錄中', newTab: '新增標籤', diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts index 7e7593d3..c67404d3 100644 --- a/src/client/locales-zh-MO.ts +++ b/src/client/locales-zh-MO.ts @@ -125,6 +125,7 @@ export const zhMO: Record = { gitStatusConflict: '有衝突', changesClean: '工作區沒有變更', changesNoHistory: '還沒有提交歷史', + changesNewFile: '新文件', changesStageFailed: '暫存失敗:{message}', changesOpGone: '此操作已不在工作階段記錄中', newTab: '新增標籤', diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts index 3ee2eabb..867ea4d5 100644 --- a/src/client/locales-zh-TW.ts +++ b/src/client/locales-zh-TW.ts @@ -125,6 +125,7 @@ export const zhTW: Record = { gitStatusConflict: '有衝突', changesClean: '工作區沒有變更', changesNoHistory: '還沒有提交歷史', + changesNewFile: '新檔案', changesStageFailed: '暫存失敗:{message}', changesOpGone: '此操作已不在作業階段記錄中', newTab: '新增標籤', diff --git a/src/client/locales.ts b/src/client/locales.ts index 33c0ed97..eb57d851 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -122,6 +122,7 @@ export const zh = { gitStatusConflict: '有冲突', changesClean: '工作区没有变更', changesNoHistory: '还没有提交历史', + changesNewFile: '新文件', changesStageFailed: '暂存失败:{message}', changesOpGone: '该操作已不在会话记录中', newTab: '新建标签页', @@ -690,6 +691,7 @@ export const en: Record = { gitStatusConflict: 'Conflicted', changesClean: 'No changes in the working tree', changesNoHistory: 'No commits yet', + changesNewFile: 'New file', changesStageFailed: 'Staging failed: {message}', changesOpGone: 'This operation is no longer in the session log', newTab: 'New tab', diff --git a/src/client/ui/git-status.ts b/src/client/ui/git-status.ts index 3d6ef64c..25dc0477 100644 --- a/src/client/ui/git-status.ts +++ b/src/client/ui/git-status.ts @@ -21,7 +21,7 @@ * returned early, so a click during the poll silently did nothing). */ import { useCallback, useEffect, useSyncExternalStore } from 'react' -import { api, type GitStatusResult, type SessionScope } from '../api.ts' +import { api, type GitLineCounts, type GitStatusResult, type SessionScope } from '../api.ts' /** The semantic class of one changed path (drives the row's ink). */ export type GitTone = @@ -90,6 +90,22 @@ function joinRoot(root: string, rel: string): string { return `${base}/${rel.replace(/^[\\/]+/, '')}` } +/** + * 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. + */ +function sameCounts(left: GitLineCounts | undefined, right: GitLineCounts | undefined): boolean { + if (left === right) return true + if (left === undefined || right === undefined) return false + if ('additions' in left && 'additions' in right) { + return left.additions === right.additions && left.deletions === right.deletions + } + return 'binary' in left && 'binary' in right +} + /** * Whether two status snapshots carry the same information. Compared field by * field (never by serializing the whole object): the entries are the payload @@ -104,7 +120,7 @@ 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 + return entry.path === other.path && entry.xy === other.xy && sameCounts(entry.counts, other.counts) }) } diff --git a/src/git.ts b/src/git.ts index 081296aa..4865b62e 100644 --- a/src/git.ts +++ b/src/git.ts @@ -21,8 +21,18 @@ 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 } +/** One path's line-count summary from `git diff --numstat`. A binary change is + * its own variant because git reports `-`/`-` for it: there ARE no counts, and + * saying `+0 −0` would invent a number. */ +export type GitLineCounts = { additions: number; deletions: number } | { binary: true } + /** The source-control panel snapshot. */ export interface GitStatusResult { isRepo: boolean @@ -95,6 +105,81 @@ export function parsePorcelainZ(output: string): GitStatusEntry[] { return entries } +/** + * Resolve one `--numstat` path field to the path the file has NOW: the plain + * (`old => new`) and brace (`src/{a => b}/x.ts`) rename notations both fold + * into the new name, and anything else passes through verbatim. + * + * Only the LINE-framed output needs this: in `-z` framing git writes the two + * names as separate NUL fields, so a path is never folded into rename notation + * there — a file literally named `a => b.txt` keeps its own name. + */ +function resolveNumstatPath(path: string): string { + const arrow = path.indexOf(' => ') + if (arrow === -1) return path + const open = path.indexOf('{') + if (open !== -1 && open < arrow) { + const close = path.indexOf('}', arrow + 4) + if (close !== -1) return `${path.slice(0, open)}${path.slice(arrow + 4, close)}${path.slice(close + 1)}` + } + return path.slice(arrow + 4) +} + +/** + * Parse one `git diff --numstat` answer into a path → line-counts map. Both + * framings are accepted: the production `-z` one (records NUL-framed, so paths + * with newlines or quotes stay lossless) and the plain line-framed one. + * + * Three record shapes exist: + * - `2\t0\tpath` — an ordinary change, + * - `-\t-\tpath` — a binary change: no counts exist, so it maps to the binary + * variant rather than to `0 0`, + * - renames — the path field is the pair `old => new` (or the brace form + * `src/{a => b}/x.ts`) in line framing, and two NUL-framed fields (origin + * first) in `-z` framing. + * + * A rename is attributed to the NEW path: that is the file as it exists now, + * and the exact path `git status --porcelain` reports for the same change, so + * the counts land on the row the panel renders. + */ +export function parseNumstat(output: string): Map { + const counts = new Map() + const framed = output.includes('\0') + const records = output.split(framed ? '\0' : '\n') + let index = 0 + while (index < records.length) { + const record = records[index]! + index += 1 + if (record === '') continue + const addedEnd = record.indexOf('\t') + const deletedEnd = addedEnd === -1 ? -1 : record.indexOf('\t', addedEnd + 1) + // Not a numstat record (a stray line, or a truncated answer). + if (deletedEnd === -1) continue + const added = record.slice(0, addedEnd) + const deleted = record.slice(addedEnd + 1, deletedEnd) + let path = record.slice(deletedEnd + 1) + if (framed && path === '') { + // A rename: the origin and the new name are the next two NUL fields. + const renamed = records[index + 1] + index += 2 + if (renamed === undefined) continue + path = renamed + } else if (!framed) { + path = resolveNumstatPath(path) + } + if (path === '') continue + if (added === '-' || deleted === '-') { + counts.set(path, { binary: true }) + continue + } + const additions = Number(added) + const deletions = Number(deleted) + if (!Number.isFinite(additions) || !Number.isFinite(deletions)) continue + counts.set(path, { additions, deletions }) + } + return counts +} + /** One raw porcelain worktree record. Prunable checkouts are retained by * Git's administrative metadata after their directory disappears and must not * become selectable command targets. Locked checkouts remain usable. */ @@ -305,25 +390,66 @@ export async function currentBranch(cwd: string): Promise { * freeze the browser main thread on JSON parse or list render (#369). */ const GIT_STATUS_LIMIT = 2_000 +/** + * 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, from: Map): 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, + }) + } +} + /** * Working-tree status (untracked included). `--untracked-files=all` lists * the contents of new directories as individual entries, while preserving * repository discovery and explicit repository selection for workspace roots. + * + * The per-path line counts (#131) ride this SAME read: one batch of three git + * processes answers status and both numstat sides together, never one process + * per file, and callers keep their existing refresh cadence. A numstat failure + * costs only the counts (the rows fall back to their count-less rendering) — + * the status answer itself must never fail because of it. */ export async function status(cwd: string, selected?: string): Promise { const repositories = await repoRoots(cwd) if (repositories.length === 0) return { isRepo: false, entries: [], repositories: [] } const root = await repoRoot(cwd, selected) - const [branch, raw] = await Promise.all([ + const [branch, raw, unstagedNumstat, stagedNumstat] = await Promise.all([ currentBranch(root).catch(() => 'HEAD'), runGit(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']), + runGit(root, ['diff', '--numstat', '-z']).catch(() => ''), + runGit(root, ['diff', '--cached', '--numstat', '-z']).catch(() => ''), ]) const parsed = parsePorcelainZ(raw) + const lineCounts = new Map() + addLineCounts(lineCounts, parseNumstat(stagedNumstat)) + addLineCounts(lineCounts, parseNumstat(unstagedNumstat)) const truncated = parsed.length > GIT_STATUS_LIMIT + const bounded = truncated ? parsed.slice(0, GIT_STATUS_LIMIT) : parsed return { isRepo: true, branch, - entries: truncated ? parsed.slice(0, GIT_STATUS_LIMIT) : parsed, + // Paths git has no numstat row for (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 } + }), truncated, root, repositories, diff --git a/tests/change-tree-counts.spec.ts b/tests/change-tree-counts.spec.ts new file mode 100644 index 00000000..8bb8a706 --- /dev/null +++ b/tests/change-tree-counts.spec.ts @@ -0,0 +1,74 @@ +/** + * 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. + */ +import { describe, expect, it } from 'vitest' +import { buildChangeTree, sumLineCounts } from '../src/client/changes/change-tree.ts' +import type { 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 } +} + +describe('change tree line counts', () => { + it('keeps each entry counts on its own leaf', () => { + const tree = buildChangeTree([ + entry('src/a.ts', ' M', { additions: 4, deletions: 2 }), + entry('src/deep/b.ts', ' M', { binary: true }), + entry('new.txt', '??'), + ]) + const src = tree.find(node => node.kind === 'dir' && node.path === 'src')! + expect(src.kind).toBe('dir') + const leaves = src.kind === 'dir' ? src.children : [] + expect(leaves.find(node => node.kind === 'file' && node.path === 'src/a.ts')) + .toMatchObject({ counts: { additions: 4, deletions: 2 } }) + // The binary leaf keeps the binary marker, never a count of 0. + const nested = leaves.find(node => node.kind === 'dir')! + const nestedLeaves = nested.kind === 'dir' ? nested.children : [] + expect(nestedLeaves[0]).toMatchObject({ path: 'src/deep/b.ts', counts: { binary: true } }) + // The untracked leaf has NO counts property at all. + const untracked = tree.find(node => node.kind === 'file' && node.path === 'new.txt')! + expect(untracked.kind === 'file' && 'counts' in untracked).toBe(false) + }) + + 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 }), + ]) + expect(sumLineCounts(tree)).toEqual({ additions: 8, deletions: 5, files: 3 }) + }) + + it('counts only the rows that HAVE numbers (binary and untracked add nothing)', () => { + const tree = buildChangeTree([ + entry('src/a.ts', ' M', { additions: 4, deletions: 2 }), + entry('blob.bin', ' M', { binary: true }), + entry('new.txt', '??'), + ]) + // 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 }) + }) + + it('counts every member regardless of how deep the directory chain folds', () => { + // One compressed chain row stands for `src/client/changes`; the total must + // still be the sum of the leaves under it. + 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 }), + ]) + expect(tree).toHaveLength(1) + expect(tree[0]).toMatchObject({ kind: 'dir', name: 'src/client/changes' }) + expect(sumLineCounts(tree)).toEqual({ additions: 7, deletions: 1, files: 2 }) + }) +}) diff --git a/tests/git-view-worktree.spec.tsx b/tests/git-view-worktree.spec.tsx index 87c2a920..403c5b48 100644 --- a/tests/git-view-worktree.spec.tsx +++ b/tests/git-view-worktree.spec.tsx @@ -16,7 +16,7 @@ import { createRoot, type Root } from 'react-dom/client' import { act } from 'react-dom/test-utils' import { GitLens } from '../src/client/changes/GitLens.tsx' import { createSidebarStore } from '../src/client/state.ts' -import { api, type GitLogEntry, type GitStatusResult, type GitWorktree } from '../src/client/api.ts' +import { api, type GitLogEntry, type GitStatusEntry, type GitStatusResult, type GitWorktree } from '../src/client/api.ts' import type { BetterSidebarService } from '../src/client/service.ts' import { t } from '../src/client/locales.ts' import type { Context } from '../src/context-types.ts' @@ -448,7 +448,7 @@ describe('GitLens (changes tab, git lens) change tree', () => { async function mountTree( container: HTMLElement, root: Root, - entries: Array<{ path: string; xy: string }>, + entries: Array<{ path: string; xy: string; counts?: GitStatusEntry['counts'] }>, ): Promise { const changes = entries.filter(row => row.xy !== ' ').length vi.spyOn(api, 'gitWorktrees').mockResolvedValue([{ path: MAIN, branch: 'main', current: true, changes }]) @@ -684,4 +684,118 @@ describe('GitLens (changes tab, git lens) change tree', () => { vi.useRealTimers() } }) + + /** + * Issue #131: the added/deleted line counts the status answer carries are + * what the file rows and the group headers print. The header's number is the + * sum of the numbers under it, and a row git has no numstat for (an untracked + * file, a binary blob) says so instead of printing an invented `+0 −0`. + */ + describe('line counts (#131)', () => { + /** One rendered row's/band's count cluster, as its data attributes. */ + function counted(container: HTMLElement, selector: string): { added: string | null; deleted: string | null; text: string } { + const node = container.querySelector(selector) + expect(node, selector).not.toBeNull() + return { + added: node!.getAttribute('data-added'), + deleted: node!.getAttribute('data-deleted'), + text: node!.textContent ?? '', + } + } + + it('prints each row its own counts and each band the sum of its members', async () => { + 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 } }, + ]) + + expect(counted(container, '[data-path="src/a.ts"] [data-lines="count"]')) + .toEqual({ added: '4', deleted: '2', text: '+4−2' }) + expect(counted(container, '[data-path="src/b.ts"] [data-lines="count"]')) + .toEqual({ added: '1', deleted: '0', text: '+1' }) + expect(counted(container, '[data-path="docs/c.md"] [data-lines="count"]')) + .toEqual({ added: '3', deleted: '3', text: '+3−3' }) + + // Each band's total IS the sum of the rows under it (4+1 / 2+0 and + // 3 / 3) — and each group only counts its own members. + expect(counted(container, '[data-group="unstaged"] [data-lines="group"]')) + .toEqual({ added: '5', deleted: '2', text: '+5−2' }) + expect(counted(container, '[data-group="staged"] [data-lines="group"]')) + .toEqual({ added: '3', deleted: '3', text: '+3−3' }) + + // The same numbers, read back off the DOM: band = Σ members. + const sumOf = (group: string, side: 'added' | 'deleted'): number => + [...container.querySelectorAll(`[data-group="${group}"] [data-path] [data-lines="count"]`)] + .reduce((total, node) => total + Number(node.getAttribute(`data-${side}`)), 0) + expect(sumOf('unstaged', 'added')).toBe(5) + expect(sumOf('unstaged', 'deleted')).toBe(2) + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) + + it('says "new file" for an untracked entry and "binary" for a blob, inventing no numbers', async () => { + const { container, root } = makeRoot() + try { + await mountTree(container, root, [ + { path: 'new.txt', xy: '??' }, + { path: 'blob.bin', xy: ' M', counts: { binary: true } }, + ]) + + expect(container.querySelector('[data-path="new.txt"] [data-lines="new"]')?.textContent) + .toBe(t('changesNewFile')) + expect(container.querySelector('[data-path="blob.bin"] [data-lines="binary"]')?.textContent) + .toBe(t('diffBinary')) + // Neither row claims a count... + expect(container.querySelector('[data-path="new.txt"] [data-lines="count"]')).toBeNull() + expect(container.querySelector('[data-path="blob.bin"] [data-lines="count"]')).toBeNull() + // ...and with nothing to sum, the band shows no total at all. + expect(container.querySelector('[data-group="unstaged"] [data-lines="group"]')).toBeNull() + // The count pill still reports how many files changed. + expect(container.querySelector('[data-group="unstaged"] [data-count]')?.textContent).toBe('2') + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) + + it('republishes the numbers when only the counts moved (same paths, same porcelain)', async () => { + vi.useFakeTimers() + const { container, root } = makeRoot() + try { + vi.spyOn(api, 'gitWorktrees').mockResolvedValue([{ path: MAIN, branch: 'main', current: true, changes: 1 }]) + // Two answers with the SAME path and the SAME porcelain code: only the + // 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 } }], + }) + .mockResolvedValue({ + isRepo: true, branch: 'main', entries: [{ path: 'src/a.ts', xy: ' M', counts: { additions: 7, deletions: 0 } }], + }) + vi.spyOn(api, 'gitBranch').mockResolvedValue({ current: 'main', names: ['main'] }) + vi.spyOn(api, 'gitLog').mockResolvedValue([]) + + mountGit(root) + await flushEffects() + expect(counted(container, '[data-path="src/a.ts"] [data-lines="count"]').added).toBe('1') + + await act(async () => { await vi.advanceTimersByTimeAsync(2_600) }) + await flushEffects() + // Both caches had to notice: the store's field-by-field snapshot + // compare AND the lens's content key. Either one ignoring the counts + // leaves the row printing its first reading forever. + expect(counted(container, '[data-path="src/a.ts"] [data-lines="count"]').added).toBe('7') + expect(counted(container, '[data-group="unstaged"] [data-lines="group"]').added).toBe('7') + } finally { + act(() => { root.unmount() }) + container.remove() + vi.useRealTimers() + } + }) + }) }) diff --git a/tests/git-worktree.spec.ts b/tests/git-worktree.spec.ts index c0b4e2ef..7a5e91f6 100644 --- a/tests/git-worktree.spec.ts +++ b/tests/git-worktree.spec.ts @@ -79,8 +79,10 @@ describe('linked Git worktrees', () => { expect(listed.find(entry => entry.current)).toMatchObject({ branch: 'main', changes: 0 }) 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. expect((await status(await resolveWorktree(main, agentPath))).entries).toEqual([ - { path: 'tracked.txt', xy: ' M' }, + { path: 'tracked.txt', xy: ' M', counts: { additions: 1, deletions: 1 } }, ]) await expect(resolveWorktree(main, root)).rejects.toThrow('unknown linked worktree') diff --git a/tests/git.spec.ts b/tests/git.spec.ts index 9b130356..316bb20a 100644 --- a/tests/git.spec.ts +++ b/tests/git.spec.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { promisify } from 'node:util' import { describe, expect, it } from 'vitest' import { parseUnifiedDiff } from '../src/client/diff/rows.ts' -import { checkout, parseLogLines, parsePorcelainZ, repoRoots, status } from '../src/git.ts' +import { checkout, parseLogLines, parseNumstat, parsePorcelainZ, repoRoots, status } from '../src/git.ts' const execFileAsync = promisify(execFile) const normalizePath = (path: string): string => path.replaceAll('\\', '/') @@ -298,3 +298,113 @@ describe('git parsing', () => { } }) }) + +/** + * Issue #131: the per-path added/deleted line counts ride the EXISTING status + * read (one batch, never one git process per file). The parser below is what + * turns `git diff --numstat` answers into those numbers. + */ +describe('numstat line counts (#131)', () => { + it('parses line-framed records into added/deleted per path', () => { + expect(parseNumstat(['2\t0\tsrc/a.ts', '0\t3\tsrc/b.ts', ''].join('\n'))).toEqual(new Map([ + ['src/a.ts', { additions: 2, deletions: 0 }], + ['src/b.ts', { additions: 0, deletions: 3 }], + ])) + }) + + it('parses the production NUL framing (what status() actually runs)', () => { + // `git diff --numstat -z` puts the counts and the path in NUL-framed + // records, so a path with a newline or a quote stays lossless. + expect(parseNumstat(['12\t4\tsrc/a.ts', '1\t1\todd\nname.ts', ''].join('\0'))).toEqual(new Map([ + ['src/a.ts', { additions: 12, deletions: 4 }], + ['odd\nname.ts', { additions: 1, deletions: 1 }], + ])) + }) + + it('reads a binary change as binary rather than as 0/0', () => { + // git prints `-` for both counts: there are no line counts to report, and + // a fabricated `0 0` would make a changed blob read as an empty change. + expect(parseNumstat('-\t-\tassets/logo.png\0')).toEqual(new Map([ + ['assets/logo.png', { binary: true }], + ])) + }) + + it('attributes a rename to the NEW path (plain and brace notations)', () => { + expect(parseNumstat(['5\t1\told.txt => new.txt', ''].join('\n'))).toEqual(new Map([ + ['new.txt', { additions: 5, deletions: 1 }], + ])) + // The brace form keeps the unchanged prefix/suffix around the arrow. + expect(parseNumstat(['3\t1\tsrc/{a => b}/x.ts', ''].join('\n'))).toEqual(new Map([ + ['src/b/x.ts', { additions: 3, deletions: 1 }], + ])) + }) + + it('attributes a NUL-framed rename from its two name fields', () => { + // In `-z` framing the origin and the new name are their own NUL fields + // (origin first) — the format `status()` consumes. + expect(parseNumstat('0\t0\t\0src/a/y.ts\0src/b/z.ts\0')).toEqual(new Map([ + ['src/b/z.ts', { additions: 0, deletions: 0 }], + ])) + }) + + it('keeps a path that literally contains an arrow under NUL framing', () => { + // `-z` framing never folds names into rename notation, so this is a real + // file name and must stay attributable to itself. + expect(parseNumstat('1\t0\ta => b.txt\0')).toEqual(new Map([ + ['a => b.txt', { additions: 1, deletions: 0 }], + ])) + }) + + it('answers an empty map for empty or junk output', () => { + expect(parseNumstat('')).toEqual(new Map()) + expect(parseNumstat('\0')).toEqual(new Map()) + 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 }) + + // 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. + 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') + // A staged rename: the counts belong to the new path. + execFileSync('git', ['mv', 'renamed.txt', 'moved.txt'], { cwd: root }) + // A binary blob, and an untracked file git will not diff at all. + writeFileSync(join(root, 'blob.bin'), Buffer.from([0, 1, 2, 3, 0, 5])) + execFileSync('git', ['add', 'blob.bin'], { cwd: root }) + writeFileSync(join(root, 'untracked.txt'), 'brand new\n') + + 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 }, + }) + expect(byPath.get('moved.txt')).toEqual({ + path: 'moved.txt', xy: 'R ', counts: { additions: 0, deletions: 0 }, + }) + expect(byPath.get('blob.bin')).toEqual({ + path: 'blob.bin', xy: 'A ', counts: { 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". + expect(byPath.get('untracked.txt')).toEqual({ path: 'untracked.txt', xy: '??' }) + expect(byPath.has('renamed.txt')).toBe(false) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) +})