/** * Read-only git context for the browse pages. * * The header shows the checked-out branch (or the detached head); uncommitted * changes are the changes chip's concern. Queries go through the shared * `lib/git` seams so the read-only * plumbing lives in one place. State (the TTL cache) lives in the factory * closure, never in `lib/`. */ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { createExecRunner, currentBranch, hasCommits, repoRoot, revParse, type RunGit, } from "../../../lib/git/index.ts"; import { diffArgs, type DiffMode } from "../../../lib/diff/modes.ts"; import { type ChangedFile, inMode, parseStatusZ } from "../../../lib/diff/status.ts"; export interface GitStatus { /** Checked-out branch, when HEAD is attached. */ branch?: string; /** Short object id, when HEAD is detached. */ head?: string; } export type GitStatusProvider = () => Promise; export interface GitStatusOptions { /** How long a result is reused, in ms (default 2000). */ ttlMs?: number; /** Wall-clock seam; defaults to the real clock. */ now?: () => number; } /** * Memoize `read` for `ttlMs`, sharing an in-flight call. `checkedAt` is stamped * before the read starts, so a failure is cached for the same window instead of * retrying on every page render. */ function ttlMemo( read: () => Promise, ttlMs: number, now: () => number, ): () => Promise { let cached: T | undefined; let checkedAt = 0; let pending: Promise | undefined; return () => { if (pending) return pending; const t = now(); if (checkedAt !== 0 && t - checkedAt < ttlMs) return Promise.resolve(cached); checkedAt = t; pending = read() .catch(() => undefined) .then((next) => { cached = next; return next; }) .finally(() => { pending = undefined; }); return pending; }; } /** * Build a provider for `root` that caches its result for `ttlMs`. It never * throws: a non-repository, a failed git call, or a timeout yields `undefined`, * and the page simply omits the chip. */ export function createGitStatus( pi: Pick, root: string, options: GitStatusOptions = {}, ): GitStatusProvider { const runGit = createExecRunner(pi); async function read(): Promise { if (!(await repoRoot(runGit, root))) return undefined; const branch = await currentBranch(runGit, root); const head = branch ? undefined : (await revParse(runGit, root, "HEAD"))?.slice(0, 7); if (!branch && !head) return undefined; return { branch, head }; } return ttlMemo(read, options.ttlMs ?? 2000, options.now ?? (() => Date.now())); } /** One comparison scope's change list. */ export interface DiffList { /** * The comparison the numbers were taken in, which is not always the one asked for: with no commit * yet, `head` falls to the index when anything is staged and to the working tree when nothing is * (`git diff HEAD` cannot run at all). A page that links to this list opens the comparison it * names. */ mode: DiffMode; files: ChangedFile[]; /** `git diff --stat` output for the scope, or an empty string. */ stat: string; /** Added lines in the scope. */ insertions: number; /** Removed lines in the scope. */ deletions: number; } /** * The change list for the browse pages. Like {@link createGitStatus}, it never * throws: a non-repository, a failed git call, or a timeout yields `undefined`, * and the page omits the change chrome. */ export interface GitDiffProvider { list(mode: DiffMode): Promise; } export interface GitDiffOptions { /** How long the status list is reused, in ms (default 2000). */ ttlMs?: number; /** Per-call git timeout in ms (default 4000). */ timeoutMs?: number; /** Wall-clock seam; defaults to the real clock. */ now?: () => number; } interface RepoState { files: ChangedFile[]; hasCommits: boolean; } const INSERTIONS = /(\d+) insertions?\(\+\)/; const DELETIONS = /(\d+) deletions?\(-\)/; /** A count from a diffstat summary line, or `0` when the line does not carry it. */ function summaryCount(text: string, pattern: RegExp): number { const match = pattern.exec(text); return match ? Number(match[1]) : 0; } /** Build a read-only diff provider for `root`, with a TTL-cached status list. */ export function createGitDiff( pi: Pick, root: string, options: GitDiffOptions = {}, ): GitDiffProvider { const exec = createExecRunner(pi); const run: RunGit = (args, opts) => exec(args, { timeoutMs: options.timeoutMs ?? 4000, ...opts }); async function read(): Promise { if (!(await repoRoot(run, root))) return undefined; const status = await run(["status", "--porcelain=v1", "-z", "--untracked-files=all"], { cwd: root }); if (status.code !== 0) return undefined; return { files: parseStatusZ(status.stdout), hasCommits: await hasCommits(run, root) }; } /** The cached repository state, or `undefined` outside a repository. */ const state = ttlMemo(read, options.ttlMs ?? 2000, options.now ?? (() => Date.now())); /** * The comparison a request is really taken in, one ladder and no second idea about a fresh * repository: `head` needs a commit, then the index when anything is staged, then the working * tree — the first of those that holds what the reader has. Its numbers and the page that links * to them come from the value this returns. */ const effectiveMode = (mode: DiffMode, current: RepoState): DiffMode => { if (mode !== "head" || current.hasCommits) return mode; return current.files.some((file) => inMode(file, "staged")) ? "staged" : "worktree"; }; return { async list(mode) { const current = await state(); if (!current) return undefined; const taken = effectiveMode(mode, current); const args = diffArgs(taken); const stat = await run(["diff", "--no-color", "--stat", ...args, "--"], { cwd: root }); const output = stat.code === 0 ? stat.stdout : ""; const trimmed = output.trimEnd(); const summary = trimmed.slice(trimmed.lastIndexOf("\n") + 1); return { mode: taken, // The paths are the ones the mode *asked for* names, not the comparison's: `head` is // every changed path, and a marker must not vanish from an untracked file the reader // can still change before the first commit. files: current.files.filter((file) => inMode(file, mode)), stat: output.trim(), insertions: summaryCount(summary, INSERTIONS), deletions: summaryCount(summary, DELETIONS), }; }, }; }