mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-03 23:37:53 +01:00
* fix(retro): keep retro history in the state root, shared across worktrees (#3749) /retro saved snapshots under .context/retros inside the working tree, so a run in a linked worktree saw none of the main checkout's history, reported "First retro recorded", and wrote a snapshot that git worktree remove deletes. gstack-retro-metrics --history [--next <date>] now resolves the history directory as <state root>/projects/<slug>/retros (the slug is keyed on the git common dir, so every worktree shares it), moves any legacy .context/retros from this worktree and the main checkout into it, lists prior snapshots and prints the next snapshot path. Step 12/13 and the gbrain prior-retros query use it. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(gate-diff): read a bare base as origin/<base> in gate-diff and diff-scope (#3650) gstack-gate-diff and gstack-diff-scope resolved a bare base such as main to the local branch whenever it shared history with HEAD. A local main that is behind origin/main (a linked worktree, or a Capy clone, where local main never moves) then set the merge base, so /ship's gate scan and specialist scope also read commits already upstream. Both now prefer origin/<base> when it resolves, the base /ship fetches and merges against. Fixes #3650 Co-authored-by: exGeni <135786749+exGeni@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(retro): make history migration safe against symlinks and concurrent runs (#3749 review) Review pass 1 findings: a .context/retros that resolves outside its worktree (or to the shared history itself) is left alone, so migration can no longer delete the history it points at; moves are no-clobber with retry; a copy identical to any same-date snapshot collapses; RETRO_FILE is reserved as {} so overlapping runs in two worktrees never share a path; --next must be a YYYY-MM-DD date; a missing option value no longer loops forever. Step 12 names RETRO_HISTORY_ERROR instead of reading it as a stale helper. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * docs(changelog): fragment for the #3749 retro history fix Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: pre-landing review fixes (diff-scope reads slash-named bases through origin too) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(retro): trim Step 12/13 prose back under the parity skeleton cap Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: Step 11 review fixes (a fork branch, a colliding tag or another remote never replaces the base) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(retro): keep today="<today>" in Step 12 so the judge excerpt keeps both date inputs Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * docs(changelog): describe the fork, tag and remote guards (#3650) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(retro): compare #3749 history paths with forward slashes so the Windows shard passes Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(review): review-plan and gate-diff plan the same with a stale local main or a shadowing tag (GST-883, failing first) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(review): gate-diff and review-plan resolve a branch base to origin/<base> by full ref name; review-plan scans the merge base its own diff used (GST-883) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * docs(changelog): GST-883 fragment Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(review-risk): hostile-input time bounds for every risk pattern; the R51 rm and rmSync rules fail (GST-898) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(review-risk): the R51 rm and rmSync rules run in linear time (GST-898) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(review-packets-removed): repin lib/review-risk.ts on the GST-898 verdict-identity replay Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(review-risk): padding cannot push recursive: true out of the rmSync window; repin on the GST-898 no-loss replay Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * docs(changelog): GST-898 fragment wording Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(review): planner misreads: SVG chart as runtime, session data as auth, bare base in diff-scope and receipt depth (GST-911, GST-884, failing first) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(review): a drawing-only SVG is data and a scripted one is security; session data files are not auth; diff-scope and the receipt depth read origin/<base> by full ref name (GST-911, GST-884) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(review): the SVG drawing check refuses CSS escapes and reads zero-padded character references; the security class reads a file's changed SVG lines joined (GST-911 review pass 1) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(review): a stray quote cannot hide an external href in a drawing SVG (GST-911 review pass 2, failing first) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(review): the SVG drawing check reads every name= without consuming its value, so a stray quote cannot hide an external href (GST-911 review pass 2) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(review): CSS in a drawing SVG holds only declarations and url(#id): image-set(), image(), element() keep it code (GST-911 Step 11, failing first) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(review): a drawing SVG's CSS holds declarations only, no @ rule and no function but url(#id), which closes image-set(), image(), element() and every other CSS load (GST-911 Step 11) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(review): a style element's CSS is read past comments and CDATA, unclosed style tags are refused in linear time, and every drawing verdict holds at 1 MB and 8 MB (GST-911, failing first) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(review): walk a style element's CSS with indexOf, dropping comments and reading CDATA, so no hidden </style> ends it early and unclosed style tags refuse in linear time (GST-911) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * docs(review-policy): the linear-time claim covers R51's rm and rmSync rules (GST-898) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * docs(review-policy): state the rmSync padding rule exactly (GST-898) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(review-depth): linear url() refusal in svgDrawing (wave review-2, red-team CRITICAL) SVG_REFUSED's url() entry backtracked quadratically on url( followed by a long whitespace run (80k spaces: 820 ms; 1 MB: over 230 s), and svgDrawing runs in collectLive and in collectCommit, which ship-queue ready, train build and land call with no timeout. The rewritten entry refuses exactly what #3838's pattern refused. Repin lib/review-depth.ts under no-loss replay GST-911-redos (verdict identity: 60,000 seeded strings, the edges and every SVG blob in history, zero differences). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: pre-landing review fixes (wave review-2, pass 1) - bin/gstack-diff-scope: _resolve_base takes a related local <base> before another remote's twin, the order resolveBase uses, so the two tools pick the same base for a bare name when origin/<base> is unrelated. - lib/review-depth.ts: a drawing's DOCTYPE names no document but W3C's SVG DTD; SYSTEM and other PUBLIC identifiers keep the SVG code. Repin lib/review-depth.ts under no-loss replay GST-911-redos (the DOCTYPE change only keeps more SVGs code, so it drops no reviewer). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: freeze the exported SVG_REFUSED list (wave review-2, Step 11) Exported only so test/review-risk-redos.test.ts can reach the url() entry; a frozen readonly copy keeps any importer from changing verdicts while DEPTH_RULES still reports the original rules. Repin lib/review-depth.ts under no-loss replay GST-911-redos (no pattern changed). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Revert "fix: freeze the exported SVG_REFUSED list (wave review-2, Step 11)" The fix-check (wave review-2) showed Object.freeze is shallow: each RegExp can still be changed in place, so the freeze did not close adversarial-native#1, and it moved the tree past the one the Step 11 voices reviewed. The finding ships as an open note (its reviewer rated it Low, not blocking; no production caller mutates the list). Restores the lib/review-depth.ts pin under no-loss replay GST-911-redos. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * docs(changelog): wave review-2 entry for the integrator fixes Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * docs(review-policy): a drawing's DOCTYPE names no outside document (wave review-2 docs audit) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Co-authored-by: exGeni <135786749+exGeni@users.noreply.github.com>
392 lines
18 KiB
TypeScript
392 lines
18 KiB
TypeScript
/**
|
|
* gate-diff git — the candidate model and the hardened git calls behind
|
|
* bin/gstack-gate-diff. ONE comparison: resolved merge-base SHA → the working
|
|
* tree as it stands (`git diff -M --no-color --no-ext-diff --no-textconv
|
|
* <merge-base>`), plus non-ignored untracked files as additions; never the
|
|
* committed + HEAD + untracked concatenation gstack-diff-scope uses. `--commit
|
|
* <sha>` scans one commit's first-parent delta without the working tree.
|
|
*
|
|
* Binary, symlink, submodule and undecodable paths come back as named
|
|
* `unsupported` files, not zero hunks. Every git call runs with
|
|
* GIT_OPTIONAL_LOCKS=0, no pager, no prompt, a timeout, and `--` before paths.
|
|
*/
|
|
import { spawnSync } from 'node:child_process';
|
|
import * as fs from 'node:fs';
|
|
import * as path from 'node:path';
|
|
import type { CommitInfo, FileDiff, FileStatus, Hunk, Unsupported } from './types';
|
|
|
|
export const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
|
|
const DIFF_FLAGS = ['diff', '-M', '--no-color', '--no-ext-diff', '--no-textconv', '--unified=3'];
|
|
|
|
export interface GitResult {
|
|
status: number;
|
|
stdout: Buffer;
|
|
stderr: string;
|
|
}
|
|
|
|
export function runGit(args: string[], cwd: string, timeoutMs = 60_000): GitResult {
|
|
const r = spawnSync('git', ['-c', 'core.quotePath=false', '--no-pager', ...args], {
|
|
cwd, timeout: timeoutMs, maxBuffer: 512 * 1024 * 1024,
|
|
env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' },
|
|
});
|
|
return { status: r.status ?? -1, stdout: r.stdout ?? Buffer.alloc(0), stderr: (r.stderr ?? Buffer.alloc(0)).toString('utf-8') };
|
|
}
|
|
|
|
function gitText(args: string[], cwd: string): string | null {
|
|
const r = runGit(args, cwd);
|
|
return r.status === 0 ? r.stdout.toString('utf-8').trim() : null;
|
|
}
|
|
|
|
export function repoRoot(cwd: string): string | null {
|
|
return gitText(['rev-parse', '--show-toplevel'], cwd);
|
|
}
|
|
|
|
export function resolvesToCommit(ref: string, cwd: string): string | null {
|
|
if (!/^[A-Za-z0-9._\/@{}^~-]+$/.test(ref) || ref.startsWith('-')) return null;
|
|
return gitText(['rev-parse', '--verify', '-q', `${ref}^{commit}`], cwd);
|
|
}
|
|
|
|
/**
|
|
* A ref that could be a branch name: not a sha, not relative or symbolic
|
|
* (`HEAD~1`, `main^2`, `@{u}`, `HEAD`, `FETCH_HEAD`), not a full `refs/` path.
|
|
* Only such a ref has a remote-tracking twin (`origin/<ref>`) worth trying, and
|
|
* only such a ref goes into a fix-line refspec; `origin/HEAD~1` would resolve
|
|
* to a different commit than the `HEAD~1` the caller named.
|
|
*/
|
|
function isBranchName(ref: string): boolean {
|
|
return !/^[0-9a-f]{7,64}$/.test(ref) && !/[~^]|@\{/.test(ref) && !/^(?:[A-Z_]*HEAD)$/.test(ref) && !ref.startsWith('refs/');
|
|
}
|
|
|
|
function remoteNames(cwd: string): string[] {
|
|
const remotes = (gitText(['remote'], cwd) ?? '').split('\n').filter(Boolean);
|
|
return remotes.includes('origin') ? ['origin', ...remotes.filter((r) => r !== 'origin')] : remotes;
|
|
}
|
|
|
|
/**
|
|
* The remote's HEAD target → `main` → `master` (the gstack-diff-scope chain),
|
|
* as a ref name; the remotes are walked in resolveBase's order, so the default
|
|
* and the fix line come from the same remote.
|
|
*/
|
|
export function defaultBase(cwd: string): string {
|
|
const remotes = remoteNames(cwd);
|
|
for (const remote of remotes) {
|
|
const head = gitText(['symbolic-ref', '-q', `refs/remotes/${remote}/HEAD`], cwd);
|
|
if (head) return head.replace(/^refs\/remotes\//, '');
|
|
}
|
|
for (const name of ['main', 'master']) {
|
|
if (resolvesToCommit(name, cwd) || remotes.some((remote) => resolvesToCommit(`${remote}/${name}`, cwd))) return name;
|
|
}
|
|
return 'main';
|
|
}
|
|
|
|
export function isShallow(cwd: string): boolean {
|
|
return gitText(['rev-parse', '--is-shallow-repository'], cwd) === 'true';
|
|
}
|
|
|
|
/**
|
|
* The base as a ref that resolves here and, when `head` is given, shares
|
|
* history with it. A bare branch name resolves to origin's tracking branch
|
|
* (`refs/remotes/origin/main` for `main`), the base /ship merges against and
|
|
* the one review-collect's collectLive and review-dispatch read: a stale local
|
|
* `main` behind it would scan upstream commits the branch only inherited
|
|
* (#3650, GST-883), so a local branch that differs is reported as `differs`.
|
|
* Without a related origin twin the related local branch wins over any other
|
|
* remote, so a fork's branch cannot replace it; it is `fallback` when origin
|
|
* lacks the branch or shares no history with HEAD (named as `unrelatedRemote`),
|
|
* and plain with no origin. Another remote's tracking branch is used only when
|
|
* no related local branch exists. A clone that checked out only the feature
|
|
* branch has no local `main` (`missing`); a local `main` that shares no
|
|
* history with HEAD is `unrelated`, so the fix line's fetch into the tracking
|
|
* ref is a fix and not a loop. Branches are read by their full names
|
|
* (`refs/heads/`, `refs/remotes/`), so a tag named `main` or `origin/main`
|
|
* cannot stand in for them, and a remote-qualified name (`upstream/main`) is
|
|
* taken as given.
|
|
*/
|
|
export function resolveBase(ref: string, cwd: string, head?: string): { ref: string; sha: string; local?: 'missing' | 'unrelated' | 'differs' | 'fallback'; unrelatedRemote?: string } | null {
|
|
const related = (sha: string) => !head || mergeBase(sha, head, cwd) !== null;
|
|
const direct = () => resolvesToCommit(ref, cwd);
|
|
if (!isBranchName(ref)) { const sha = direct(); return sha ? { ref, sha } : null; }
|
|
const qualified = resolvesToCommit(`refs/remotes/` + ref, cwd);
|
|
if (qualified) return { ref, sha: qualified };
|
|
const local = resolvesToCommit(`refs/heads/` + ref, cwd);
|
|
const remotes = remoteNames(cwd);
|
|
const localRelated = !!local && related(local);
|
|
const twin = (remote: string) => {
|
|
const sha = resolvesToCommit(`refs/remotes/` + remote + '/' + ref, cwd);
|
|
if (!sha || !related(sha)) return null;
|
|
const tracking = remote + '/' + ref;
|
|
return sha === local ? { ref: tracking, sha } : { ref: tracking, sha, local: !local ? 'missing' as const : localRelated ? 'differs' as const : 'unrelated' as const };
|
|
};
|
|
const hasOrigin = remotes.includes('origin');
|
|
const origin = hasOrigin ? twin('origin') : null;
|
|
if (origin) return origin;
|
|
const originRef = resolvesToCommit(`refs/remotes/origin/` + ref, cwd);
|
|
const fallback = hasOrigin ? { local: 'fallback' as const, ...(originRef ? { unrelatedRemote: 'origin/' + ref } : {}) } : {};
|
|
if (localRelated) return { ref, sha: local!, ...fallback };
|
|
for (const remote of remotes) {
|
|
if (remote === 'origin') continue;
|
|
const other = twin(remote);
|
|
if (other) return other;
|
|
}
|
|
if (local) return { ref, sha: local, ...(remotes.length ? { local: 'fallback' as const, ...(originRef ? { unrelatedRemote: 'origin/' + ref } : {}) } : {}) };
|
|
const sha = direct();
|
|
return sha ? { ref, sha } : null;
|
|
}
|
|
|
|
/** A word for a printed shell line: as is when it is plain, single-quoted otherwise (ref names may hold `;`, `$`, `(`, `{1,2}`). */
|
|
function shellWord(s: string): string {
|
|
return /^[A-Za-z0-9._\/@^~+:-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
|
|
}
|
|
|
|
/**
|
|
* The concrete recovery for an unresolvable base: fetch it from the detected
|
|
* remote into its remote-tracking ref (which resolveBase then finds; a bare
|
|
* `git fetch origin main` only updates FETCH_HEAD in a single-branch clone),
|
|
* unshallowing when needed. The refspec is forced (`+`) so the line also
|
|
* repairs a tracking ref that exists but shares no history with HEAD. A sha
|
|
* or a relative ref (`HEAD~1`, `main^2`, `@{u}`) is not a refspec: that gets a
|
|
* plain fetch (deepened when shallow).
|
|
*/
|
|
export function noBaseFix(ref: string, cwd: string): string {
|
|
const remotes = remoteNames(cwd);
|
|
const m = /^([^/]+)\/(.+)$/.exec(ref);
|
|
const remote = m && remotes.includes(m[1]) ? m[1] : remotes[0] ?? 'origin';
|
|
const branch = m && remotes.includes(m[1]) ? m[2] : ref;
|
|
if (!isBranchName(ref)) return isShallow(cwd) ? `git fetch --deepen=50 ${shellWord(remote)}` : `git fetch ${shellWord(remote)}`;
|
|
const refspec = shellWord(`+${branch}:refs/remotes/${remote}/${branch}`);
|
|
return isShallow(cwd) ? `git fetch --unshallow ${shellWord(remote)} ${refspec}` : `git fetch ${shellWord(remote)} ${refspec}`;
|
|
}
|
|
|
|
export function mergeBase(a: string, b: string, cwd: string): string | null {
|
|
return gitText(['merge-base', a, b], cwd);
|
|
}
|
|
|
|
export function headSha(cwd: string): string | null {
|
|
return gitText(['rev-parse', '--verify', '-q', 'HEAD^{commit}'], cwd);
|
|
}
|
|
|
|
/** C-style unquote of a git path (`"a\\tb"`), including octal UTF-8 bytes. */
|
|
export function unquoteGitPath(p: string): string {
|
|
if (!(p.startsWith('"') && p.endsWith('"') && p.length >= 2)) return p;
|
|
const bytes: number[] = [];
|
|
const s = p.slice(1, -1);
|
|
for (let i = 0; i < s.length; i++) {
|
|
const c = s[i];
|
|
if (c !== '\\') {
|
|
bytes.push(...Buffer.from(c, 'utf-8'));
|
|
continue;
|
|
}
|
|
const n = s[++i];
|
|
if (n === undefined) break;
|
|
if (/[0-7]/.test(n)) {
|
|
const oct = s.slice(i, i + 3).match(/^[0-7]{1,3}/)?.[0] ?? n;
|
|
bytes.push(Number.parseInt(oct, 8));
|
|
i += oct.length - 1;
|
|
} else bytes.push(...Buffer.from({ t: '\t', n: '\n', r: '\r', a: '\x07', b: '\b', f: '\f', v: '\v' }[n] ?? n, 'utf-8'));
|
|
}
|
|
return Buffer.from(bytes).toString('utf-8');
|
|
}
|
|
|
|
function stripPrefix(p: string, prefix: 'a/' | 'b/'): string {
|
|
const u = unquoteGitPath(p);
|
|
return u.startsWith(prefix) ? u.slice(2) : u;
|
|
}
|
|
|
|
/** Split `diff --git a/x b/y` into (x, y); equal paths resolve exactly, renames with spaces fall back to the middle ` b/`. */
|
|
function splitDiffGitLine(rest: string): [string, string] {
|
|
if (rest.startsWith('"')) {
|
|
const m = /^("(?:[^"\\]|\\.)*") ("(?:[^"\\]|\\.)*")$/.exec(rest);
|
|
if (m) return [stripPrefix(m[1], 'a/'), stripPrefix(m[2], 'b/')];
|
|
}
|
|
const body = rest.startsWith('a/') ? rest.slice(2) : rest;
|
|
if (body.length % 2 === 1) {
|
|
const half = (body.length - 1) / 2;
|
|
if (body.slice(half, half + 3) === ' b/' && body.slice(0, half) === body.slice(half + 3)) return [body.slice(0, half), body.slice(0, half)];
|
|
}
|
|
const idx = body.indexOf(' b/');
|
|
return idx < 0 ? [body, body] : [body.slice(0, idx), body.slice(idx + 3)];
|
|
}
|
|
|
|
interface Section {
|
|
headers: string[];
|
|
body: string[];
|
|
}
|
|
|
|
function splitSections(text: string): Section[] {
|
|
const sections: Section[] = [];
|
|
let cur: Section | null = null;
|
|
let inBody = false;
|
|
for (const line of text.split('\n')) {
|
|
if (line.startsWith('diff --git ')) {
|
|
cur = { headers: [line], body: [] };
|
|
sections.push(cur);
|
|
inBody = false;
|
|
continue;
|
|
}
|
|
if (!cur) continue;
|
|
if (!inBody && line.startsWith('@@')) inBody = true;
|
|
if (inBody) cur.body.push(line);
|
|
else cur.headers.push(line);
|
|
}
|
|
return sections;
|
|
}
|
|
|
|
function parseHunks(body: string[]): Hunk[] {
|
|
const hunks: Hunk[] = [];
|
|
let cur: Hunk | null = null;
|
|
for (const line of body) {
|
|
if (line.startsWith('@@')) {
|
|
cur = { header: line, lines: [] };
|
|
hunks.push(cur);
|
|
continue;
|
|
}
|
|
if (!cur || line.startsWith('\\')) continue;
|
|
if (line.startsWith('+')) cur.lines.push({ kind: 'add', text: line.slice(1) });
|
|
else if (line.startsWith('-')) cur.lines.push({ kind: 'del', text: line.slice(1) });
|
|
else if (line.startsWith(' ') || line === '') cur.lines.push({ kind: 'ctx', text: line.slice(1) });
|
|
}
|
|
return hunks;
|
|
}
|
|
|
|
function sectionToFile(sec: Section): FileDiff {
|
|
let [oldPath, newPath] = splitDiffGitLine(sec.headers[0].slice('diff --git '.length));
|
|
let status: FileStatus = 'modified';
|
|
let unsupported: Unsupported | undefined;
|
|
for (const h of sec.headers.slice(1)) {
|
|
if (h.startsWith('rename from ')) oldPath = unquoteGitPath(h.slice(12));
|
|
else if (h.startsWith('rename to ')) { newPath = unquoteGitPath(h.slice(10)); status = 'renamed'; }
|
|
else if (h.startsWith('copy from ')) oldPath = unquoteGitPath(h.slice(10));
|
|
else if (h.startsWith('copy to ')) { newPath = unquoteGitPath(h.slice(8)); status = 'copied'; }
|
|
else if (h.startsWith('new file mode')) status = 'added';
|
|
else if (h.startsWith('deleted file mode')) status = 'deleted';
|
|
else if (h.startsWith('--- ') && !h.startsWith('--- /dev/null')) oldPath = stripPrefix(h.slice(4), 'a/');
|
|
else if (h.startsWith('+++ ') && !h.startsWith('+++ /dev/null')) newPath = stripPrefix(h.slice(4), 'b/');
|
|
if (/\b120000\b/.test(h) && /mode/.test(h)) unsupported = 'symlink';
|
|
if (/^index [0-9a-f]+\.\.[0-9a-f]+ 160000$/.test(h) || /\b160000\b/.test(h) && /mode/.test(h)) unsupported = 'submodule';
|
|
if (h.startsWith('Binary files ')) unsupported = unsupported ?? 'binary';
|
|
if (h.startsWith('old mode') || h.startsWith('new mode')) status = status === 'modified' ? 'typechange' : status;
|
|
}
|
|
if (status === 'added') oldPath = newPath;
|
|
if (status === 'deleted') newPath = oldPath;
|
|
const hunks = unsupported ? [] : parseHunks(sec.body);
|
|
if (!unsupported && hunks.some((h) => h.lines.some((l) => /^Subproject commit [0-9a-f]+/.test(l.text)))) unsupported = 'submodule';
|
|
if (!unsupported && sec.body.some((l) => l.includes('\uFFFD'))) unsupported = 'undecodable';
|
|
const file: FileDiff = { oldPath, newPath, status: status === 'typechange' && hunks.length ? 'modified' : status, hunks: unsupported ? [] : hunks };
|
|
if (unsupported) file.unsupported = unsupported;
|
|
return file;
|
|
}
|
|
|
|
/** Parse `git diff` text (as produced with the flags above) into structured files. */
|
|
export function parseUnifiedDiff(text: string): FileDiff[] {
|
|
return splitSections(text).map(sectionToFile);
|
|
}
|
|
|
|
function decode(buf: Buffer): string {
|
|
return new TextDecoder('utf-8', { fatal: false }).decode(buf);
|
|
}
|
|
|
|
/** merge-base → working tree (tracked changes, staged and unstaged, with rename detection). */
|
|
export function diffWorkingTree(mergeBaseSha: string, cwd: string): FileDiff[] {
|
|
const r = runGit([...DIFF_FLAGS, mergeBaseSha, '--'], cwd);
|
|
if (r.status !== 0) throw new Error(`git diff failed: ${r.stderr.trim() || `exit ${r.status}`}`);
|
|
return parseUnifiedDiff(decode(r.stdout));
|
|
}
|
|
|
|
/**
|
|
* The commit's first parent, EMPTY_TREE for a root commit, or null when the
|
|
* parent is missing (shallow boundary). Read from the raw object: `git log
|
|
* --format=%P` hides a shallow boundary's parents, which would make the
|
|
* boundary look like a root and list the whole tree as added.
|
|
*/
|
|
export function firstParent(sha: string, cwd: string): string | null {
|
|
const raw = gitText(['cat-file', '-p', `${sha}^{commit}`], cwd);
|
|
if (raw === null) return null;
|
|
const parent = /^parent ([0-9a-f]{40,64})$/m.exec(raw.split('\n\n')[0] ?? '')?.[1];
|
|
if (!parent) return EMPTY_TREE;
|
|
return resolvesToCommit(parent, cwd);
|
|
}
|
|
|
|
/** One commit's first-parent delta (root commits diff against the empty tree). Throws when the parent is missing. */
|
|
export function diffCommit(sha: string, cwd: string): FileDiff[] {
|
|
const parent = firstParent(sha, cwd);
|
|
if (!parent) throw new Error(`first parent of ${sha} is not present (shallow history); fix: ${noBaseFix(`${sha}^`, cwd)}`);
|
|
const r = runGit([...DIFF_FLAGS, parent, sha, '--'], cwd);
|
|
if (r.status !== 0) throw new Error(`git diff failed: ${r.stderr.trim() || `exit ${r.status}`}`);
|
|
return parseUnifiedDiff(decode(r.stdout));
|
|
}
|
|
|
|
export function untrackedPaths(cwd: string): string[] {
|
|
const r = runGit(['ls-files', '-z', '--others', '--exclude-standard'], cwd);
|
|
if (r.status !== 0) return [];
|
|
return r.stdout.toString('utf-8').split('\0').filter(Boolean);
|
|
}
|
|
|
|
/** Non-ignored untracked files as whole-file additions; binary/symlink/undecodable named, nested repos as submodules. */
|
|
export function untrackedAsAdded(cwd: string, root: string): FileDiff[] {
|
|
const out: FileDiff[] = [];
|
|
for (const rel of untrackedPaths(cwd)) {
|
|
const abs = path.join(root, rel);
|
|
const file: FileDiff = { oldPath: rel, newPath: rel, status: 'added', hunks: [] };
|
|
try {
|
|
const st = fs.lstatSync(abs);
|
|
if (st.isSymbolicLink()) file.unsupported = 'symlink';
|
|
else if (st.isDirectory()) file.unsupported = 'submodule';
|
|
else {
|
|
const buf = fs.readFileSync(abs);
|
|
if (buf.subarray(0, 8000).includes(0)) file.unsupported = 'binary';
|
|
else {
|
|
let text: string;
|
|
try {
|
|
text = new TextDecoder('utf-8', { fatal: true }).decode(buf);
|
|
} catch {
|
|
file.unsupported = 'undecodable';
|
|
out.push(file);
|
|
continue;
|
|
}
|
|
const lines = text.split('\n');
|
|
if (lines[lines.length - 1] === '') lines.pop();
|
|
file.hunks = [{ header: `@@ -0,0 +1,${lines.length} @@`, lines: lines.map((t) => ({ kind: 'add' as const, text: t })) }];
|
|
}
|
|
}
|
|
} catch {
|
|
file.unsupported = 'undecodable';
|
|
}
|
|
out.push(file);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export function commitsInRange(fromExclusive: string, toInclusive: string, cwd: string): CommitInfo[] {
|
|
const r = runGit(['log', '--format=%H%x00%B%x00', `${fromExclusive}..${toInclusive}`, '--'], cwd);
|
|
if (r.status !== 0) return [];
|
|
const parts = r.stdout.toString('utf-8').split('\0');
|
|
const out: CommitInfo[] = [];
|
|
for (let i = 0; i + 1 < parts.length; i += 2) {
|
|
const sha = parts[i].trim();
|
|
if (/^[0-9a-f]{40,64}$/.test(sha)) out.push({ sha, message: parts[i + 1] });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export function commitInfo(sha: string, cwd: string): CommitInfo | null {
|
|
const msg = gitText(['log', '-1', '--format=%B', sha, '--'], cwd);
|
|
return msg === null ? null : { sha, message: msg };
|
|
}
|
|
|
|
/** Paths in the candidate tree: tracked + untracked for the working tree, `ls-tree` for a commit. */
|
|
export function treePaths(cwd: string, commit?: string): string[] {
|
|
const r = commit
|
|
? runGit(['ls-tree', '-r', '-z', '--name-only', commit, '--'], cwd)
|
|
: runGit(['ls-files', '-z', '--cached', '--others', '--exclude-standard'], cwd);
|
|
if (r.status !== 0) return [];
|
|
return r.stdout.toString('utf-8').split('\0').filter(Boolean);
|
|
}
|
|
|
|
export function readClaudeMd(root: string): string {
|
|
try {
|
|
return fs.readFileSync(path.join(root, 'CLAUDE.md'), 'utf-8');
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|