@lyrumu/pi-diff 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE.md +8 -0
- package/README.md +120 -2
- package/README.zh-CN.md +121 -0
- package/THIRD_PARTY_LICENSES.md +33 -0
- package/index.ts +153 -0
- package/package.json +45 -4
- package/src/diff-engine.ts +218 -0
- package/src/git.ts +378 -0
- package/src/language.ts +91 -0
- package/src/preferences.ts +47 -0
- package/src/snapshot.ts +114 -0
- package/src/store.ts +77 -0
- package/src/tracker.ts +508 -0
- package/src/tui/diff-screen.ts +310 -0
- package/src/tui/file-tree-utils.ts +174 -0
- package/src/tui/file-tree.ts +99 -0
- package/src/tui/patch-diff.ts +243 -0
- package/src/tui/scopes.ts +20 -0
- package/src/tui/text.ts +15 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { formatPatch, structuredPatch } from "diff";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Patch primitives — ported from opencode `packages/core/src/vcs/patch.ts`
|
|
5
|
+
* (MIT, see NOTICE.md). Kept line-for-line where possible; TypeScript guards
|
|
6
|
+
* and the hunk-aware countPatch correction are documented in PLAN.md.
|
|
7
|
+
* The `diff` package provides structuredPatch/formatPatch, exactly as upstream.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
// Effectively "full file" context; adapters use it when no context is requested.
|
|
11
|
+
export const PATCH_CONTEXT_LINES = 2_147_483_647;
|
|
12
|
+
export const MAX_PATCH_BYTES = 10_000_000;
|
|
13
|
+
export const MAX_TOTAL_PATCH_BYTES = 10_000_000;
|
|
14
|
+
|
|
15
|
+
export interface Patch {
|
|
16
|
+
readonly text: string;
|
|
17
|
+
readonly truncated: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const emptyPatch = (file: string) =>
|
|
21
|
+
formatPatch(structuredPatch(file, file, "", "", "", "", { context: 0 }));
|
|
22
|
+
|
|
23
|
+
export const addPatch = (file: string, content: string) =>
|
|
24
|
+
formatPatch(structuredPatch(file, file, "", content, "", "", { context: 0 }));
|
|
25
|
+
|
|
26
|
+
export const deletePatch = (file: string, content: string) =>
|
|
27
|
+
formatPatch(structuredPatch(file, file, content, "", "", "", { context: 0 }));
|
|
28
|
+
|
|
29
|
+
/** Count changed lines in a unified diff, ignoring `+++`/`---` file headers. */
|
|
30
|
+
export const countPatch = (patch: string) => {
|
|
31
|
+
let additions = 0;
|
|
32
|
+
let deletions = 0;
|
|
33
|
+
let remaining = 0;
|
|
34
|
+
for (const line of patch.split("\n")) {
|
|
35
|
+
const hunk = line.startsWith("@@ ") ? /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line) : null;
|
|
36
|
+
if (hunk) remaining = Number(hunk[1] ?? 1) + Number(hunk[2] ?? 1);
|
|
37
|
+
else if (remaining > 0) {
|
|
38
|
+
if (line.startsWith("+")) { additions++; remaining--; }
|
|
39
|
+
else if (line.startsWith("-")) { deletions++; remaining--; }
|
|
40
|
+
else if (line.startsWith(" ")) remaining -= 2;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return { additions, deletions };
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const parseQuotedPath = (value: string) => {
|
|
47
|
+
let out = "";
|
|
48
|
+
for (let idx = 1; idx < value.length; idx++) {
|
|
49
|
+
const char = value[idx]!;
|
|
50
|
+
if (char === '"') return { value: out, end: idx + 1 };
|
|
51
|
+
if (char !== "\\") {
|
|
52
|
+
out += char;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const next = value[++idx];
|
|
57
|
+
if (next === "t") out += "\t";
|
|
58
|
+
else if (next === "n") out += "\n";
|
|
59
|
+
else if (next === "r") out += "\r";
|
|
60
|
+
else if (next === '"' || next === "\\") out += next;
|
|
61
|
+
else out = next ?? "";
|
|
62
|
+
}
|
|
63
|
+
return undefined;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const parsePathToken = (value: string) => {
|
|
67
|
+
if (!value.startsWith('"')) return value.split("\t")[0] ?? value;
|
|
68
|
+
return parseQuotedPath(value)?.value ?? value;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const fileFromDiffPath = (value: string | undefined) => {
|
|
72
|
+
if (!value || value === "/dev/null") return undefined;
|
|
73
|
+
const file = parsePathToken(value);
|
|
74
|
+
if (file.startsWith("a/") || file.startsWith("b/")) return file.slice(2);
|
|
75
|
+
return file;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const fileFromGitHeader = (header: string) => {
|
|
79
|
+
if (header.startsWith('"')) {
|
|
80
|
+
const first = parseQuotedPath(header);
|
|
81
|
+
const second = first ? header.slice(first.end).trimStart() : undefined;
|
|
82
|
+
if (!second) return undefined;
|
|
83
|
+
if (!second.startsWith('"')) return fileFromDiffPath(second);
|
|
84
|
+
const parsed = parseQuotedPath(second);
|
|
85
|
+
return fileFromDiffPath(parsed?.value);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const separator = header.indexOf(" b/");
|
|
89
|
+
if (separator === -1) return undefined;
|
|
90
|
+
return fileFromDiffPath(header.slice(separator + 1));
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
export const fileFromPatchChunk = (chunk: string) => {
|
|
94
|
+
const next = /^\+\+\+ (.+)$/m.exec(chunk)?.[1];
|
|
95
|
+
const before = /^--- (.+)$/m.exec(chunk)?.[1];
|
|
96
|
+
const file = fileFromDiffPath(next) ?? fileFromDiffPath(before);
|
|
97
|
+
if (file) return file;
|
|
98
|
+
|
|
99
|
+
const header = /^diff --git (.+)$/m.exec(chunk)?.[1];
|
|
100
|
+
return fileFromGitHeader(header ?? "");
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/** Split `git diff`-format output into per-file chunks, dropping a trailing partial chunk when truncated. */
|
|
104
|
+
export const splitGitPatch = (patch: Patch) => {
|
|
105
|
+
const starts = [...patch.text.matchAll(/(?:^|\n)diff --git /g)].map((match) =>
|
|
106
|
+
match[0].startsWith("\n") ? match.index + 1 : match.index,
|
|
107
|
+
);
|
|
108
|
+
const chunks = starts.map((start, index) =>
|
|
109
|
+
patch.text.slice(start, starts[index + 1] ?? patch.text.length),
|
|
110
|
+
);
|
|
111
|
+
if (!patch.truncated) return chunks;
|
|
112
|
+
return chunks.slice(0, -1);
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/** Map per-file chunks by the file they touch, concatenating chunks for the same file. */
|
|
116
|
+
export const chunksByFile = (patch: Patch, fallback: (index: number) => string | undefined) =>
|
|
117
|
+
splitGitPatch(patch).reduce((acc, chunk, index) => {
|
|
118
|
+
const file = fileFromPatchChunk(chunk) ?? fallback(index);
|
|
119
|
+
if (!file) return acc;
|
|
120
|
+
acc.set(file, (acc.get(file) ?? "") + chunk);
|
|
121
|
+
return acc;
|
|
122
|
+
}, new Map<string, string>());
|
|
123
|
+
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
// Session-diff view layer (pi-diff specific; opencode computes this via its
|
|
126
|
+
// git snapshot trees — see PLAN.md deviations D3/D4).
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
/** Status of a changed file, mirroring opencode `FileStatus["status"]`. */
|
|
130
|
+
export type FileStatus = "added" | "modified" | "deleted";
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* A single changed-file patch for one scope (turn / session / git). The
|
|
134
|
+
* unified `patch` text is the core primitive (opencode-aligned); hashes are
|
|
135
|
+
* content-addressed cache hints for the session-cumulative recompute.
|
|
136
|
+
*/
|
|
137
|
+
export interface FilePatch {
|
|
138
|
+
/** Project-relative posix path. */
|
|
139
|
+
file: string;
|
|
140
|
+
status: FileStatus;
|
|
141
|
+
/** Unified diff text; empty for binary / capped files. */
|
|
142
|
+
patch: string;
|
|
143
|
+
additions: number;
|
|
144
|
+
deletions: number;
|
|
145
|
+
/** Old side is unknown (no-git bash-detected change). */
|
|
146
|
+
baselineUnknown?: boolean;
|
|
147
|
+
/** Content is binary; UI shows "binary file changed". */
|
|
148
|
+
binary?: boolean;
|
|
149
|
+
/** Patch exceeded the byte cap and was emptied. */
|
|
150
|
+
tooLarge?: boolean;
|
|
151
|
+
/** A file side could not be read or captured; never treat it as absent. */
|
|
152
|
+
unavailable?: boolean;
|
|
153
|
+
/** Only the latest turn patch is available for a cumulative view. */
|
|
154
|
+
cumulativeFallback?: boolean;
|
|
155
|
+
/** sha256 of old-side bytes; null = file did not exist on the old side. */
|
|
156
|
+
oldHash?: string | null;
|
|
157
|
+
/** sha256 of new-side bytes; null = file does not exist on the new side. */
|
|
158
|
+
newHash?: string | null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Detect binary content the way git does: a NUL byte anywhere in the buffer. */
|
|
162
|
+
export function isBinary(content: Buffer): boolean {
|
|
163
|
+
return content.includes(0);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Build a full-file-context FilePatch from old/new content buffers.
|
|
168
|
+
* Applies opencode's degradation rules: binary → empty patch + `binary`;
|
|
169
|
+
* patch larger than MAX_PATCH_BYTES → emptyPatch + `tooLarge`.
|
|
170
|
+
*/
|
|
171
|
+
export function makeFilePatch(
|
|
172
|
+
file: string,
|
|
173
|
+
oldContent: Buffer | null,
|
|
174
|
+
newContent: Buffer | null,
|
|
175
|
+
opts: { oldHash?: string | null; newHash?: string | null; baselineUnknown?: boolean } = {},
|
|
176
|
+
): FilePatch {
|
|
177
|
+
const status: FileStatus =
|
|
178
|
+
oldContent === null ? "added" : newContent === null ? "deleted" : "modified";
|
|
179
|
+
const base: FilePatch = {
|
|
180
|
+
file,
|
|
181
|
+
status,
|
|
182
|
+
patch: "",
|
|
183
|
+
additions: 0,
|
|
184
|
+
deletions: 0,
|
|
185
|
+
oldHash: opts.oldHash ?? null,
|
|
186
|
+
newHash: opts.newHash ?? null,
|
|
187
|
+
};
|
|
188
|
+
if (opts.baselineUnknown) base.baselineUnknown = true;
|
|
189
|
+
|
|
190
|
+
const binary = (oldContent !== null && isBinary(oldContent)) || (newContent !== null && isBinary(newContent));
|
|
191
|
+
if (binary) {
|
|
192
|
+
base.binary = true;
|
|
193
|
+
return base;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Skip patch computation for oversized inputs; the patch could not fit the cap anyway.
|
|
197
|
+
const oldLen = oldContent?.byteLength ?? 0;
|
|
198
|
+
const newLen = newContent?.byteLength ?? 0;
|
|
199
|
+
if (Math.max(oldLen, newLen) > MAX_PATCH_BYTES) {
|
|
200
|
+
base.tooLarge = true;
|
|
201
|
+
return base;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const oldStr = oldContent?.toString("utf8") ?? "";
|
|
205
|
+
const newStr = newContent?.toString("utf8") ?? "";
|
|
206
|
+
const text = formatPatch(structuredPatch(file, file, oldStr, newStr, "", "", {
|
|
207
|
+
context: PATCH_CONTEXT_LINES,
|
|
208
|
+
}));
|
|
209
|
+
if (Buffer.byteLength(text, "utf8") > MAX_PATCH_BYTES) {
|
|
210
|
+
base.tooLarge = true;
|
|
211
|
+
return base;
|
|
212
|
+
}
|
|
213
|
+
base.patch = text;
|
|
214
|
+
const counts = countPatch(text);
|
|
215
|
+
base.additions = counts.additions;
|
|
216
|
+
base.deletions = counts.deletions;
|
|
217
|
+
return base;
|
|
218
|
+
}
|
package/src/git.ts
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import {
|
|
4
|
+
chunksByFile,
|
|
5
|
+
emptyPatch,
|
|
6
|
+
MAX_PATCH_BYTES,
|
|
7
|
+
MAX_TOTAL_PATCH_BYTES,
|
|
8
|
+
type FilePatch,
|
|
9
|
+
type FileStatus,
|
|
10
|
+
type Patch,
|
|
11
|
+
} from "./diff-engine.ts";
|
|
12
|
+
|
|
13
|
+
const exec = promisify(execFile);
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Read-only git CLI wrapper. Never writes to the repository.
|
|
17
|
+
*
|
|
18
|
+
* Ports opencode's branch/committed/working pipeline with the Effect runtime
|
|
19
|
+
* replaced by async functions. Untracked files use its read-only per-file
|
|
20
|
+
* fallback instead of the temporary-index optimization (see PLAN.md).
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const BASE_ARGS = [
|
|
24
|
+
"--no-optional-locks",
|
|
25
|
+
"-c", "core.autocrlf=false",
|
|
26
|
+
"-c", "core.fsmonitor=false",
|
|
27
|
+
"-c", "core.longpaths=true",
|
|
28
|
+
"-c", "core.symlinks=true",
|
|
29
|
+
"-c", "core.quotepath=false",
|
|
30
|
+
] as const;
|
|
31
|
+
|
|
32
|
+
export const VCS_DIFF_CONTEXT_LINES = 12;
|
|
33
|
+
export type GitDiffMode = "branch" | "committed" | "working" | "unstaged";
|
|
34
|
+
export interface GitDiffOptions {
|
|
35
|
+
readonly context?: number;
|
|
36
|
+
readonly base?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface Item extends StatusItem {
|
|
40
|
+
readonly status: FileStatus;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface Stat {
|
|
44
|
+
readonly file: string;
|
|
45
|
+
readonly additions: number;
|
|
46
|
+
readonly deletions: number;
|
|
47
|
+
readonly binary: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Drain capped output without retaining more than the byte budget. */
|
|
51
|
+
function run(cwd: string, args: readonly string[], maxOutputBytes = 64 * 1024 * 1024) {
|
|
52
|
+
return new Promise<{ text: string; truncated: boolean; exitCode: number }>((resolve) => {
|
|
53
|
+
const child = spawn("git", [...BASE_ARGS, ...args], { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
54
|
+
const chunks: Buffer[] = [];
|
|
55
|
+
let size = 0;
|
|
56
|
+
let truncated = false;
|
|
57
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
58
|
+
const available = Math.max(0, maxOutputBytes - size);
|
|
59
|
+
if (chunk.length > available) truncated = true;
|
|
60
|
+
if (available > 0) {
|
|
61
|
+
const kept = chunk.subarray(0, available);
|
|
62
|
+
chunks.push(kept);
|
|
63
|
+
size += kept.length;
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
child.stderr.resume();
|
|
67
|
+
child.on("error", () => resolve({ text: "", truncated: false, exitCode: 1 }));
|
|
68
|
+
child.on("close", (code) => resolve({ text: Buffer.concat(chunks).toString("utf8"), truncated, exitCode: code ?? 1 }));
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const kind = (code: string): FileStatus => {
|
|
73
|
+
if (code === "??") return "added";
|
|
74
|
+
if (code.includes("U")) return "modified";
|
|
75
|
+
if (code.includes("A") && !code.includes("D")) return "added";
|
|
76
|
+
if (code.includes("D") && !code.includes("A")) return "deleted";
|
|
77
|
+
return "modified";
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const nuls = (text: string) => text.split("\0").filter(Boolean);
|
|
81
|
+
|
|
82
|
+
const numstat = (text: string): Stat[] =>
|
|
83
|
+
nuls(text).flatMap((item) => {
|
|
84
|
+
const a = item.indexOf("\t");
|
|
85
|
+
const b = item.indexOf("\t", a + 1);
|
|
86
|
+
if (a === -1 || b === -1) return [];
|
|
87
|
+
const file = item.slice(b + 1);
|
|
88
|
+
if (!file) return [];
|
|
89
|
+
const adds = item.slice(0, a);
|
|
90
|
+
const dels = item.slice(a + 1, b);
|
|
91
|
+
const additions = adds === "-" ? 0 : Number.parseInt(adds || "0", 10);
|
|
92
|
+
const deletions = dels === "-" ? 0 : Number.parseInt(dels || "0", 10);
|
|
93
|
+
return [{
|
|
94
|
+
file,
|
|
95
|
+
additions: Number.isFinite(additions) ? additions : 0,
|
|
96
|
+
deletions: Number.isFinite(deletions) ? deletions : 0,
|
|
97
|
+
binary: adds === "-" || dels === "-",
|
|
98
|
+
}];
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
async function lines(cwd: string, args: string[]) {
|
|
102
|
+
return (await run(cwd, args)).text.split(/\r?\n/).map((item) => item.trim()).filter(Boolean);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function defaultBranch(cwd: string): Promise<{ name: string; ref: string } | undefined> {
|
|
106
|
+
const remotes = await lines(cwd, ["remote"]);
|
|
107
|
+
const remote = remotes.includes("origin") ? "origin"
|
|
108
|
+
: remotes.length === 1 ? remotes[0]
|
|
109
|
+
: remotes.includes("upstream") ? "upstream" : remotes[0];
|
|
110
|
+
if (remote) {
|
|
111
|
+
const head = await run(cwd, ["symbolic-ref", `refs/remotes/${remote}/HEAD`]);
|
|
112
|
+
if (head.exitCode === 0) {
|
|
113
|
+
const ref = head.text.trim().replace(/^refs\/remotes\//, "");
|
|
114
|
+
const name = ref.startsWith(`${remote}/`) ? ref.slice(`${remote}/`.length) : "";
|
|
115
|
+
if (name) return { name, ref };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const list = await lines(cwd, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]);
|
|
119
|
+
const configured = (await run(cwd, ["config", "init.defaultBranch"])).text.trim();
|
|
120
|
+
if (configured && list.includes(configured)) return { name: configured, ref: configured };
|
|
121
|
+
if (list.includes("main")) return { name: "main", ref: "main" };
|
|
122
|
+
if (list.includes("master")) return { name: "master", ref: "master" };
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function mergeBase(cwd: string, base: string) {
|
|
127
|
+
const resolved = await run(cwd, ["rev-parse", "--verify", "--end-of-options", `${base}^{commit}`]);
|
|
128
|
+
if (resolved.exitCode !== 0) return undefined;
|
|
129
|
+
const result = await run(cwd, ["merge-base", resolved.text.trim(), "HEAD"]);
|
|
130
|
+
return result.exitCode === 0 ? result.text.trim() || undefined : undefined;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function nativePatch(root: string, ref: string | undefined, item: Item, context: number, target?: "HEAD"): Promise<Patch> {
|
|
134
|
+
const result = await run(root, [
|
|
135
|
+
"--literal-pathspecs", "diff",
|
|
136
|
+
...(item.code === "??" || ref === undefined ? ["--no-index"] : []),
|
|
137
|
+
"--patch", "--no-ext-diff", "--no-renames", `--unified=${context}`,
|
|
138
|
+
...(item.code === "??" || ref === undefined ? ["--", "/dev/null", item.file] : [...(ref ? [ref] : []), ...(target ? [target] : []), "--", item.file]),
|
|
139
|
+
], MAX_PATCH_BYTES);
|
|
140
|
+
// --no-index reports differences with exit code 1, not a command failure.
|
|
141
|
+
if (result.exitCode !== 0 && !(result.exitCode === 1 && (item.code === "??" || ref === undefined))) {
|
|
142
|
+
throw new Error(`Unable to read Git patch for ${item.file}`);
|
|
143
|
+
}
|
|
144
|
+
return { text: result.truncated ? "" : result.text, truncated: result.truncated };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function statUntracked(root: string, file: string): Promise<Stat | undefined> {
|
|
148
|
+
const result = await run(root, ["diff", "--no-index", "--numstat", "--", "/dev/null", file], 4096);
|
|
149
|
+
if (result.truncated) return undefined;
|
|
150
|
+
return numstat(result.text)[0];
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function files(
|
|
154
|
+
root: string,
|
|
155
|
+
ref: string | undefined,
|
|
156
|
+
list: Item[],
|
|
157
|
+
stats: Map<string, Stat>,
|
|
158
|
+
batch: { patches: Map<string, string>; capped: boolean },
|
|
159
|
+
context: number,
|
|
160
|
+
target?: "HEAD",
|
|
161
|
+
): Promise<FilePatch[]> {
|
|
162
|
+
const next: FilePatch[] = [];
|
|
163
|
+
let total = 0;
|
|
164
|
+
let capped = false;
|
|
165
|
+
for (const item of list.sort((a, b) => a.file.localeCompare(b.file))) {
|
|
166
|
+
const stat = stats.get(item.file) ?? (!target && item.status === "added" ? await statUntracked(root, item.file) : undefined);
|
|
167
|
+
let patch = emptyPatch(item.file);
|
|
168
|
+
let tooLarge = capped;
|
|
169
|
+
if (!capped) {
|
|
170
|
+
const batched = batch.patches.get(item.file);
|
|
171
|
+
if (batched !== undefined) patch = batched;
|
|
172
|
+
else if (item.code !== "??" && batch.capped) tooLarge = true;
|
|
173
|
+
else {
|
|
174
|
+
const result = await nativePatch(root, ref, item, context, target);
|
|
175
|
+
tooLarge = result.truncated;
|
|
176
|
+
if (!result.truncated && result.text) patch = result.text;
|
|
177
|
+
}
|
|
178
|
+
if (Buffer.byteLength(patch) > MAX_PATCH_BYTES) tooLarge = true;
|
|
179
|
+
if (tooLarge) patch = emptyPatch(item.file);
|
|
180
|
+
if (total + Buffer.byteLength(patch) > MAX_TOTAL_PATCH_BYTES) {
|
|
181
|
+
capped = true;
|
|
182
|
+
tooLarge = true;
|
|
183
|
+
patch = emptyPatch(item.file);
|
|
184
|
+
}
|
|
185
|
+
if (!capped) {
|
|
186
|
+
total += Buffer.byteLength(patch);
|
|
187
|
+
capped = total >= MAX_TOTAL_PATCH_BYTES;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const binary = stat?.binary || /^Binary files .+ differ$/m.test(patch);
|
|
191
|
+
next.push({
|
|
192
|
+
file: item.file,
|
|
193
|
+
status: item.status,
|
|
194
|
+
patch: binary ? "" : patch,
|
|
195
|
+
additions: stat?.additions ?? 0,
|
|
196
|
+
deletions: stat?.deletions ?? 0,
|
|
197
|
+
...(binary ? { binary: true } : {}),
|
|
198
|
+
...(tooLarge ? { tooLarge: true } : {}),
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return next;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export interface StatusItem {
|
|
205
|
+
/** Project-relative posix path. */
|
|
206
|
+
file: string;
|
|
207
|
+
/** Two-letter porcelain code, e.g. " M", "??", "M ". */
|
|
208
|
+
code: string;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export const Git = {
|
|
212
|
+
/** working: HEAD → disk; committed: merge base → HEAD; branch: merge base → disk. */
|
|
213
|
+
async diff(cwd: string, mode: GitDiffMode, options: GitDiffOptions = {}): Promise<FilePatch[]> {
|
|
214
|
+
const context = options.context ?? VCS_DIFF_CONTEXT_LINES;
|
|
215
|
+
if (!Number.isSafeInteger(context) || context < 0) throw new Error("Invalid Git diff context");
|
|
216
|
+
if (!await Git.isAvailable(cwd)) return [];
|
|
217
|
+
const rootResult = await run(cwd, ["rev-parse", "--show-toplevel"]);
|
|
218
|
+
if (rootResult.exitCode !== 0) throw new Error("Unable to find Git worktree");
|
|
219
|
+
const root = rootResult.text.replace(/\r?\n$/, "");
|
|
220
|
+
const hasHead = await Git.headCommit(cwd) !== null;
|
|
221
|
+
if (!hasHead && mode === "committed") return [];
|
|
222
|
+
// Empty ref compares disk against the index; undefined means an unborn baseline.
|
|
223
|
+
let ref: string | undefined = mode === "unstaged" ? "" : hasHead ? "HEAD" : undefined;
|
|
224
|
+
const target = mode === "committed" ? "HEAD" : undefined;
|
|
225
|
+
if (hasHead && mode !== "working" && mode !== "unstaged") {
|
|
226
|
+
const base = options.base ?? (await defaultBranch(cwd))?.ref;
|
|
227
|
+
ref = base ? await mergeBase(cwd, base) : undefined;
|
|
228
|
+
if (!ref) throw new Error(base ? `No merge base available for ${base}` : "No review base available");
|
|
229
|
+
}
|
|
230
|
+
const extraResult = target ? { text: "", exitCode: 0, truncated: false }
|
|
231
|
+
: await run(cwd, ["status", "--porcelain=v1", "--untracked-files=all", "--no-renames", "-z", "--", "."]);
|
|
232
|
+
if (extraResult.exitCode !== 0 || extraResult.truncated) throw new Error("Unable to list Git changes");
|
|
233
|
+
const extra: Item[] = Git.parseStatus(extraResult.text).map((item) => ({ ...item, status: kind(item.code) }));
|
|
234
|
+
if (ref === undefined) return files(root, ref, extra, new Map(), { patches: new Map(), capped: false }, context);
|
|
235
|
+
const args = ["diff", "--no-ext-diff", "--no-renames"];
|
|
236
|
+
const revisions = [...(ref ? [ref] : []), ...(target ? [target] : []), "--", "."];
|
|
237
|
+
const [names, counts] = await Promise.all([
|
|
238
|
+
run(cwd, [...args, "--name-status", "-z", ...revisions]),
|
|
239
|
+
run(cwd, [...args, "--numstat", "-z", ...revisions]),
|
|
240
|
+
]);
|
|
241
|
+
if (names.exitCode !== 0 || names.truncated || counts.exitCode !== 0 || counts.truncated) {
|
|
242
|
+
throw new Error("Unable to list Git changes");
|
|
243
|
+
}
|
|
244
|
+
const tokens = nuls(names.text);
|
|
245
|
+
const list: Item[] = tokens.flatMap((code, idx) => {
|
|
246
|
+
const file = tokens[idx + 1];
|
|
247
|
+
return idx % 2 === 0 && file ? [{ file, code, status: kind(code) }] : [];
|
|
248
|
+
});
|
|
249
|
+
const result = list.length === 0 ? { text: "", truncated: false, exitCode: 0 }
|
|
250
|
+
: await run(cwd, [...args, "--patch", `--unified=${context}`, ...revisions], MAX_TOTAL_PATCH_BYTES);
|
|
251
|
+
if (result.exitCode !== 0) throw new Error("Unable to read Git changes");
|
|
252
|
+
const merged = new Map(list.map((item) => [item.file, item]));
|
|
253
|
+
for (const item of extra) if (item.code === "??" && !merged.has(item.file)) merged.set(item.file, item);
|
|
254
|
+
return files(root, ref, [...merged.values()], new Map(numstat(counts.text).map((stat) => [stat.file, stat])), {
|
|
255
|
+
patches: chunksByFile(result, (index) => list[index]?.file),
|
|
256
|
+
capped: result.truncated,
|
|
257
|
+
}, context, target);
|
|
258
|
+
},
|
|
259
|
+
|
|
260
|
+
async isAvailable(cwd: string): Promise<boolean> {
|
|
261
|
+
// `git rev-parse --is-inside-work-tree`
|
|
262
|
+
return exec("git", [...BASE_ARGS, "rev-parse", "--is-inside-work-tree"], { cwd })
|
|
263
|
+
.then((r) => r.stdout.trim() === "true")
|
|
264
|
+
.catch(() => false);
|
|
265
|
+
},
|
|
266
|
+
|
|
267
|
+
/** Current HEAD commit id, or null (e.g. unborn branch). */
|
|
268
|
+
async headCommit(cwd: string): Promise<string | null> {
|
|
269
|
+
try {
|
|
270
|
+
const r = await exec("git", [...BASE_ARGS, "rev-parse", "HEAD"], { cwd });
|
|
271
|
+
return r.stdout.trim() || null;
|
|
272
|
+
} catch {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
|
|
277
|
+
/** Root-relative directory prefix for porcelain and revision paths. */
|
|
278
|
+
async prefix(cwd: string): Promise<string> {
|
|
279
|
+
const result = await run(cwd, ["rev-parse", "--show-prefix"]);
|
|
280
|
+
if (result.exitCode !== 0) throw new Error("Unable to resolve Git directory prefix");
|
|
281
|
+
return result.text.replace(/\r?\n$/, "");
|
|
282
|
+
},
|
|
283
|
+
|
|
284
|
+
/** Changed tracked paths when a shell command also moves HEAD. */
|
|
285
|
+
async changedCommitFiles(cwd: string, from: string | null, to: string | null): Promise<string[]> {
|
|
286
|
+
if (from === to || (!from && !to)) return [];
|
|
287
|
+
if ([from, to].some((ref) => ref !== null && !/^[a-f0-9]{40,64}$/.test(ref))) return [];
|
|
288
|
+
const args = from && to
|
|
289
|
+
? ["diff", "--no-ext-diff", "--no-renames", "--name-only", "-z", from, to, "--", "."]
|
|
290
|
+
: ["ls-tree", "-r", "--name-only", "-z", (to ?? from)!, "--", "."];
|
|
291
|
+
const result = await run(cwd, args);
|
|
292
|
+
if (result.exitCode !== 0 || result.truncated) throw new Error("Unable to list committed file changes");
|
|
293
|
+
return nuls(result.text);
|
|
294
|
+
},
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Raw `git status --porcelain=v1 -z` output, used as an opaque workspace
|
|
298
|
+
* marker by Tracker.scanWorkspace (two markers are compared via
|
|
299
|
+
* parseStatus). Arguments align with opencode `VcsGit.statusNames`.
|
|
300
|
+
*/
|
|
301
|
+
async statusPorcelain(cwd: string): Promise<string> {
|
|
302
|
+
try {
|
|
303
|
+
const r = await exec(
|
|
304
|
+
"git",
|
|
305
|
+
[
|
|
306
|
+
...BASE_ARGS,
|
|
307
|
+
"status",
|
|
308
|
+
"--porcelain=v1",
|
|
309
|
+
"--untracked-files=all",
|
|
310
|
+
"--no-renames",
|
|
311
|
+
"-z",
|
|
312
|
+
"--",
|
|
313
|
+
".",
|
|
314
|
+
],
|
|
315
|
+
{ cwd, maxBuffer: 64 * 1024 * 1024 },
|
|
316
|
+
);
|
|
317
|
+
return r.stdout;
|
|
318
|
+
} catch {
|
|
319
|
+
return "";
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Parse porcelain `-z` output into items. With --no-renames every NUL-
|
|
325
|
+
* separated token is "XY <path>" (port of opencode's nuls().flatMap).
|
|
326
|
+
*/
|
|
327
|
+
parseStatus(raw: string): StatusItem[] {
|
|
328
|
+
return raw
|
|
329
|
+
.split("\0")
|
|
330
|
+
.flatMap((item) => {
|
|
331
|
+
const file = item.slice(3);
|
|
332
|
+
if (!file) return [];
|
|
333
|
+
const code = item.slice(0, 2);
|
|
334
|
+
return [{ file, code }];
|
|
335
|
+
});
|
|
336
|
+
},
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Parse a workspace signature into file -> "code:hash" entries. Returns an
|
|
340
|
+
* empty map for markers that are not valid signatures.
|
|
341
|
+
*/
|
|
342
|
+
parseWorkspaceSignature(marker: string): Map<string, string> {
|
|
343
|
+
let entries: [string, string, string][];
|
|
344
|
+
try {
|
|
345
|
+
const parsed: unknown = JSON.parse(marker);
|
|
346
|
+
const files = typeof parsed === "object" && parsed !== null && "files" in parsed ? parsed.files : parsed;
|
|
347
|
+
if (!Array.isArray(files)) return new Map();
|
|
348
|
+
entries = files as [string, string, string][];
|
|
349
|
+
} catch {
|
|
350
|
+
return new Map();
|
|
351
|
+
}
|
|
352
|
+
const map = new Map<string, string>();
|
|
353
|
+
for (const entry of entries) {
|
|
354
|
+
if (!Array.isArray(entry)) continue;
|
|
355
|
+
const [file, code, hash] = entry;
|
|
356
|
+
if (typeof file !== "string" || typeof code !== "string" || typeof hash !== "string") continue;
|
|
357
|
+
map.set(file, `${code}:${hash}`);
|
|
358
|
+
}
|
|
359
|
+
return map;
|
|
360
|
+
},
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* File content (raw bytes) at a revision, e.g. "HEAD" or a pinned commit.
|
|
364
|
+
* Returns null when the path did not exist at that revision or git failed.
|
|
365
|
+
*/
|
|
366
|
+
async showRevision(cwd: string, rev: string, path: string): Promise<Buffer | null> {
|
|
367
|
+
try {
|
|
368
|
+
const r = await exec("git", [...BASE_ARGS, "show", `${rev}:${path}`], {
|
|
369
|
+
cwd,
|
|
370
|
+
encoding: "buffer",
|
|
371
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
372
|
+
}) as unknown as { stdout: Buffer };
|
|
373
|
+
return r.stdout;
|
|
374
|
+
} catch {
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
},
|
|
378
|
+
} as const;
|
package/src/language.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
export type Language = "en" | "zh-CN";
|
|
2
|
+
export type LocalizedText = string | ((language: Language) => string);
|
|
3
|
+
|
|
4
|
+
export function localize(text: LocalizedText, language: Language): string {
|
|
5
|
+
return typeof text === "function" ? text(language) : text;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const en = {
|
|
9
|
+
lastTurn: "Last turn",
|
|
10
|
+
turn: (turn: number) => `Last turn · Turn ${turn}`,
|
|
11
|
+
session: "Session total",
|
|
12
|
+
unstaged: "Unstaged",
|
|
13
|
+
working: "Uncommitted",
|
|
14
|
+
branch: "All branch changes",
|
|
15
|
+
files: "Files",
|
|
16
|
+
fileCount: (count: number) => `${count} ${count === 1 ? "file" : "files"}`,
|
|
17
|
+
switchView: "[Switch view]",
|
|
18
|
+
showFiles: "[Show files]",
|
|
19
|
+
dragDivider: "↔ Drag to resize",
|
|
20
|
+
unifiedOnly: "[Unified only]",
|
|
21
|
+
fixedUnified: "Unified view (added/deleted file)",
|
|
22
|
+
unified: "Unified view",
|
|
23
|
+
split: "Split view",
|
|
24
|
+
wrap: "Auto wrap",
|
|
25
|
+
noFileToSwitch: "No file to switch views",
|
|
26
|
+
tooNarrow: "Diff pane too narrow; widen the terminal for split view",
|
|
27
|
+
noChanges: "No file changes",
|
|
28
|
+
unavailable: "File contents unavailable",
|
|
29
|
+
binary: "Binary file changed",
|
|
30
|
+
tooLarge: "Diff exceeds the 10 MB limit",
|
|
31
|
+
deletedUnknown: "File deleted; previous contents unknown",
|
|
32
|
+
noPatch: "No diff content available for this file",
|
|
33
|
+
noTextChanges: "No text changes (empty file or metadata-only change)",
|
|
34
|
+
baselineUnknown: "Previous contents unknown",
|
|
35
|
+
cumulativeFallback: "Showing last turn only; session total could not be fully restored",
|
|
36
|
+
noHistory: "No valid change records in this old session; past changes unavailable",
|
|
37
|
+
noTurns: "No turn records; only tasks after enabling the extension are recorded",
|
|
38
|
+
emptyTurn: "No file changes in this turn",
|
|
39
|
+
unavailableTotal: "No usable history; complete session total unavailable",
|
|
40
|
+
emptySession: "No cumulative changes in this session",
|
|
41
|
+
incompleteHistory: "History incomplete",
|
|
42
|
+
loading: "Loading changes…",
|
|
43
|
+
loadFailed: (error: string) => `Failed to load: ${error}`,
|
|
44
|
+
requiresTui: "pi-diff requires an interactive TUI",
|
|
45
|
+
error: (error: string) => `pi-diff: ${error}`,
|
|
46
|
+
footer: (fixed: boolean, focus: "tree" | "diff") => `l/L 中文 · [/] Focus: ${focus === "tree" ? "Files" : "Diff"} · Tab/Shift+Tab Scope · ${fixed ? "A/D Unified only" : "v/V Unified/Split"} · ↑↓/Wheel Scroll · j/k ${focus === "tree" ? "Files" : "Scroll"} · Esc/q Close`,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export const messages: Record<Language, typeof en> = {
|
|
50
|
+
en,
|
|
51
|
+
"zh-CN": {
|
|
52
|
+
lastTurn: "最近一轮",
|
|
53
|
+
turn: (turn) => `最近一轮 · 第 ${turn} 轮`,
|
|
54
|
+
session: "会话累计",
|
|
55
|
+
unstaged: "未暂存",
|
|
56
|
+
working: "未提交",
|
|
57
|
+
branch: "分支全部改动",
|
|
58
|
+
files: "文件",
|
|
59
|
+
fileCount: (count) => `${count} 个文件`,
|
|
60
|
+
switchView: "[切换视图]",
|
|
61
|
+
showFiles: "[展开文件树]",
|
|
62
|
+
dragDivider: "↔ 拖动调整宽度",
|
|
63
|
+
unifiedOnly: "[仅合并视图]",
|
|
64
|
+
fixedUnified: "合并视图(新增/删除文件)",
|
|
65
|
+
unified: "合并视图",
|
|
66
|
+
split: "拆分视图",
|
|
67
|
+
wrap: "自动换行",
|
|
68
|
+
noFileToSwitch: "没有可切换的文件",
|
|
69
|
+
tooNarrow: "右侧宽度不足,请拉宽终端后切换拆分视图",
|
|
70
|
+
noChanges: "没有文件改动",
|
|
71
|
+
unavailable: "文件内容不可用",
|
|
72
|
+
binary: "二进制文件已改变",
|
|
73
|
+
tooLarge: "差异超过 10MB 上限",
|
|
74
|
+
deletedUnknown: "文件已删除;修改前内容未知",
|
|
75
|
+
noPatch: "此文件没有可用的差异内容",
|
|
76
|
+
noTextChanges: "没有文本变化(空文件或仅元数据变化)",
|
|
77
|
+
baselineUnknown: "修改前内容未知",
|
|
78
|
+
cumulativeFallback: "仅显示最后一轮,累计无法完整恢复",
|
|
79
|
+
noHistory: "旧会话没有有效的改动记录,无法展示当时变化",
|
|
80
|
+
noTurns: "没有轮次记录;仅记录插件启用后的任务",
|
|
81
|
+
emptyTurn: "本轮没有文件改动",
|
|
82
|
+
unavailableTotal: "没有可用的历史改动,无法展示完整累计",
|
|
83
|
+
emptySession: "当前会话没有累计改动",
|
|
84
|
+
incompleteHistory: "历史记录不完整",
|
|
85
|
+
loading: "正在加载改动…",
|
|
86
|
+
loadFailed: (error) => `加载失败:${error}`,
|
|
87
|
+
requiresTui: "pi-diff 需要在交互式 TUI 中使用",
|
|
88
|
+
error: (error) => `pi-diff:${error}`,
|
|
89
|
+
footer: (fixed, focus) => `l/L English · [/] 焦点:${focus === "tree" ? "文件树" : "内容"} · Tab/Shift+Tab 范围 · ${fixed ? "A/D 仅合并" : "v/V 合并/拆分"} · ↑↓/滚轮 滚动 · j/k ${focus === "tree" ? "文件" : "滚动"} · Esc/q 关闭`,
|
|
90
|
+
},
|
|
91
|
+
};
|