|
| 1 | +// Git metrics for the OpenCode sidebar. |
| 2 | +// |
| 3 | +// Two independent numbers, deliberately not OpenCode's own diff counters: |
| 4 | +// branch = merge-base(<default branch>, HEAD) -> HEAD (committed work on this branch) |
| 5 | +// dirty = HEAD -> index + working tree (tracked, not committed yet) |
| 6 | + |
| 7 | +import { execFile } from "node:child_process"; |
| 8 | + |
| 9 | +export type Stats = { |
| 10 | + files: number; |
| 11 | + additions: number; |
| 12 | + deletions: number; |
| 13 | +}; |
| 14 | + |
| 15 | +export type BaseBranch = { |
| 16 | + /** What to call it on screen. */ |
| 17 | + label: string; |
| 18 | + /** A ref that actually resolves, which the label may not: a clone need not carry the branch locally. */ |
| 19 | + ref: string; |
| 20 | +}; |
| 21 | + |
| 22 | +export type VcsStatus = { |
| 23 | + base: string; |
| 24 | + branch: Stats; |
| 25 | + dirty: Stats; |
| 26 | +}; |
| 27 | + |
| 28 | +export type StatusSegment = { |
| 29 | + label: string; |
| 30 | + additions: number; |
| 31 | + deletions: number; |
| 32 | +}; |
| 33 | + |
| 34 | +export type GitRunner = (args: string[]) => Promise<string | undefined>; |
| 35 | + |
| 36 | +const FALLBACK_BASE = "main"; |
| 37 | +const BASE_CANDIDATES = ["main", "master"]; |
| 38 | + |
| 39 | +function emptyStats(): Stats { |
| 40 | + return { files: 0, additions: 0, deletions: 0 }; |
| 41 | +} |
| 42 | + |
| 43 | +/** Sum `git diff --numstat` output. Binary files report "-" and count as changed files only. */ |
| 44 | +export function parseNumstat(output: string): Stats { |
| 45 | + const stats = emptyStats(); |
| 46 | + for (const line of output.split("\n")) { |
| 47 | + if (line.trim() === "") continue; |
| 48 | + const [additions = "", deletions = ""] = line.split("\t"); |
| 49 | + stats.files += 1; |
| 50 | + const added = Number.parseInt(additions, 10); |
| 51 | + const deleted = Number.parseInt(deletions, 10); |
| 52 | + if (Number.isInteger(added)) stats.additions += added; |
| 53 | + if (Number.isInteger(deleted)) stats.deletions += deleted; |
| 54 | + } |
| 55 | + return stats; |
| 56 | +} |
| 57 | + |
| 58 | +function hasLines(stats: Stats): boolean { |
| 59 | + return stats.additions > 0 || stats.deletions > 0; |
| 60 | +} |
| 61 | + |
| 62 | +function fileCount(count: number): string { |
| 63 | + return `${count} ${count === 1 ? "file" : "files"}`; |
| 64 | +} |
| 65 | + |
| 66 | +/** One line each, kept separate so the sidebar can colour additions and deletions on its own. */ |
| 67 | +export function statusSegments(status: VcsStatus): StatusSegment[] { |
| 68 | + const segments: StatusSegment[] = []; |
| 69 | + const { branch, dirty } = status; |
| 70 | + if (branch.files > 0) { |
| 71 | + // Binary-only changes carry no line counts, so the file count is all that is left to show. |
| 72 | + const label = `Since ${status.base}:`; |
| 73 | + segments.push({ |
| 74 | + label: hasLines(branch) ? label : `${label} ${fileCount(branch.files)}`, |
| 75 | + additions: branch.additions, |
| 76 | + deletions: branch.deletions, |
| 77 | + }); |
| 78 | + } |
| 79 | + if (dirty.files > 0) { |
| 80 | + segments.push({ |
| 81 | + label: `Uncommitted: ${fileCount(dirty.files)}`, |
| 82 | + additions: dirty.additions, |
| 83 | + deletions: dirty.deletions, |
| 84 | + }); |
| 85 | + } |
| 86 | + return segments; |
| 87 | +} |
| 88 | + |
| 89 | +/** Trimmed stdout, or undefined when git fails (not a repo, unknown ref, ...). */ |
| 90 | +export function gitRunner(cwd: string): GitRunner { |
| 91 | + return (args) => |
| 92 | + new Promise((resolve) => { |
| 93 | + execFile("git", ["--no-optional-locks", ...args], { cwd }, (error, stdout) => { |
| 94 | + resolve(error ? undefined : stdout.trim()); |
| 95 | + }); |
| 96 | + }); |
| 97 | +} |
| 98 | + |
| 99 | +/** Local branch first so a stale remote does not widen the delta, remote as the fallback. */ |
| 100 | +async function resolveRef(run: GitRunner, name: string): Promise<string | undefined> { |
| 101 | + for (const ref of [`refs/heads/${name}`, `refs/remotes/origin/${name}`]) { |
| 102 | + if ((await run(["rev-parse", "--verify", "--quiet", ref])) !== undefined) return ref; |
| 103 | + } |
| 104 | + return undefined; |
| 105 | +} |
| 106 | + |
| 107 | +/** The branch point: whatever the remote calls default, else the first branch that exists. */ |
| 108 | +export async function detectBase(run: GitRunner): Promise<BaseBranch> { |
| 109 | + const remoteHead = await run(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]); |
| 110 | + const names = remoteHead ? [remoteHead.replace(/^origin\//, "")] : BASE_CANDIDATES; |
| 111 | + for (const name of names) { |
| 112 | + const ref = await resolveRef(run, name); |
| 113 | + if (ref) return { label: name, ref }; |
| 114 | + } |
| 115 | + return { label: FALLBACK_BASE, ref: FALLBACK_BASE }; |
| 116 | +} |
| 117 | + |
| 118 | +async function collectBranch(run: GitRunner, ref: string): Promise<Stats> { |
| 119 | + const mergeBase = await run(["merge-base", ref, "HEAD"]); |
| 120 | + if (!mergeBase) return emptyStats(); |
| 121 | + const numstat = await run(["diff", "--numstat", `${mergeBase}..HEAD`]); |
| 122 | + return numstat === undefined ? emptyStats() : parseNumstat(numstat); |
| 123 | +} |
| 124 | + |
| 125 | +async function collectDirty(run: GitRunner): Promise<Stats> { |
| 126 | + const numstat = await run(["diff", "--numstat", "HEAD"]); |
| 127 | + return numstat === undefined ? emptyStats() : parseNumstat(numstat); |
| 128 | +} |
| 129 | + |
| 130 | +/** Undefined outside a repository. Branch and dirty stats are gathered concurrently. */ |
| 131 | +export async function collectStatus(run: GitRunner): Promise<VcsStatus | undefined> { |
| 132 | + if ((await run(["rev-parse", "--git-dir"])) === undefined) return undefined; |
| 133 | + const base = await detectBase(run); |
| 134 | + const [branch, dirty] = await Promise.all([collectBranch(run, base.ref), collectDirty(run)]); |
| 135 | + return { base: base.label, branch, dirty }; |
| 136 | +} |
0 commit comments