@saadjs/pi-git-status 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -0
  3. package/core.ts +137 -0
  4. package/index.ts +86 -0
  5. package/package.json +35 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Saad Bash
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # @saadjs/pi-git-status
2
+
3
+ Git status in Pi's footer, alongside other extensions' statuses.
4
+
5
+ ```text
6
+ main • 3 changed • 2 untracked • +42 −17
7
+ ```
8
+
9
+ Clean trees show `main • clean`. The status is hidden outside Git repositories or when Git is unavailable.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pi install npm:@saadjs/pi-git-status
15
+ ```
16
+
17
+ To try locally from the monorepo root:
18
+
19
+ ```bash
20
+ pi -e ./extensions/git-status/index.ts
21
+ ```
22
+
23
+ Use an absolute path to `index.ts` when running Pi in another repository.
24
+
25
+ ## Counts
26
+
27
+ - **Branch:** current branch, or `detached`.
28
+ - **Changed:** tracked files with staged or unstaged changes, counted once per file, including renames, conflicts, and submodule changes.
29
+ - **Untracked:** individual untracked files; ignored files are excluded.
30
+ - **+ / −:** net tracked-file line additions/deletions against `HEAD`. Untracked and binary contents are excluded.
31
+
32
+ Counts cover the whole repository, even from a subdirectory. Refreshes on session start, after successful `edit`/`write` tools, and after agent completion.
33
+
34
+ Custom footers must display extension statuses via `footerData.getExtensionStatuses()`.
35
+
36
+ ## Test
37
+
38
+ ```bash
39
+ pnpm --filter @saadjs/pi-git-status test
40
+ ```
package/core.ts ADDED
@@ -0,0 +1,137 @@
1
+ import { execFile } from "node:child_process";
2
+
3
+ export interface GitStatus {
4
+ branch: string;
5
+ changed: number;
6
+ untracked: number;
7
+ added: number;
8
+ removed: number;
9
+ }
10
+
11
+ export interface WorkingTreeStatus {
12
+ branch: string;
13
+ unborn: boolean;
14
+ changed: number;
15
+ untracked: number;
16
+ }
17
+
18
+ /** Parse porcelain v1 -z, skipping the extra source path on rename/copy records. */
19
+ export function parseWorkingTree(output: string): WorkingTreeStatus {
20
+ const records = output.split("\0");
21
+ const header = records.shift() ?? "";
22
+ const unborn = /^## (No commits yet on |Initial commit on )/.test(header);
23
+ const branch = header.startsWith("## HEAD (no branch)")
24
+ ? "detached"
25
+ : header
26
+ .replace(/^## (?:No commits yet on |Initial commit on )?/, "")
27
+ .split("...")[0]
28
+ .replace(/ \[.*\]$/, "");
29
+ let changed = 0;
30
+ let untracked = 0;
31
+
32
+ for (let i = 0; i < records.length; i++) {
33
+ const record = records[i];
34
+ if (!record) continue;
35
+ const status = record.slice(0, 2);
36
+ if (status === "??") untracked++;
37
+ else if (status !== "!!") changed++;
38
+ if (/[RC]/.test(status)) i++;
39
+ }
40
+
41
+ return { branch, unborn, changed, untracked };
42
+ }
43
+
44
+ /** Binary files report '-' instead of line counts; rename paths are separate NUL records. */
45
+ export function parseNumstat(output: string): Pick<GitStatus, "added" | "removed"> {
46
+ const records = output.split("\0");
47
+ let added = 0;
48
+ let removed = 0;
49
+ for (let i = 0; i < records.length; i++) {
50
+ const match = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/.exec(records[i]);
51
+ if (!match) continue;
52
+ if (match[1] !== "-") added += Number(match[1]);
53
+ if (match[2] !== "-") removed += Number(match[2]);
54
+ if (match[3] === "") i += 2;
55
+ }
56
+ return { added, removed };
57
+ }
58
+
59
+ function git(cwd: string, args: string[], signal?: AbortSignal): Promise<string> {
60
+ return new Promise((resolve, reject) => {
61
+ const child = execFile(
62
+ "git",
63
+ ["-c", "color.ui=false", ...args],
64
+ {
65
+ cwd,
66
+ signal,
67
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
68
+ encoding: "utf8",
69
+ timeout: 5_000,
70
+ maxBuffer: 16 * 1024 * 1024,
71
+ windowsHide: true,
72
+ },
73
+ (error, stdout) => (error ? reject(error) : resolve(stdout)),
74
+ );
75
+ // hash-object --stdin needs EOF to hash the empty tree (including SHA-256 repos).
76
+ child.stdin?.end();
77
+ });
78
+ }
79
+
80
+ /** Net tracked-file changes against HEAD; untracked contents are deliberately excluded. */
81
+ export async function readGitStatus(cwd: string, signal?: AbortSignal): Promise<GitStatus | null> {
82
+ try {
83
+ const status = parseWorkingTree(
84
+ await git(
85
+ cwd,
86
+ ["status", "--porcelain=v1", "-z", "--branch", "--untracked-files=all", "--renames"],
87
+ signal,
88
+ ),
89
+ );
90
+ // Before the first commit, compare the working tree to an empty tree instead of HEAD.
91
+ const base = status.unborn
92
+ ? (await git(cwd, ["hash-object", "-t", "tree", "--stdin"], signal)).trim()
93
+ : "HEAD";
94
+ const diff = await git(
95
+ cwd,
96
+ [
97
+ "diff",
98
+ "--numstat",
99
+ "-z",
100
+ "--no-ext-diff",
101
+ "--no-textconv",
102
+ "--no-relative",
103
+ "--find-renames",
104
+ base,
105
+ "--",
106
+ ],
107
+ signal,
108
+ );
109
+ return {
110
+ branch: status.branch,
111
+ changed: status.changed,
112
+ untracked: status.untracked,
113
+ ...parseNumstat(diff),
114
+ };
115
+ } catch {
116
+ // Not a repository, Git unavailable, timeout, or cancellation: don't leave stale counts.
117
+ return null;
118
+ }
119
+ }
120
+
121
+ type StatusColor = "text" | "accent" | "muted" | "success" | "error";
122
+
123
+ export function formatGitStatus(
124
+ status: GitStatus,
125
+ color: (name: StatusColor, text: string) => string = (_name, text) => text,
126
+ ): string {
127
+ const separator = color("muted", " • ");
128
+ if (status.changed === 0 && status.untracked === 0) {
129
+ return color("text", status.branch) + separator + color("success", "clean");
130
+ }
131
+ return [
132
+ color("text", status.branch),
133
+ color(status.changed ? "accent" : "muted", `${status.changed} changed`),
134
+ color("muted", `${status.untracked} untracked`),
135
+ `${color(status.added ? "success" : "muted", `+${status.added}`)} ${color(status.removed ? "error" : "muted", `−${status.removed}`)}`,
136
+ ].join(separator);
137
+ }
package/index.ts ADDED
@@ -0,0 +1,86 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { formatGitStatus, readGitStatus } from "./core.ts";
3
+
4
+ const STATUS_KEY = "git-status";
5
+ const DEBOUNCE_MS = 150;
6
+
7
+ export default function (pi: ExtensionAPI) {
8
+ let stop: (() => void) | undefined;
9
+ let requestRefresh: ((ctx: ExtensionContext) => void) | undefined;
10
+
11
+ pi.on("session_start", (_event, ctx) => {
12
+ stop?.();
13
+ stop = undefined;
14
+ requestRefresh = undefined;
15
+ if (ctx.mode !== "tui" || !ctx.hasUI) return;
16
+
17
+ let context = ctx;
18
+ let disposed = false;
19
+ let busy = false;
20
+ let pending = false;
21
+ let lastText: string | undefined;
22
+ let debounce: ReturnType<typeof setTimeout> | undefined;
23
+ const controller = new AbortController();
24
+
25
+ async function refresh() {
26
+ if (disposed) return;
27
+ if (busy) {
28
+ pending = true;
29
+ return;
30
+ }
31
+ busy = true;
32
+ const current = context;
33
+ try {
34
+ const status = await readGitStatus(current.cwd, controller.signal);
35
+ if (disposed) return;
36
+ const text = status
37
+ ? formatGitStatus(status, (name, value) => current.ui.theme.fg(name, value))
38
+ : undefined;
39
+ if (text !== lastText) {
40
+ current.ui.setStatus(STATUS_KEY, text);
41
+ lastText = text;
42
+ }
43
+ } finally {
44
+ busy = false;
45
+ if (pending && !disposed) {
46
+ pending = false;
47
+ void refresh();
48
+ }
49
+ }
50
+ }
51
+
52
+ requestRefresh = (nextContext) => {
53
+ context = nextContext;
54
+ if (debounce) clearTimeout(debounce);
55
+ debounce = setTimeout(() => {
56
+ debounce = undefined;
57
+ void refresh();
58
+ }, DEBOUNCE_MS);
59
+ debounce.unref();
60
+ };
61
+
62
+ stop = () => {
63
+ if (disposed) return;
64
+ disposed = true;
65
+ if (debounce) clearTimeout(debounce);
66
+ controller.abort();
67
+ context.ui.setStatus(STATUS_KEY, undefined);
68
+ };
69
+ void refresh();
70
+ });
71
+
72
+ // Refresh after successful file mutations, not read-only tools or every shell call.
73
+ pi.on("tool_result", (event, ctx) => {
74
+ if (!event.isError && (event.toolName === "edit" || event.toolName === "write")) {
75
+ requestRefresh?.(ctx);
76
+ }
77
+ });
78
+ // Catch shell-made changes once the agent finishes.
79
+ pi.on("agent_end", (_event, ctx) => requestRefresh?.(ctx));
80
+
81
+ pi.on("session_shutdown", () => {
82
+ stop?.();
83
+ stop = undefined;
84
+ requestRefresh = undefined;
85
+ });
86
+ }
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@saadjs/pi-git-status",
3
+ "version": "0.1.0",
4
+ "description": "Live Git branch, changed files, and line counts in the Pi footer",
5
+ "keywords": [
6
+ "extension",
7
+ "footer",
8
+ "git",
9
+ "pi",
10
+ "pi-package",
11
+ "status"
12
+ ],
13
+ "license": "MIT",
14
+ "files": [
15
+ "index.ts",
16
+ "core.ts",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "type": "module",
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "peerDependencies": {
25
+ "@earendil-works/pi-coding-agent": "*"
26
+ },
27
+ "pi": {
28
+ "extensions": [
29
+ "./index.ts"
30
+ ]
31
+ },
32
+ "scripts": {
33
+ "test": "node --experimental-strip-types --test tests/*.test.ts"
34
+ }
35
+ }