Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix: display changed files for diff command

ldstyle8ab8a80af911d
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index 92acfa7866..4d3069cfe1 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -92,7 +92,7 @@ import {
} from "./components/team-shared.js";
import { padToWidth, prefixedLines, renderStyledMarkdownLines, renderWrappedText } from "./rendering/text.js";
import { chalk, editorTheme, palette, selectListTheme, setCurrentThemeName } from "./theme.js";
-import type { Hunk, GitDiffData, TurnDiff } from "../core/types.js";
+import type { Hunk, GitDiffData, GitDiffStats, TurnDiff } from "../core/types.js";
const END_CURSOR = "\x1b[7m \x1b[0m";
const ENABLE_MOUSE_TRACKING = "\x1b[?1000h\x1b[?1006h";
@@ -372,15 +372,121 @@ interface DiffFileEntry {
source: "working" | string;
}
+export interface DiffSourceEntry {
+ label: string;
+ title: string;
+ subtitle: string;
+ stats: GitDiffStats | null;
+ files: DiffFileEntry[];
+ emptyMessage: string;
+}
+
type DiffViewerState = {
viewMode: "list" | "detail";
selectedIndex: number;
- files: DiffFileEntry[];
+ sourceIndex: number;
+ sources: DiffSourceEntry[];
scrollOffset: number;
- title: string;
- subtitle: string;
};
+type DiffFilePayload = {
+ filePath: string;
+ linesAdded: number;
+ linesRemoved: number;
+ isNewFile: boolean;
+ isUntracked?: boolean;
+ isBinary?: boolean;
+ isLargeFile?: boolean;
+ isTruncated?: boolean;
+ hunks?: Hunk[];
+};
+
+function toDiffFileEntry(file: DiffFilePayload, source: "working" | string): DiffFileEntry {
+ return {
+ filePath: file.filePath,
+ linesAdded: file.linesAdded,
+ linesRemoved: file.linesRemoved,
+ isNewFile: file.isNewFile,
+ isUntracked: file.isUntracked ?? (source === "working" ? file.isNewFile : false),
+ isBinary: file.isBinary ?? false,
+ isLargeFile: file.isLargeFile ?? false,
+ isTruncated: file.isTruncated ?? false,
+ hunks: file.hunks || [],
+ source,
+ };
+}
+
+function sortDiffFiles(files: DiffFileEntry[]): DiffFileEntry[] {
+ return files.sort((a, b) => a.filePath.localeCompare(b.filePath));
+}
+
+export function truncateDiffPathStart(pathValue: string, maxWidth: number): string {
+ if (pathValue.length <= maxWidth) {
+ return pathValue;
+ }
+ if (maxWidth <= 1) {
+ return "…";
+ }
+ return `…${pathValue.slice(-(maxWidth - 1))}`;
+}
+
+function formatDiffStats(stats: GitDiffStats | null): string {
+ const filesChanged = stats?.filesChanged ?? 0;
+ const linesAdded = stats?.linesAdded ?? 0;
+ const linesRemoved = stats?.linesRemoved ?? 0;
+ const noun = filesChanged === 1 ? "file" : "files";
+ const parts = [`${filesChanged} ${noun} changed`];
+ if (linesAdded > 0) {
+ parts.push(`+${linesAdded}`);
+ }
+ if (linesRemoved > 0) {
+ parts.push(`-${linesRemoved}`);
+ }
+ return parts.join(" ");
+}
+
+export function buildDiffViewerSources(payload: Record<string, unknown>): DiffSourceEntry[] {
+ const turns = (payload.turns || []) as TurnDiff[];
+ const gitDiff = (payload.gitDiff || null) as GitDiffData | null;
+ const sources: DiffSourceEntry[] = [];
+ const currentStats = gitDiff?.stats ?? {
+ filesChanged: 0,
+ linesAdded: 0,
+ linesRemoved: 0,
+ };
+ const currentFiles = gitDiff
+ ? sortDiffFiles(Object.values(gitDiff.files).map((file) => toDiffFileEntry(file, "working")))
+ : [];
+
+ sources.push({
+ label: "Current",
+ title: "Diff (git diff HEAD)",
+ subtitle: formatDiffStats(currentStats),
+ stats: currentStats,
+ files: currentFiles,
+ emptyMessage: currentStats.filesChanged > 0 && currentFiles.length === 0
+ ? "Too many files to display details"
+ : "Working tree is clean",
+ });
+
+ for (const turn of turns) {
+ const files = sortDiffFiles(
+ Object.values(turn.files).map((file) => toDiffFileEntry(file, `Turn ${turn.turnIndex}`)),
+ );
+ const prompt = turn.userPromptPreview ? ` · ${turn.userPromptPreview}` : "";
+ sources.push({
+ label: `T${turn.turnIndex}`,
+ title: `Diff (Turn ${turn.turnIndex})`,
+ subtitle: `${formatDiffStats(turn.stats)}${prompt}`,
+ stats: turn.stats,
+ files,
+ emptyMessage: "No file changes in this turn",
+ });
+ }
+
+ return sources;
+}
+
const PATH_DELIMITERS = new Set([" ", "\t", '"', "'", "="]);
function findLastPathDelimiter(text: string): number {
@@ -1495,59 +1601,14 @@ export class AppScreen implements Component, Focusable {
/** Enter DiffViewer mode to browse git/turn diffs interactively */
enterDiffViewer(payload: Record<string, unknown>): void {
- const turns = (payload.turns || []) as TurnDiff[];
- const gitDiff = (payload.gitDiff || null) as GitDiffData | null;
- const files: DiffFileEntry[] = [];
-
- if (gitDiff) {
- for (const f of Object.values(gitDiff.files)) {
- files.push({
- filePath: f.filePath,
- linesAdded: f.linesAdded,
- linesRemoved: f.linesRemoved,
- isNewFile: f.isNewFile,
- isUntracked: f.isUntracked ?? f.isNewFile,
- isBinary: f.isBinary ?? false,
- isLargeFile: f.isLargeFile ?? false,
- isTruncated: f.isTruncated ?? false,
- hunks: f.hunks || [],
- source: "working",
- });
- }
- }
-
- for (const turn of turns) {
- for (const f of Object.values(turn.files)) {
- files.push({
- filePath: f.filePath,
- linesAdded: f.linesAdded,
- linesRemoved: f.linesRemoved,
- isNewFile: f.isNewFile,
- isUntracked: f.isUntracked ?? false,
- isBinary: f.isBinary ?? false,
- isLargeFile: f.isLargeFile ?? false,
- isTruncated: f.isTruncated ?? false,
- hunks: f.hunks || [],
- source: `Turn ${turn.turnIndex}`,
- });
- }
- }
-
- const totalAdded = files.reduce((s, f) => s + f.linesAdded, 0);
- const totalRemoved = files.reduce((s, f) => s + f.linesRemoved, 0);
- const turnCount = turns.length;
- const title = `Diff (git diff HEAD)`;
- const parts: string[] = [`${files.length} files changed +${totalAdded} -${totalRemoved}`];
- if (turnCount > 0) parts.push(`turns:${turnCount}`);
- const subtitle = parts.join(" · ");
+ const sources = buildDiffViewerSources(payload);
this.diffViewerState = {
viewMode: "list",
selectedIndex: 0,
- files,
+ sourceIndex: 0,
+ sources,
scrollOffset: 0,
- title,
- subtitle,
};
this.tui.requestRender();
}
@@ -1557,6 +1618,26 @@ export class AppScreen implements Component, Focusable {
this.tui.requestRender();
}
+ private _currentDiffSource(): DiffSourceEntry | null {
+ if (!this.diffViewerState) return null;
+ return this.diffViewerState.sources[this.diffViewerState.sourceIndex]
+ ?? this.diffViewerState.sources[0]
+ ?? null;
+ }
+
+ private _selectDiffSource(sourceIndex: number): void {
+ if (!this.diffViewerState) return;
+ const maxIndex = Math.max(0, this.diffViewerState.sources.length - 1);
+ this.diffViewerState.sourceIndex = Math.max(0, Math.min(sourceIndex, maxIndex));
+ this.diffViewerState.selectedIndex = 0;
+ this.diffViewerState.scrollOffset = 0;
+ }
+
+ private _diffViewerHeaderLineCount(): number {
+ if (!this.diffViewerState) return 0;
+ return this.diffViewerState.sources.length > 1 ? 4 : 3;
+ }
+
private handleDiffViewerInput(data: string, height: number): void {
if (!this.diffViewerState) return;
@@ -1572,6 +1653,19 @@ export class AppScreen implements Component, Focusable {
}
if (this.diffViewerState.viewMode === "list") {
+ const source = this._currentDiffSource();
+ if (!source) return;
+
+ if (matchesKey(data, "left") || data.toLowerCase() === "h") {
+ this._selectDiffSource(this.diffViewerState.sourceIndex - 1);
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "right") || data.toLowerCase() === "l") {
+ this._selectDiffSource(this.diffViewerState.sourceIndex + 1);
+ this.tui.requestRender();
+ return;
+ }
// List view paginates a 5-file centered window derived from
// selectedIndex at render time, so navigation only needs to move the
// selection; the window follows automatically.
@@ -1583,14 +1677,14 @@ export class AppScreen implements Component, Focusable {
return;
}
if (matchesKey(data, "down") || data.toLowerCase() === "j") {
- if (this.diffViewerState.selectedIndex < this.diffViewerState.files.length - 1) {
+ if (this.diffViewerState.selectedIndex < source.files.length - 1) {
this.diffViewerState.selectedIndex++;
this.tui.requestRender();
}
return;
}
if (matchesKey(data, "return")) {
- const file = this.diffViewerState.files[this.diffViewerState.selectedIndex];
+ const file = source.files[this.diffViewerState.selectedIndex];
if (file) {
this.diffViewerState.viewMode = "detail";
this.diffViewerState.scrollOffset = 0;
@@ -1604,7 +1698,7 @@ export class AppScreen implements Component, Focusable {
return;
}
if (matchesKey(data, "end") || data.toLowerCase() === "shift+g") {
- this.diffViewerState.selectedIndex = Math.max(0, this.diffViewerState.files.length - 1);
+ this.diffViewerState.selectedIndex = Math.max(0, source.files.length - 1);
this.tui.requestRender();
return;
}
@@ -1612,7 +1706,8 @@ export class AppScreen implements Component, Focusable {
}
if (this.diffViewerState.viewMode === "detail") {
- const file = this.diffViewerState.files[this.diffViewerState.selectedIndex];
+ const source = this._currentDiffSource();
+ const file = source?.files[this.diffViewerState.selectedIndex];
if (!file) return;
if (matchesKey(data, "left") || data.toLowerCase() === "h") {
@@ -1623,7 +1718,7 @@ export class AppScreen implements Component, Focusable {
}
const totalLines = this._countDiffLines(file);
- const availableHeight = Math.max(1, height - 3);
+ const availableHeight = Math.max(1, height - this._diffViewerHeaderLineCount() - 1);
if (matchesKey(data, "up") || data.toLowerCase() === "k") {
this.diffViewerState.scrollOffset = Math.max(0, this.diffViewerState.scrollOffset - 1);
@@ -1736,11 +1831,24 @@ export class AppScreen implements Component, Focusable {
const safeWidth = Math.max(1, width);
const lines: string[] = [];
+ const source = this._currentDiffSource();
+ if (!source) return lines;
// Title
- lines.push(padToWidth(palette.border.panel(`━━━ ${this.diffViewerState.title} ━━━`), safeWidth));
+ lines.push(padToWidth(palette.border.panel(`━━━ ${source.title} ━━━`), safeWidth));
// Subtitle
- lines.push(padToWidth(palette.text.dim(` ${this.diffViewerState.subtitle}`), safeWidth));
+ lines.push(padToWidth(palette.text.dim(` ${source.subtitle}`), safeWidth));
+ if (this.diffViewerState.sources.length > 1) {
+ const selector = this.diffViewerState.sources
+ .map((item, index) => {
+ if (index === this.diffViewerState?.sourceIndex) {
+ return palette.text.accent(`[${item.label}]`);
+ }
+ return palette.text.dim(item.label);
+ })
+ .join(palette.text.dim(" · "));
+ lines.push(padToWidth(` ${selector}`, safeWidth));
+ }
lines.push(padToWidth(palette.text.dim(` ${"─".repeat(Math.max(0, safeWidth - 4))}`), safeWidth));
if (this.diffViewerState.viewMode === "list") {
@@ -1748,10 +1856,10 @@ export class AppScreen implements Component, Focusable {
// mirroring Claude Code's DiffFileList. When there are more files than
// the window, show ↑/↓ "N more files" hints above/below the window.
const MAX_VISIBLE = 5;
- const total = this.diffViewerState.files.length;
+ const total = source.files.length;
if (total === 0) {
- lines.push(padToWidth(palette.text.dim(" No file changes in this session"), safeWidth));
+ lines.push(padToWidth(palette.text.dim(` ${source.emptyMessage}`), safeWidth));
} else {
let start: number;
let end: number;
@@ -1776,13 +1884,11 @@ export class AppScreen implements Component, Focusable {
}
for (let i = start; i < end; i++) {
- const file = this.diffViewerState.files[i]!;
+ const file = source.files[i]!;
const isSelected = i === this.diffViewerState.selectedIndex;
const pointer = isSelected ? "❯ " : " ";
const relativePath = this._toRelativePath(file.filePath);
- const displayPath = relativePath.length > safeWidth - 16
- ? relativePath.slice(0, safeWidth - 19) + "..."
- : relativePath;
+ const displayPath = truncateDiffPathStart(relativePath, Math.max(1, safeWidth - 16));
// 构建右侧状态标签(对齐 Claude Code FileStats):
// - untracked → "untracked"
@@ -1801,28 +1907,36 @@ export class AppScreen implements Component, Focusable {
statsLabel = "Large file modified";
statsStyled = palette.text.dim("Large file modified");
} else {
- const addPart = palette.status.success(`+${file.linesAdded}`);
- const removePart = palette.status.error(`-${file.linesRemoved}`);
- statsLabel = `+${file.linesAdded} -${file.linesRemoved}`;
- statsStyled = `${addPart} ${removePart}`;
+ const statParts: string[] = [];
+ const styledParts: string[] = [];
+ if (file.linesAdded > 0) {
+ statParts.push(`+${file.linesAdded}`);
+ styledParts.push(palette.status.success(`+${file.linesAdded}`));
+ }
+ if (file.linesRemoved > 0) {
+ statParts.push(`-${file.linesRemoved}`);
+ styledParts.push(palette.status.error(`-${file.linesRemoved}`));
+ }
+ statsLabel = statParts.join(" ");
+ statsStyled = styledParts.join(" ");
if (file.isTruncated) {
- statsLabel += " (truncated)";
- statsStyled += palette.text.dim(" (truncated)");
+ statsLabel = statsLabel ? `${statsLabel} (truncated)` : "(truncated)";
+ statsStyled = statsStyled
+ ? `${statsStyled}${palette.text.dim(" (truncated)")}`
+ : palette.text.dim("(truncated)");
}
}
- const sourceLabel = file.source === "working" || file.isUntracked
- ? ""
- : file.isNewFile
- ? "(new)"
- : file.source;
+ const sourceLabel = file.isNewFile && !file.isUntracked ? "(new)" : "";
const line = `${pointer}${displayPath}`;
- const rightLabel = sourceLabel ? `${sourceLabel} ${statsLabel}` : statsLabel;
- const rightStyled = sourceLabel
- ? `${palette.text.dim(sourceLabel)} ${statsStyled}`
- : statsStyled;
- const padded = padToWidth(line, safeWidth - rightLabel.length - 1);
- const fullLine = `${padded}${rightStyled}`;
+ const rightLabel = [sourceLabel, statsLabel].filter(Boolean).join(" ");
+ const rightStyled = [
+ sourceLabel ? palette.text.dim(sourceLabel) : "",
+ statsStyled,
+ ].filter(Boolean).join(" ");
+ const fullLine = rightLabel
+ ? `${padToWidth(line, Math.max(1, safeWidth - rightLabel.length - 1))}${rightStyled}`
+ : padToWidth(line, safeWidth);
if (isSelected) {
lines.push(palette.text.accent(fullLine));
} else {
@@ -1839,11 +1953,11 @@ export class AppScreen implements Component, Focusable {
}
}
} else {
- const file = this.diffViewerState.files[this.diffViewerState.selectedIndex];
+ const file = source.files[this.diffViewerState.selectedIndex];
if (!file) return lines;
const detailLines = this._renderDiffDetailLines(file, safeWidth);
- const availableHeight = Math.max(1, this.tui.terminal.rows - 4);
+ const availableHeight = Math.max(1, this.tui.terminal.rows - lines.length - 1);
const offset = this.diffViewerState.scrollOffset;
const maxLines = Math.min(detailLines.length, offset + availableHeight);
@@ -1862,9 +1976,10 @@ export class AppScreen implements Component, Focusable {
return lines;
}
- const hintText = this.diffViewerState.files.length > 0
- ? " ↑/↓ to select · Enter to view · Esc to close"
- : " Esc to close";
+ const sourceHint = this.diffViewerState.sources.length > 1 ? "←/→ source · " : "";
+ const hintText = source.files.length > 0
+ ? ` ${sourceHint}↑/↓ to select · Enter to view · Esc to close`
+ : ` ${sourceHint}Esc to close`;
lines.push(padToWidth(palette.text.dim(hintText), safeWidth));
return lines;
diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.py
index 0296e52abf..5183edcded 100644
--- a/jiuwenswarm/server/utils/diff_service.py
+++ b/jiuwenswarm/server/utils/diff_service.py
@@ -493,6 +493,91 @@ class DiffService:
return hunks, truncated
+ @staticmethod
+ def _decode_c_escaped(inner: str) -> str:
+ """Decode git's C-style escapes in an already-unquoted path segment.
+
+ Handles ``\\t \\n \\r \\a \\b \\v \\f \\" \\\\`` , octal ``\\NNN`` and
+ hex ``\\xNN``; unknown escapes keep the backslash literally.
+ """
+ simple = {
+ "a": 0x07, "b": 0x08, "t": 0x09, "n": 0x0A,
+ "v": 0x0B, "f": 0x0C, "r": 0x0D, '"': 0x22, "\\": 0x5C,
+ }
+ out = bytearray()
+ i = 0
+ while i < len(inner):
+ ch = inner[i]
+ if ch != "\\":
+ out.extend(ch.encode("utf-8"))
+ i += 1
+ continue
+ i += 1
+ if i >= len(inner):
+ break
+ esc = inner[i]
+ if esc in simple:
+ out.append(simple[esc])
+ i += 1
+ continue
+ if esc == "x":
+ hexd = inner[i + 1:i + 3]
+ if len(hexd) == 2 and all(c in "0123456789abcdefABCDEF" for c in hexd):
+ out.append(int(hexd, 16) & 0xFF)
+ i += 3
+ continue
+ if esc in "01234567":
+ j = i
+ oct_digits = ""
+ while j < len(inner) and inner[j] in "01234567" and len(oct_digits) < 3:
+ oct_digits += inner[j]
+ j += 1
+ out.append(int(oct_digits, 8) & 0xFF)
+ i = j
+ continue
+ # Unknown escape: keep backslash and the char literally.
+ out.extend(b"\\")
+ out.extend(esc.encode("utf-8"))
+ i += 1
+ return out.decode("utf-8", errors="replace")
+
+ @staticmethod
+ def _unquote_git_path(path: str) -> str:
+ """Decode a git-quoted path back to its raw bytes.
+
+ git wraps paths containing control chars / quotes / backslashes in
+ double quotes and C-escapes the offending bytes. This quoting is
+ independent of ``core.quotepath`` (which only governs non-ASCII bytes),
+ so a literal TAB in a filename is emitted as ``"dir\\tfile.txt"``
+ regardless of that setting. Feeding the quoted form straight into
+ ``Path(repo) / path`` resolves to a non-existent file, so numstat,
+ diff headers and ls-files paths must be unquoted here to match the
+ real on-disk relative path. Unquoted paths are returned verbatim.
+ """
+ if not (len(path) >= 2 and path.startswith('"') and path.endswith('"')):
+ return path
+ return DiffService._decode_c_escaped(path[1:-1])
+
+ @staticmethod
+ def _extract_diff_header_path(token: str) -> str | None:
+ """Extract the on-disk relative path from a ``--- a/`` / ``+++ b/`` token.
+
+ git quotes the whole ``a/<path>`` / ``b/<path>`` form when the path
+ contains control chars (e.g. ``+++ "b/dir\\tfile.txt"``), so the prefix
+ lives inside the quotes. Strip the prefix and decode, returning the
+ real relative path, or ``None`` for ``/dev/null`` (deleted/new file
+ counterpart).
+ """
+ if token == "/dev/null":
+ return None
+ quoted = len(token) >= 2 and token.startswith('"') and token.endswith('"')
+ inner = token[1:-1] if quoted else token
+ for prefix in ("b/", "a/"):
+ if inner.startswith(prefix):
+ rel = inner[len(prefix):]
+ return DiffService._decode_c_escaped(rel) if quoted else rel
+ return DiffService._decode_c_escaped(inner) if quoted else inner
+
@staticmethod
def _run_git_command(project_dir: str, args: list[str]) -> str | None:
"""在 project_dir 中运行 git 命令,返回 stdout 或 None."""
@@ -585,7 +670,8 @@ class DiffService:
parts = line.split("\t")
if len(parts) < 3:
continue
- added_str, removed_str, file_path = parts[0], parts[1], parts[2]
+ added_str, removed_str = parts[0], parts[1]
+ file_path = "\t".join(parts[2:])
# rename 的 numstat 路径需归一化为新路径,否则与 _parse_git_diff_hunks
# 从 "+++ b/new" 提取的 key 不一致,导致 hunks 丢失。
# 两种形式:
@@ -599,6 +685,9 @@ class DiffService:
file_path = file_path[:m.start()] + m.group(2) + file_path[m.end():]
if " => " in file_path:
file_path = file_path.rsplit(" => ", 1)[-1].strip()
+ # 控制字符路径(如含 TAB)会被 git 加引号并 C 转义(与
+ # core.quotepath 无关),解码回原始字节串才能对应磁盘真实文件。
+ file_path = DiffService._unquote_git_path(file_path)
is_binary = added_str == "-" and removed_str == "-"
result[file_path] = {
"added": 0 if is_binary else int(added_str),
@@ -647,10 +736,14 @@ class DiffService:
line_counts: dict[str, int] = {}
truncated: set[str] = set()
- # 匹配 diff 头部: diff --git a/path b/path, --- a/path, +++ b/path
+ # 匹配 diff 头部: --- a/path, +++ b/path
+ # 控制字符路径会被整体加引号(如 +++ "b/dir\tfile.txt"),b/ 前缀在引号内,
+ # 所以捕获整个 token(含引号)再用 _extract_diff_header_path 剥前缀+解码。
+ # 限定 b//a/ 前缀或两端引号,避免把以 "++ " 开头的 hunk 内容行(会变成
+ # "+++ ...",无 b/ 前缀也非两端引号)误判为文件头。
# 对于删除文件,+++ b/ 行是 +++ /dev/null 不会匹配,需要回退到 --- a/ 行
- file_header_new_re = re.compile(r"^\+\+\+ b/(.+)$")
- file_header_old_re = re.compile(r"^--- a/(.+)$")
+ file_header_new_re = re.compile(r'^\+\+\+ (b/.*|".*")$')
+ file_header_old_re = re.compile(r'^--- (a/.*|".*")$')
# 匹配 hunk 头部: @@ -oldStart,oldLines +newStart,newLines @@
hunk_header_re = re.compile(
r"^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@"
@@ -660,20 +753,22 @@ class DiffService:
# 检测文件头(优先 +++ b/ 行)
file_match = file_header_new_re.match(line)
if file_match:
- current_file = file_match.group(1)
- if current_file not in files:
- files[current_file] = []
- line_counts[current_file] = 0
- current_hunk = None
+ resolved = DiffService._extract_diff_header_path(file_match.group(1))
+ if resolved is not None:
+ current_file = resolved
+ if current_file not in files:
+ files[current_file] = []
+ line_counts[current_file] = 0
+ current_hunk = None
continue
# 回退:对于删除文件,+++ b/ 不匹配(是 +++ /dev/null),
# 从 --- a/ 行提取文件路径
file_match = file_header_old_re.match(line)
if file_match:
- path = file_match.group(1)
- if path != "/dev/null":
- current_file = path
+ resolved = DiffService._extract_diff_header_path(file_match.group(1))
+ if resolved is not None:
+ current_file = resolved
if current_file not in files:
files[current_file] = []
line_counts[current_file] = 0
@@ -736,14 +831,19 @@ class DiffService:
continue
full = "diff --git " + chunk
if len(full.encode("utf-8", errors="replace")) > MAX_DIFF_SIZE_BYTES:
- # 提取文件路径用于标记
- m = re.search(r"^\+\+\+ b/(.+)$", full, re.MULTILINE)
+ # 提取文件路径用于标记。路径可能被引号包裹(控制字符),
+ # 需用 _extract_diff_header_path 解码以与 numstat key 对齐。
+ m = re.search(r'^\+\+\+ (b/.*|".*")$', full, re.MULTILINE)
if m:
- large_files.add(m.group(1))
+ resolved = DiffService._extract_diff_header_path(m.group(1))
+ if resolved is not None:
+ large_files.add(resolved)
else:
- m2 = re.search(r"^--- a/(.+)$", full, re.MULTILINE)
- if m2 and m2.group(1) != "/dev/null":
- large_files.add(m2.group(1))
+ m2 = re.search(r'^--- (a/.*|".*")$', full, re.MULTILINE)
+ if m2:
+ resolved = DiffService._extract_diff_header_path(m2.group(1))
+ if resolved is not None:
+ large_files.add(resolved)
continue
kept.append(full)
return "".join(kept), large_files
@@ -751,10 +851,11 @@ class DiffService:
def _get_untracked_files(
self, project_dir: str, max_files: int = MAX_FILES
) -> dict[str, dict[str, Any]]:
- """获取未跟踪文件列表并生成合成 diff(全部为新增行)."""
- # core.quotepath=false 让 git 直接输出原始 UTF-8 文件名,
- # 而非八进制转义串(如 "aaa_design/Code\346\250\241..."),
- # 否则中文路径无法对应到磁盘真实路径,read_text 会失败、hunk 为空。
+ """获取未跟踪文件列表,仅记录文件名和状态."""
+ # core.quotepath=false 让 git 对非 ASCII 字节直接输出原始 UTF-8 文件名
+ # (而非八进制转义串),否则中文路径无法对应磁盘真实路径。但 ASCII 控制字符
+ # (如 TAB)无论该设置如何都会被加引号并 C 转义(如 "dir\tfile.txt"),
+ # 仍需 _unquote_git_path 解码才能对应磁盘真实文件。
output = self._run_git_command(
project_dir,
["-c", "core.quotepath=false", "ls-files", "--others", "--exclude-standard"],
@@ -769,40 +870,18 @@ class DiffService:
rel_path = rel_path.strip()
if not rel_path:
continue
+ rel_path = DiffService._unquote_git_path(rel_path)
abs_path = str(Path(project_dir) / rel_path)
- try:
- content = Path(abs_path).read_text(encoding="utf-8", errors="replace")
- except (OSError, ValueError):
- # 二进制文件或无法读取,只记录文件名不含 hunk
- content = None
-
- if content is not None:
- lines = content.splitlines()
- is_truncated = len(lines) > MAX_LINES_PER_FILE
- if is_truncated:
- lines = lines[:MAX_LINES_PER_FILE]
- hunks = [{
- "oldStart": 0,
- "oldLines": 0,
- "newStart": 1,
- "newLines": len(lines),
- "lines": [f"+{line}" for line in lines],
- }]
- lines_added = len(lines)
- else:
- hunks = []
- lines_added = 0
- is_truncated = False
files[abs_path] = {
"filePath": abs_path,
- "hunks": hunks,
+ "hunks": [],
"isNewFile": True,
- "isBinary": content is None,
+ "isBinary": False,
"isLargeFile": False,
- "isTruncated": is_truncated,
+ "isTruncated": False,
"isUntracked": True,
- "linesAdded": lines_added,
+ "linesAdded": 0,
"linesRemoved": 0,
"lastEditTime": None,
}
@@ -836,6 +915,7 @@ class DiffService:
return None
files: dict[str, dict[str, Any]] = {}
+ total_files_changed = 0
total_added = 0
total_removed = 0
@@ -862,6 +942,9 @@ class DiffService:
diff_output = self._run_git_command(repo_dir, ["diff", "HEAD"])
if numstat_output and diff_output:
per_file_stats = self._parse_git_numstat(numstat_output)
+ total_files_changed += len(per_file_stats)
+ total_added += sum(int(stats["added"]) for stats in per_file_stats.values())
+ total_removed += sum(int(stats["removed"]) for stats in per_file_stats.values())
filtered_output, large_files = self._split_large_file_diffs(diff_output)
all_hunks, truncated_files = self._parse_git_diff_hunks(filtered_output)
@@ -876,8 +959,6 @@ class DiffService:
hunks = all_hunks.get(rel_path, [])
lines_added = stats["added"]
lines_removed = stats["removed"]
- total_added += lines_added
- total_removed += lines_removed
files[abs_path] = {
"filePath": abs_path,
@@ -901,6 +982,7 @@ class DiffService:
file_info.setdefault("isLargeFile", False)
file_info.setdefault("isTruncated", False)
files[abs_path] = file_info
+ total_files_changed += 1
total_added += file_info["linesAdded"]
if not files:
@@ -908,7 +990,7 @@ class DiffService:
return {
"stats": {
- "filesChanged": len(files),
+ "filesChanged": total_files_changed,
"linesAdded": total_added,
"linesRemoved": total_removed,
},
diff --git a/tests/unit_tests/server/test_diff_service.py b/tests/unit_tests/server/test_diff_service.py
index 7c215adba9..155ccc54e9 100644
--- a/tests/unit_tests/server/test_diff_service.py
+++ b/tests/unit_tests/server/test_diff_service.py
@@ -32,8 +32,64 @@ def test_git_diff_from_subdir_includes_repo_root_untracked_files(tmp_path):
assert str(tracked) in diff["files"]
assert str(untracked) in diff["files"]
assert diff["files"][str(untracked)]["isUntracked"] is True
- assert diff["files"][str(untracked)]["linesAdded"] == 2
+ assert diff["files"][str(untracked)]["linesAdded"] == 0
+ assert diff["files"][str(untracked)]["hunks"] == []
assert diff["stats"]["filesChanged"] == 2
+ assert diff["stats"]["linesAdded"] == 1
+ assert diff["stats"]["linesRemoved"] == 1
+
+
+def test_git_diff_stats_include_tracked_files_beyond_detail_cap(tmp_path):
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "Test User")
+
+ for i in range(60):
+ file_path = repo / f"file-{i:02d}.txt"
+ file_path.write_text("before\n", encoding="utf-8")
+
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-m", "initial")
+
+ for i in range(60):
+ file_path = repo / f"file-{i:02d}.txt"
+ file_path.write_text("after\n", encoding="utf-8")
+
+ diff = DiffService().get_git_diff(str(repo))
+
+ assert diff is not None
+ assert len(diff["files"]) == 50
+ assert diff["stats"]["filesChanged"] == 60
+ assert diff["stats"]["linesAdded"] == 60
+ assert diff["stats"]["linesRemoved"] == 60
+
+
+def test_git_diff_preserves_tabs_in_file_paths(tmp_path):
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "Test User")
+ _git(repo, "config", "core.quotepath", "false")
+
+ tab_name = "dir\tfile.txt"
+ tab_file = repo / tab_name
+ tab_file.write_text("before\nbefore2\nbefore3\n", encoding="utf-8")
+ _git(repo, "add", "--", tab_name)
+ _git(repo, "commit", "-m", "initial")
+
+ tab_file.write_text("after\nafter2\n", encoding="utf-8")
+
+ diff = DiffService().get_git_diff(str(repo))
+
+ assert diff is not None
+ tab_abs = str(tab_file)
+ assert tab_abs in diff["files"]
+ file_info = diff["files"][tab_abs]
+ assert file_info["linesAdded"] == 2
+ assert file_info["linesRemoved"] == 3
def test_git_diff_staged_rename_with_modification_keeps_hunks(tmp_path):