repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/git-status/index.ts

Raw
File outline
/**
 * Git status footer segment producer.
 *
 * Detects git branch, ahead/behind, and file status via porcelain v2.
 * Emits footer:segment with zone "workspace".
 */

import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
import { execFile } from "node:child_process";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);
const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
const CWD_STATUS_ID = "cwd";
const GIT_STATUS_ID = "git";

type GitStatus = {
	branch?: string;
	ahead: number;
	behind: number;
	conflicted: number;
	untracked: number;
	stashed: boolean;
	modified: number;
	staged: number;
	renamed: number;
	deleted: number;
};

const ICONS = {
	git: "", ahead: "↑", behind: "↓", diverged: "⇕",
	conflicted: "=", untracked: "?", stashed: "$",
	modified: "!", staged: "+", renamed: "»", deleted: "✘",
};

function hasFooter(): boolean {
	const footer = (globalThis as any)[FOOTER_KEY];
	return footer?.loaded === true && footer.version >= 1;
}

function parsePorcelain(stdout: string, hasStash: boolean): GitStatus {
	const s: GitStatus = { branch: undefined, ahead: 0, behind: 0, conflicted: 0, untracked: 0, stashed: false, modified: 0, staged: 0, renamed: 0, deleted: 0 };
	s.stashed = hasStash;

	for (const line of stdout.split(/\r?\n/)) {
		if (!line) continue;
		if (line.startsWith("# branch.head ")) {
			const b = line.slice("# branch.head ".length).trim();
			s.branch = b && b !== "(detached)" ? b : undefined;
			continue;
		}
		if (line.startsWith("# branch.ab ")) {
			const m = line.match(/\+(\d+)\s+-(\d+)/);
			if (m) { s.ahead = Number(m[1]); s.behind = Number(m[2]); }
			continue;
		}
		if (line.startsWith("#")) continue;
		if (line.startsWith("? ")) { s.untracked++; continue; }
		if (line.startsWith("u ")) { s.conflicted++; continue; }
		if (!(line.startsWith("1 ") || line.startsWith("2 "))) continue;
		const xy = line.split(" ")[1] ?? "..";
		const x = xy[0] ?? ".", y = xy[1] ?? ".";
		if (x === "R") s.renamed++;
		else if (x === "D") s.deleted++;
		else if (x !== "." && x !== " ") s.staged++;
		if (y === "M") s.modified++;
		else if (y === "D") s.deleted++;
	}
	return s;
}

async function readGitStatus(cwd: string): Promise<GitStatus> {
	const empty: GitStatus = { branch: undefined, ahead: 0, behind: 0, conflicted: 0, untracked: 0, stashed: false, modified: 0, staged: 0, renamed: 0, deleted: 0 };
	try {
		const [{ stdout }, stash] = await Promise.all([
			execFileAsync("git", ["status", "--porcelain=2", "--branch"], { cwd }),
			execFileAsync("git", ["rev-parse", "--verify", "--quiet", "refs/stash"], { cwd }).catch(() => ({ stdout: "" })),
		]);
		return parsePorcelain(
			typeof stdout === "string" ? stdout : String(stdout),
			stash.stdout.trim().length > 0,
		);
	} catch { return empty; }
}

function gitLabel(status: GitStatus): string | undefined {
	if (!status.branch) return undefined;
	const allStatus = [
		status.conflicted > 0 ? ICONS.conflicted : "",
		status.stashed ? ICONS.stashed : "",
		status.deleted > 0 ? ICONS.deleted : "",
		status.renamed > 0 ? ICONS.renamed : "",
		status.modified > 0 ? ICONS.modified : "",
		status.staged > 0 ? ICONS.staged : "",
		status.untracked > 0 ? ICONS.untracked : "",
	].join("");
	const ab = status.ahead > 0 && status.behind > 0 ? ICONS.diverged
		: status.ahead > 0 ? ICONS.ahead
		: status.behind > 0 ? ICONS.behind : "";
	const statusBlock = allStatus || ab ? `[${allStatus}${ab}]` : "";
	return `${status.branch}${statusBlock ? ` ${statusBlock}` : ""}`;
}

function isStaleContextError(error: unknown): boolean {
	return error instanceof Error && error.message.includes("extension ctx is stale");
}

function ignoreStaleContext(fn: () => void) {
	try { fn(); }
	catch (error) { if (!isStaleContextError(error)) throw error; }
}

function clearSegments(pi: ExtensionAPI) {
	ignoreStaleContext(() => pi.events.emit("footer:segment", { id: "cwd", text: undefined }));
	ignoreStaleContext(() => pi.events.emit("footer:segment", { id: "git-branch", text: undefined }));
}

function cwdLabel(cwd: string): string {
	const home = process.env.HOME;
	return home && cwd.startsWith(home) ? `~${cwd.slice(home.length)}` : cwd;
}

function emitGit(pi: ExtensionAPI, ctx: ExtensionContext, cwd: string, status: GitStatus) {
	const path = cwdLabel(cwd);
	const branch = gitLabel(status);

	if (hasFooter()) {
		ignoreStaleContext(() => ctx.ui.setStatus(CWD_STATUS_ID, undefined));
		ignoreStaleContext(() => ctx.ui.setStatus(GIT_STATUS_ID, undefined));
		ignoreStaleContext(() => pi.events.emit("footer:segment", { id: "cwd", text: path, icon: "󰝰", color: "syntaxOperator", zone: "workspace", order: 0 }));
		if (branch) {
			ignoreStaleContext(() => pi.events.emit("footer:segment", {
				id: "git-branch",
				text: branch,
				icon: ICONS.git,
				color: "syntaxKeyword",
				zone: "workspace",
				order: 1,
			}));
		} else {
			ignoreStaleContext(() => pi.events.emit("footer:segment", { id: "git-branch", text: undefined }));
		}
		return;
	}

	clearSegments(pi);
	ignoreStaleContext(() => ctx.ui.setStatus(CWD_STATUS_ID, path));
	ignoreStaleContext(() => ctx.ui.setStatus(GIT_STATUS_ID, branch));
}

export default function gitStatusExtension(pi: ExtensionAPI) {
	let generation = 0;
	let hasUI = false;

	const refresh = async (ctx: ExtensionContext) => {
		const ticket = generation;
		let cwd: string;
		try { cwd = ctx.cwd; }
		catch (error) { if (isStaleContextError(error)) return; throw error; }
		if (!hasUI) return;

		const status = await readGitStatus(cwd);
		if (ticket !== generation) return;
		emitGit(pi, ctx, cwd, status);
	};

	pi.on("session_start", async (_e, ctx) => { generation++; hasUI = ctx.hasUI; void refresh(ctx); });
	pi.on("agent_end", async (_e, ctx) => { if (hasUI) void refresh(ctx); });
	pi.on("tool_execution_end", async (_e, ctx) => { if (hasUI) void refresh(ctx); });
	pi.on("session_shutdown", async (_e, ctx) => {
		generation++;
		clearSegments(pi);
		ignoreStaleContext(() => {
			if (ctx.hasUI) {
				ctx.ui.setStatus(CWD_STATUS_ID, undefined);
				ctx.ui.setStatus(GIT_STATUS_ID, undefined);
			}
		});
	});
}