feat(git-lens): 变更行数统计(numstat 随既有 status 一次取回,分组头合计 + 文件行增删,未跟踪显示新文件)(#131)

This commit is contained in:
Menghuan1918 committed 2026-10-05 22:19:26 +08:00
1 parent 97ba41d441
commit 99eb9190e0
30 files changed
+605 -16

No files matched your search

+9
View File
@@ -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. */
+59 -6
View File
@@ -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 (
<span className={css.lineCounts} data-lines={props.note ?? 'count'}
data-added={props.additions} data-deleted={props.deletions}>
{props.additions > 0 && <span className={diffCss.statAdd}>+{props.additions}</span>}
{props.deletions > 0 && <span className={diffCss.statDel}>−{props.deletions}</span>}
</span>
)
}
/** 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
? <span className={css.lineNote} data-lines="new">{t('changesNewFile')}</span>
: null
}
if (!('additions' in counts)) return <span className={css.lineNote} data-lines="binary">{t('diffBinary')}</span>
return <PlusMinus additions={counts.additions} deletions={counts.deletions} />
}
/** 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: {
<span className={css.rowIcon} aria-hidden="true">{props.glyph(node.path)}</span>
<StatusBadge tone={BADGE_TONE[node.status.tone]} title={node.path}>{node.status.letter}</StatusBadge>
<span className={css.rowName}>{node.name}</span>
{/* 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. */}
<LineCounts counts={node.counts} untracked={node.status.tone === 'untracked'} />
</button>
<IconButton
size="sm"
@@ -771,6 +813,10 @@ export function GitLens(props: GitLensProps) {
// memoized rows below keep their props and never re-render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [contentKey])
// The band totals (#131) sum the very nodes the rows render, so the header
// can never disagree with the numbers printed under it.
const unstagedTotal = useMemo(() => 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}
>
<span className={css.countPill} data-count={unstagedEntries.length}>{unstagedEntries.length}</span>
{/* The group's line total (#131): the sum of its file rows. */}
{unstagedTotal.files > 0 && (
<PlusMinus additions={unstagedTotal.additions} deletions={unstagedTotal.deletions} note="group" />
)}
</SectionHeader>
{renderTree(unstagedTree, false)}
</div>
@@ -966,6 +1016,9 @@ export function GitLens(props: GitLensProps) {
: undefined}
>
<span className={css.countPill} data-count={stagedEntries.length}>{stagedEntries.length}</span>
{stagedTotal.files > 0 && (
<PlusMinus additions={stagedTotal.additions} deletions={stagedTotal.deletions} note="group" />
)}
</SectionHeader>
{renderTree(stagedTree, true)}
</div>
+44 -2
View File
@@ -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
}
+22
View File
@@ -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
+1
View File
@@ -111,6 +111,7 @@ export const ar: Record<string, string> = {
gitStatusConflict: 'تعارض',
changesClean: 'لا توجد تغييرات في مساحة العمل',
changesNoHistory: 'لا يوجد سجل إيداعات بعد',
changesNewFile: 'ملف جديد',
changesStageFailed: 'فشل الإدراج: {message}',
changesOpGone: 'لم تعد هذه العملية في سجل الجلسة',
newTab: 'تبويب جديد',
+1
View File
@@ -96,6 +96,7 @@ export const de: Record<string, string> = {
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',
+1
View File
@@ -103,6 +103,7 @@ export const fr: Record<string, string> = {
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',
+1
View File
@@ -110,6 +110,7 @@ export const hi: Record<string, string> = {
gitStatusConflict: 'टकराव',
changesClean: 'वर्कस्पेस में कोई बदलाव नहीं',
changesNoHistory: 'अभी कोई कमिट इतिहास नहीं',
changesNewFile: 'नई फ़ाइल',
changesStageFailed: 'स्टेज विफल: {message}',
changesOpGone: 'यह कार्रवाई अब सत्र लॉग में नहीं है',
newTab: 'नया टैब',
+1
View File
@@ -108,6 +108,7 @@ export const id: Record<string, string> = {
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',
+1
View File
@@ -101,6 +101,7 @@ export const it: Record<string, string> = {
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',
+1
View File
@@ -110,6 +110,7 @@ export const ja: Record<string, string> = {
gitStatusConflict: '競合',
changesClean: 'ワークスペースに変更はありません',
changesNoHistory: 'コミット履歴がまだありません',
changesNewFile: '新規ファイル',
changesStageFailed: 'ステージに失敗しました:{message}',
changesOpGone: 'この操作はセッションログに残っていません',
newTab: '新しいタブ',
+1
View File
@@ -102,6 +102,7 @@ export const ko: Record<string, string> = {
gitStatusConflict: '충돌',
changesClean: '워크스페이스에 변경 사항이 없습니다',
changesNoHistory: '아직 커밋 기록이 없습니다',
changesNewFile: '새 파일',
changesStageFailed: '스테이징 실패: {message}',
changesOpGone: '이 작업은 더 이상 세션 로그에 없습니다',
newTab: '새 탭',
+1
View File
@@ -108,6 +108,7 @@ export const nl: Record<string, string> = {
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',
+1
View File
@@ -112,6 +112,7 @@ export const pl: Record<string, string> = {
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',
+1
View File
@@ -93,6 +93,7 @@ export const pt: Record<string, string> = {
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',
+1
View File
@@ -106,6 +106,7 @@ export const ru: Record<string, string> = {
gitStatusConflict: 'Конфликт',
changesClean: 'В рабочей области нет изменений',
changesNoHistory: 'Истории коммитов пока нет',
changesNewFile: 'Новый файл',
changesStageFailed: 'Ошибка индексирования: {message}',
changesOpGone: 'Этой операции больше нет в журнале сессии',
newTab: 'Новая вкладка',
+1
View File
@@ -93,6 +93,7 @@ export const sv: Record<string, string> = {
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',
+1
View File
@@ -110,6 +110,7 @@ export const th: Record<string, string> = {
gitStatusConflict: 'มีความขัดแย้ง',
changesClean: 'ไม่มีการเปลี่ยนแปลงในเวิร์กสเปซ',
changesNoHistory: 'ยังไม่มีประวัติการ commit',
changesNewFile: 'ไฟล์ใหม่',
changesStageFailed: 'stage ไม่สำเร็จ: {message}',
changesOpGone: 'การดำเนินการนี้ไม่อยู่ในบันทึกเซสชันแล้ว',
newTab: 'Tab ใหม่',
+1
View File
@@ -110,6 +110,7 @@ export const tr: Record<string, string> = {
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',
+1
View File
@@ -110,6 +110,7 @@ export const vi: Record<string, string> = {
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',
+1
View File
@@ -125,6 +125,7 @@ export const zhHK: Record<string, string> = {
gitStatusConflict: '有衝突',
changesClean: '工作區沒有變更',
changesNoHistory: '還沒有提交歷史',
changesNewFile: '新文件',
changesStageFailed: '暫存失敗:{message}',
changesOpGone: '此操作已不在工作階段記錄中',
newTab: '新增標籤',
+1
View File
@@ -125,6 +125,7 @@ export const zhMO: Record<string, string> = {
gitStatusConflict: '有衝突',
changesClean: '工作區沒有變更',
changesNoHistory: '還沒有提交歷史',
changesNewFile: '新文件',
changesStageFailed: '暫存失敗:{message}',
changesOpGone: '此操作已不在工作階段記錄中',
newTab: '新增標籤',
+1
View File
@@ -125,6 +125,7 @@ export const zhTW: Record<string, string> = {
gitStatusConflict: '有衝突',
changesClean: '工作區沒有變更',
changesNoHistory: '還沒有提交歷史',
changesNewFile: '新檔案',
changesStageFailed: '暫存失敗:{message}',
changesOpGone: '此操作已不在作業階段記錄中',
newTab: '新增標籤',
+2
View File
@@ -122,6 +122,7 @@ export const zh = {
gitStatusConflict: '有冲突',
changesClean: '工作区没有变更',
changesNoHistory: '还没有提交历史',
changesNewFile: '新文件',
changesStageFailed: '暂存失败:{message}',
changesOpGone: '该操作已不在会话记录中',
newTab: '新建标签页',
@@ -690,6 +691,7 @@ export const en: Record<keyof typeof zh, string> = {
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',
+18 -2
View File
@@ -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)
})
}
+128 -2
View File
@@ -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<string, GitLineCounts> {
const counts = new Map<string, GitLineCounts>()
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<string> {
* 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<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,
})
}
}
/**
* 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<GitStatusResult> {
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<string, GitLineCounts>()
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,
+74
View File
@@ -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 })
})
})
+116 -2
View File
@@ -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<void> {
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<HTMLElement>(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<HTMLElement>(`[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()
}
})
})
})
+3 -1
View File
@@ -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')
+111 -1
View File
@@ -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 })
}
})
})