repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

refactor(pi/files-widget): harden file viewer command execution and add tests

0dbebb46124cf08ec51ad0a662332ed69588f206

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

pi/agent/bun.lock

Modified
36 36 "extensions/files-widget": {
37 37 "name": "@bugabinga/pi-ext-files-widget",
38 38 "version": "0.1.0",
39 + "devDependencies": {
40 + "@mariozechner/pi-tui": "^0.72.1",
41 + },
40 43 "extensions/footer": {
41 44 "name": "@bugabinga/pi-ext-footer",

pi/agent/extensions/files-widget/__tests__/file-viewer.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "bun:test";
2 +import type { Stats } from "node:fs";
3 +import { loadFileContent, type CommandRunner, type FileViewerDeps } from "../file-viewer.ts";
5 +type Call = { command: string; args: string[]; input?: string; cwd?: string };
7 +const FILE_WITH_SHELL_CHARS = `/tmp/weird "file"; rm -rf nope.md`;
9 +function fileStat(): Stats {
10 + return { isDirectory: () => false } as Stats;
13 +function dirStat(): Stats {
14 + return { isDirectory: () => true } as Stats;
17 +function deps(overrides: Partial<FileViewerDeps> = {}): FileViewerDeps {
18 + return {
19 + hasCommand: () => false,
20 + isGitRepo: () => false,
21 + runCommand: () => { throw new Error("unexpected command"); },
22 + readFile: () => "hello\nworld",
23 + stat: fileStat,
24 + columns: 80,
25 + ...overrides,
26 + };
29 +function recordingRunner(calls: Call[], responses: Record<string, string | Error>): CommandRunner {
30 + return (command, args, options = {}) => {
31 + calls.push({ command, args, input: options.input, cwd: options.cwd });
32 + const key = `${command} ${args.join(" ")}`;
33 + const response = responses[key] ?? responses[command];
34 + if (response instanceof Error) throw response;
35 + if (response !== undefined) return response;
36 + throw new Error(`unexpected command: ${key}`);
37 + };
40 +describe("loadFileContent", () => {
41 + it("returns a typed directory message", () => {
42 + const result = loadFileContent("/tmp/dir", "/tmp", false, false, 80, true, deps({ stat: dirStat }));
43 + expect(result.renderedMarkdown).toBe(false);
44 + expect(result.lines[0]).toContain("Directory selected");
45 + });
47 + it("uses execFile-style command + args for git diff and delta", () => {
48 + const calls: Call[] = [];
49 + const diff = "diff --git a/file b/file\n+new line";
50 + const result = loadFileContent(FILE_WITH_SHELL_CHARS, "/repo", true, true, 100, true, deps({
51 + hasCommand: (cmd) => cmd === "delta",
52 + isGitRepo: () => true,
53 + runCommand: recordingRunner(calls, {
54 + "git diff --no-color -- /tmp/weird \"file\"; rm -rf nope.md": diff,
55 + delta: "1 │ +new line",
56 + }),
57 + }));
59 + expect(result.renderedMarkdown).toBe(false);
60 + expect(result.lines.join("\n")).toContain("new line");
61 + expect(calls[0]).toEqual({
62 + command: "git",
63 + args: ["diff", "--no-color", "--", FILE_WITH_SHELL_CHARS],
64 + cwd: "/repo",
65 + input: undefined,
66 + });
67 + expect(calls[1]?.command).toBe("delta");
68 + expect(calls[1]?.input).toBe(diff);
69 + });
71 + it("falls back from wrapped bat to plain bat", () => {
72 + const calls: Call[] = [];
73 + const result = loadFileContent("/tmp/a.ts", "/tmp", false, false, 80, true, deps({
74 + hasCommand: (cmd) => cmd === "bat",
75 + runCommand: recordingRunner(calls, {
76 + "bat --style=numbers --color=always --paging=never --wrap=auto --terminal-width=80 /tmp/a.ts": new Error("wrap unsupported"),
77 + "bat --style=numbers --color=always --paging=never --terminal-width=80 /tmp/a.ts": "1 │ const x = 1;",
78 + }),
79 + }));
81 + expect(result.lines).toEqual(["1 │ const x = 1;"]);
82 + expect(calls).toHaveLength(2);
83 + expect(calls[1]?.args).not.toContain("--wrap=auto");
84 + });
86 + it("renders markdown with glow when available", () => {
87 + const calls: Call[] = [];
88 + const result = loadFileContent(FILE_WITH_SHELL_CHARS, "/tmp", false, false, 72, true, deps({
89 + hasCommand: (cmd) => cmd === "glow",
90 + runCommand: recordingRunner(calls, { glow: "# Rendered" }),
91 + }));
93 + expect(result.renderedMarkdown).toBe(true);
94 + expect(result.lines).toEqual(["# Rendered"]);
95 + expect(calls[0]?.args).toEqual(["-s", "dark", "-w", "72", FILE_WITH_SHELL_CHARS]);
96 + });
98 + it("falls back to raw file read with line numbers", () => {
99 + const result = loadFileContent("/tmp/a.txt", "/tmp", false, false, 80, true, deps({
100 + readFile: () => "a\nb",
101 + }));
103 + expect(result).toEqual({
104 + renderedMarkdown: false,
105 + lines: [" 1 │ a", " 2 │ b"],
106 + });
107 + });
108 +});

pi/agent/extensions/files-widget/file-viewer.ts

Modified
3 3 * Based on tmustier/pi-extensions (files-widget). MIT License.
5 5 import { visibleWidth, wrapTextWithAnsi } from "@mariozechner/pi-tui";
6 -import { execSync } from "node:child_process";
6 +import { execFileSync } from "node:child_process";
7 7 import { readFileSync, statSync } from "node:fs";
9 -import { isGitRepo } from "./git";
10 -import { hasCommand, isMarkdownPath, stripLeadingEmptyLines } from "./utils";
9 +import { isGitRepo as defaultIsGitRepo } from "./git";
10 +import { hasCommand as defaultHasCommand, isMarkdownPath, stripLeadingEmptyLines } from "./utils";
12 +const DEFAULT_TERM_WIDTH = 80;
13 +const COMMAND_TIMEOUT_MS = 10_000;
14 +const RAW_LINE_NUMBER_WIDTH = 4;
12 15 const DIFF_CONTENT_PREFIXES = new Set(["+", "-", " "]);
17 +type CommandOptions = {
18 + cwd?: string;
19 + input?: string;
20 +};
22 +export type CommandRunner = (command: string, args: string[], options?: CommandOptions) => string;
24 +export type FileViewerDeps = {
25 + hasCommand?: (cmd: string) => boolean;
26 + isGitRepo?: (cwd: string) => boolean;
27 + runCommand?: CommandRunner;
28 + readFile?: (path: string, encoding: "utf-8") => string;
29 + stat?: typeof statSync;
30 + columns?: number;
31 +};
33 +export interface LoadedFileContent {
34 + lines: string[];
35 + renderedMarkdown: boolean;
38 +function runCommand(command: string, args: string[], options: CommandOptions = {}): string {
39 + return execFileSync(command, args, {
40 + cwd: options.cwd,
41 + encoding: "utf-8",
42 + timeout: COMMAND_TIMEOUT_MS,
43 + input: options.input,
44 + stdio: options.input === undefined ? "pipe" : ["pipe", "pipe", "pipe"],
45 + });
48 +function termWidth(width: number | undefined, deps: FileViewerDeps): number {
49 + return width || deps.columns || process.stdout.columns || DEFAULT_TERM_WIDTH;
14 52 function isDiffContentLine(line: string): boolean {
15 53 if (!line) return false;
16 54 if (!DIFF_CONTENT_PREFIXES.has(line[0])) return false;
20 58 function wrapLine(line: string, width: number): string[] {
21 - if (width <= 0 || line.length <= width) {
22 - return [line];
23 - }
59 + if (width <= 0 || line.length <= width) return [line];
24 61 const wrapped: string[] = [];
25 62 for (let i = 0; i < line.length; i += width) {
26 63 wrapped.push(line.slice(i, i + width));
31 68 function wrapDiffLines(lines: string[], width: number): string[] {
32 69 if (width <= 0) return lines;
33 71 const wrapped: string[] = [];
34 72 for (const line of lines) {
35 73 if (line.length <= width) {
36 74 wrapped.push(line);
37 75 continue;
39 - if (isDiffContentLine(line)) {
40 - const prefix = line[0];
41 - const content = line.slice(1);
42 - const contentWidth = Math.max(width - 1, 1);
43 - for (const chunk of wrapLine(content, contentWidth)) {
44 - wrapped.push(prefix + chunk);
45 - }
46 - } else {
78 + if (!isDiffContentLine(line)) {
47 79 wrapped.push(...wrapLine(line, width));
80 + continue;
81 + }
83 + const prefix = line[0];
84 + const contentWidth = Math.max(width - 1, 1);
85 + for (const chunk of wrapLine(line.slice(1), contentWidth)) {
86 + wrapped.push(prefix + chunk);
50 89 return wrapped;
53 92 function extractAnsiCode(str: string, pos: number): { length: number } | null {
54 93 if (pos >= str.length || str[pos] !== "\x1b") return null;
55 94 const next = str[pos + 1];
56 96 if (next === "[") {
57 97 let j = pos + 2;
58 98 while (j < str.length && !/[mGKHJ]/.test(str[j])) j++;
59 - if (j < str.length) return { length: j + 1 - pos };
60 - return null;
99 + return j < str.length ? { length: j + 1 - pos } : null;
62 - if (next === "]") {
102 + if (next === "]" || next === "_") {
63 103 let j = pos + 2;
64 104 while (j < str.length) {
65 105 if (str[j] === "\x07") return { length: j + 1 - pos };
66 106 if (str[j] === "\x1b" && str[j + 1] === "\\") return { length: j + 2 - pos };
69 - return null;
70 - }
71 - if (next === "_") {
72 - let j = pos + 2;
73 - while (j < str.length) {
74 - if (str[j] === "\x07") return { length: j + 1 - pos };
75 - if (str[j] === "\x1b" && str[j + 1] === "\\") return { length: j + 2 - pos };
76 - j++;
77 - }
78 - return null;
80 111 return null;
97 128 function splitByVisibleWidth(line: string, width: number): { prefix: string; rest: string } {
98 129 if (width <= 0) return { prefix: "", rest: line };
99 131 let visible = 0;
100 132 let i = 0;
101 133 while (i < line.length) {
104 136 i += ansi.length;
105 137 continue;
107 140 const charWidth = visibleWidth(line[i]);
108 141 if (visible + charWidth > width) break;
109 142 visible += charWidth;
121 154 i += ansi.length;
122 155 continue;
124 158 const char = line[i];
125 159 result += char >= "0" && char <= "9" ? " " : char;
126 160 i += 1;
149 183 function wrapDeltaLines(lines: string[], width: number): string[] {
150 184 if (width <= 0) return lines;
151 186 const wrapped: string[] = [];
152 - for (const line of lines) {
153 - wrapped.push(...wrapDeltaLine(line, width));
154 - }
187 + for (const line of lines) wrapped.push(...wrapDeltaLine(line, width));
155 188 return wrapped;
158 -export interface LoadedFileContent {
159 - lines: string[];
160 - renderedMarkdown: boolean;
191 +function commandErrorMessage(error: unknown): string {
192 + return error instanceof Error ? error.message : String(error);
195 +function readGitDiff(filePath: string, cwd: string, run: CommandRunner): string {
196 + const attempts: string[][] = [
197 + ["diff", "--no-color", "--", filePath],
198 + ["diff", "--no-color", "--cached", "--", filePath],
199 + ["diff", "--no-color", "HEAD", "--", filePath],
200 + ];
202 + for (const args of attempts) {
203 + const output = run("git", args, { cwd });
204 + if (output.trim()) return output;
206 + return "";
209 +function renderDelta(diffOutput: string, cwd: string, width: number, run: CommandRunner): LoadedFileContent | undefined {
210 + try {
211 + const output = run("delta", [
212 + "--no-gitconfig",
213 + `--width=${width}`,
214 + "--line-numbers",
215 + "--wrap-max-lines=unlimited",
216 + "--max-line-length=0",
217 + ], { cwd, input: diffOutput });
219 + return { lines: wrapDeltaLines(stripLeadingEmptyLines(output.split("\n")), width), renderedMarkdown: false };
220 + } catch {
221 + return undefined;
225 +function loadDiffContent(filePath: string, cwd: string, width: number, deps: Required<FileViewerDeps>): LoadedFileContent {
226 + try {
227 + const diffOutput = readGitDiff(filePath, cwd, deps.runCommand);
228 + if (!diffOutput.trim()) {
229 + return { lines: ["No diff available - file may be untracked or unchanged"], renderedMarkdown: false };
232 + if (deps.hasCommand("delta")) {
233 + const delta = renderDelta(diffOutput, cwd, width, deps.runCommand);
234 + if (delta) return delta;
237 + return { lines: wrapDiffLines(stripLeadingEmptyLines(diffOutput.split("\n")), width), renderedMarkdown: false };
238 + } catch (error) {
239 + return { lines: [`Diff error: ${commandErrorMessage(error)}`], renderedMarkdown: false };
243 +function renderMarkdownWithGlow(filePath: string, width: number, deps: Required<FileViewerDeps>): LoadedFileContent | undefined {
244 + if (!deps.hasCommand("glow")) return undefined;
246 + try {
247 + const output = deps.runCommand("glow", ["-s", "dark", "-w", String(width), filePath]);
248 + return output.trim()
249 + ? { lines: stripLeadingEmptyLines(output.split("\n")), renderedMarkdown: true }
250 + : undefined;
251 + } catch {
252 + return undefined;
256 +function renderWithBat(filePath: string, width: number, deps: Required<FileViewerDeps>): LoadedFileContent | undefined {
257 + if (!deps.hasCommand("bat")) return undefined;
259 + const common = ["--style=numbers", "--color=always", "--paging=never"];
260 + const attempts = [
261 + [...common, "--wrap=auto", `--terminal-width=${width}`, filePath],
262 + [...common, `--terminal-width=${width}`, filePath],
263 + ];
265 + for (const args of attempts) {
266 + try {
267 + return { lines: deps.runCommand("bat", args).split("\n"), renderedMarkdown: false };
268 + } catch {
269 + // Try next bat invocation, then fall back to raw file.
273 + return undefined;
276 +function loadRawFile(filePath: string, deps: Required<FileViewerDeps>): LoadedFileContent {
277 + const raw = deps.readFile(filePath, "utf-8");
278 + return {
279 + lines: raw.split("\n").map((line, i) => `${String(i + 1).padStart(RAW_LINE_NUMBER_WIDTH)} │ ${line}`),
280 + renderedMarkdown: false,
281 + };
284 +function withDefaults(deps: FileViewerDeps): Required<FileViewerDeps> {
285 + return {
286 + hasCommand: deps.hasCommand ?? defaultHasCommand,
287 + isGitRepo: deps.isGitRepo ?? defaultIsGitRepo,
288 + runCommand: deps.runCommand ?? runCommand,
289 + readFile: deps.readFile ?? readFileSync,
290 + stat: deps.stat ?? statSync,
291 + columns: deps.columns ?? process.stdout.columns ?? DEFAULT_TERM_WIDTH,
292 + };
163 295 export function loadFileContent(
166 298 diffMode: boolean,
167 299 hasChanges: boolean,
168 300 width?: number,
169 - renderMarkdown = true
301 + renderMarkdown = true,
302 + deps: FileViewerDeps = {},
170 303 ): LoadedFileContent {
171 - const isMarkdown = isMarkdownPath(filePath);
172 - const termWidth = width || process.stdout.columns || 80;
304 + const resolvedDeps = withDefaults(deps);
305 + const resolvedWidth = termWidth(width, resolvedDeps);
175 - try {
176 - if (statSync(filePath).isDirectory()) {
177 - return ["Directory selected - expand it in the file tree instead of opening it."];
178 - }
179 - } catch {
180 - // Ignore stat errors and fall through to normal handling
308 + if (resolvedDeps.stat(filePath).isDirectory()) {
309 + return { lines: ["Directory selected - expand it in the file tree instead of opening it."], renderedMarkdown: false };
311 + } catch {
312 + // Fall through to normal file handling; read/bat/glow will surface useful errors.
315 + try {
316 + if (diffMode && hasChanges && resolvedDeps.isGitRepo(cwd)) {
317 + return loadDiffContent(filePath, cwd, resolvedWidth, resolvedDeps);
183 - if (diffMode && hasChanges && isGitRepo(cwd)) {
184 - try {
185 - // Try different diff strategies
186 - let diffOutput = "";
188 - // First try: unstaged changes
189 - const unstaged = execSync(`git diff --no-color -- "${filePath}"`, { cwd, encoding: "utf-8", timeout: 10000, stdio: "pipe" });
190 - if (unstaged.trim()) {
191 - diffOutput = unstaged;
192 - } else {
193 - // Second try: staged changes
194 - const staged = execSync(`git diff --no-color --cached -- "${filePath}"`, { cwd, encoding: "utf-8", timeout: 10000, stdio: "pipe" });
195 - if (staged.trim()) {
196 - diffOutput = staged;
197 - } else {
198 - // Third try: diff against HEAD (for new files that are staged)
199 - const headDiff = execSync(`git diff --no-color HEAD -- "${filePath}"`, { cwd, encoding: "utf-8", timeout: 10000, stdio: "pipe" });
200 - if (headDiff.trim()) {
201 - diffOutput = headDiff;
202 - }
203 - }
204 - }
206 - if (!diffOutput.trim()) {
207 - return { lines: ["No diff available - file may be untracked or unchanged"], renderedMarkdown: false };
208 - }
210 - if (hasCommand("delta")) {
211 - // Pipe through delta with line numbers for better readability
212 - try {
213 - const deltaOutput = execSync(
214 - `delta --no-gitconfig --width=${termWidth} --line-numbers --wrap-max-lines=unlimited --max-line-length=0`,
215 - {
216 - cwd,
217 - encoding: "utf-8",
218 - timeout: 10000,
219 - input: diffOutput,
220 - stdio: ["pipe", "pipe", "pipe"],
221 - }
222 - );
223 - return { lines: wrapDeltaLines(stripLeadingEmptyLines(deltaOutput.split("\n")), termWidth), renderedMarkdown: false };
224 - } catch {
225 - // Fall back to raw diff
226 - }
227 - }
229 - return { lines: wrapDiffLines(stripLeadingEmptyLines(diffOutput.split("\n")), termWidth), renderedMarkdown: false };
230 - } catch (e: any) {
231 - return { lines: [`Diff error: ${e.message}`], renderedMarkdown: false };
232 - }
320 + if (isMarkdownPath(filePath) && renderMarkdown) {
321 + const markdown = renderMarkdownWithGlow(filePath, resolvedWidth, resolvedDeps);
322 + if (markdown) return markdown;
235 - if (isMarkdown && renderMarkdown && hasCommand("glow")) {
236 - try {
237 - const output = execSync(`glow -s dark -w ${termWidth} "${filePath}"`, { encoding: "utf-8", timeout: 10000 });
238 - if (output.trim()) {
239 - return { lines: stripLeadingEmptyLines(output.split("\n")), renderedMarkdown: true };
240 - }
241 - } catch {
242 - // Fall through to bat
243 - }
244 - }
325 + const bat = renderWithBat(filePath, resolvedWidth, resolvedDeps);
326 + if (bat) return bat;
246 - if (hasCommand("bat")) {
247 - try {
248 - return {
249 - lines: execSync(
250 - `bat --style=numbers --color=always --paging=never --wrap=auto --terminal-width=${termWidth} "${filePath}"`,
251 - { encoding: "utf-8", timeout: 10000 }
252 - ).split("\n"),
253 - renderedMarkdown: false,
254 - };
255 - } catch {
256 - try {
257 - return {
258 - lines: execSync(
259 - `bat --style=numbers --color=always --paging=never --terminal-width=${termWidth} "${filePath}"`,
260 - { encoding: "utf-8", timeout: 10000 }
261 - ).split("\n"),
262 - renderedMarkdown: false,
263 - };
264 - } catch {
265 - // Fall through to raw file read
266 - }
267 - }
268 - }
270 - const raw = readFileSync(filePath, "utf-8");
271 - return {
272 - lines: raw.split("\n").map((line, i) => `${String(i + 1).padStart(4)} │ ${line}`),
273 - renderedMarkdown: false,
274 - };
275 - } catch (e: any) {
276 - return { lines: [`Error loading file: ${e.message}`], renderedMarkdown: false };
328 + return loadRawFile(filePath, resolvedDeps);
329 + } catch (error) {
330 + return { lines: [`Error loading file: ${commandErrorMessage(error)}`], renderedMarkdown: false };

pi/agent/extensions/files-widget/package.json

Modified
4 4 "name": "@bugabinga/pi-ext-files-widget",
5 5 "version": "0.1.0",
6 6 "private": true,
7 7 "type": "module",
8 - "main": "index.ts"
8 + "main": "index.ts",
9 + "scripts": {
10 + "test": "bun test ./__tests__/*.test.ts",
11 + "test:watch": "bun test ./__tests__/*.test.ts --watch"
12 + },
13 + "devDependencies": {
14 + "@mariozechner/pi-tui": "^0.72.1"
15 + }