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 clearSegments(pi: ExtensionAPI) {
	pi.events.emit("footer:segment", { id: "cwd", text: undefined });
	pi.events.emit("footer:segment", { id: "git-branch", text: undefined });
}

function emitGit(pi: ExtensionAPI, ctx: ExtensionContext, status: GitStatus) {
	const home = process.env.HOME;
	const path = home && ctx.cwd.startsWith(home) ? `~${ctx.cwd.slice(home.length)}` : ctx.cwd;
	const branch = gitLabel(status);

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

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

export default function gitStatusExtension(pi: ExtensionAPI) {
	let currentCwd = "";
	let currentCtx: ExtensionContext | undefined;
	let hasUI = false;
	let refreshInFlight = false;
	let refreshPending = false;

	const refresh = async () => {
		if (!hasUI || !currentCtx || refreshInFlight) { refreshPending = true; return; }
		const ctx = currentCtx;
		refreshInFlight = true;
		try {
			const status = await readGitStatus(currentCwd);
			emitGit(pi, ctx, status);
		} finally {
			refreshInFlight = false;
			if (refreshPending) { refreshPending = false; refresh(); }
		}
	};

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