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",
40 43 "extensions/footer": {
41 44 "name": "@bugabinga/pi-ext-footer",
pi/agent/extensions/files-widget/__tests__/file-viewer.test.ts
Addednew 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 {
19 + hasCommand: ()
=> false,
20 + isGitRepo: ()
=> false,
21 + runCommand: ()
=> {
throw new Error(
"unexpected command"); },
22 + readFile: ()
=> "hello\nworld",
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}`);
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");
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",
59 + expect(result.renderedMarkdown).
toBe(
false);
60 + expect(result.lines.
join(
"\n")).
toContain(
"new line");
61 + expect(calls[
0]).
toEqual({
63 + args: [
"diff",
"--no-color",
"--", FILE_WITH_SHELL_CHARS],
67 + expect(calls[
1]?.command).
toBe(
"delta");
68 + expect(calls[
1]?.
input).
toBe(diff);
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;",
81 + expect(result.lines).
toEqual([
"1 │ const x = 1;"]);
82 + expect(calls).
toHaveLength(
2);
83 + expect(calls[
1]?.args).not.
toContain(
"--wrap=auto");
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" }),
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]);
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",
103 + expect(result).
toEqual({
104 + renderedMarkdown:
false,
105 + lines: [
" 1 │ a",
" 2 │ b"],
pi/agent/extensions/files-widget/file-viewer.ts
Modified 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 = {
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;
33 +export interface LoadedFileContent {
35 + renderedMarkdown
: boolean;
38 +function runCommand(command
: string, args
: string[], options
: CommandOptions = {})
: string {
39 + return execFileSync(command, args, {
42 + timeout: COMMAND_TIMEOUT_MS,
43 + input: options.
input,
44 + stdio: options.
input === undefined ? "pipe" : [
"pipe",
"pipe",
"pipe"],
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) {
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);
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);
78 + if (
!isDiffContentLine(line)) {
47 79 wrapped.
push(
...wrapLine(line, width));
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);
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
=== "[") {
58 98 while (j
< str.
length && !/[mGKHJ]/.
test(str[j])) j
++;
59 - if (j
< str.
length)
return { length: j
+ 1 - pos };
99 + return j
< str.
length ? { length: j
+ 1 - pos }
: null;
102 + if (next
=== "]" || next
=== "_") {
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 };
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 };
97 128 function splitByVisibleWidth(line
: string, width
: number)
: { prefix
: string; rest
: string } {
98 129 if (width
<= 0)
return { prefix:
"", rest: line };
101 133 while (i
< line.
length) {
104 136 i
+= ansi.
length;
107 140 const charWidth
= visibleWidth(line[i]);
108 141 if (visible
+ charWidth
> width)
break;
109 142 visible
+= charWidth;
121 154 i
+= ansi.
length;
124 158 const char
= line[i];
125 159 result
+= char
>= "0" && char
<= "9" ? " " : char;
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));
187 + for (
const line
of lines) wrapped.
push(
...wrapDeltaLine(line, width));
158 -export interface LoadedFileContent {
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],
202 + for (
const args
of attempts) {
203 + const output
= run(
"git", args, { cwd });
204 + if (output.
trim())
return output;
209 +function renderDelta(diffOutput
: string, cwd
: string, width
: number, run
: CommandRunner)
: LoadedFileContent | undefined {
211 + const output
= run(
"delta", [
213 + `--width=${width}`,
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 };
225 +function loadDiffContent(filePath
: string, cwd
: string, width
: number, deps
: Required<
FileViewerDeps>)
: LoadedFileContent {
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 };
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;
247 + const output
= deps.
runCommand(
"glow", [
"-s",
"dark",
"-w",
String(width), filePath]);
248 + return output.
trim()
249 + ? { lines:
stripLeadingEmptyLines(output.
split(
"\n")), renderedMarkdown:
true }
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"];
261 + [
...common,
"--wrap=auto",
`--terminal-width=${width}`, filePath],
262 + [
...common,
`--terminal-width=${width}`, filePath],
265 + for (
const args
of attempts) {
267 + return { lines: deps.
runCommand(
"bat", args).
split(
"\n"), renderedMarkdown:
false };
276 +function loadRawFile(filePath
: string, deps
: Required<
FileViewerDeps>)
: LoadedFileContent {
277 + const raw
= deps.
readFile(filePath,
"utf-8");
279 + lines: raw.
split(
"\n").
map((line, i)
=> `${String(i + 1).padStart(RAW_LINE_NUMBER_WIDTH)} │ ${line}`),
280 + renderedMarkdown:
false,
284 +function withDefaults(deps
: FileViewerDeps)
: Required<
FileViewerDeps> {
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,
163 295 export function loadFileContent(
166 298 diffMode: boolean,
167 299 hasChanges: boolean,
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);
176 - if (
statSync(filePath).
isDirectory()) {
177 - return [
"Directory selected - expand it in the file tree instead of opening it."];
308 + if (resolvedDeps.
stat(filePath).
isDirectory()) {
309 + return { lines: [
"Directory selected - expand it in the file tree instead of opening it."], renderedMarkdown:
false };
316 + if (diffMode
&& hasChanges
&& resolvedDeps.
isGitRepo(cwd)) {
317 + return loadDiffContent(filePath, cwd, resolvedWidth, resolvedDeps);
183 - if (diffMode
&& hasChanges
&& isGitRepo(cwd)) {
186 - let diffOutput
= "";
189 - const unstaged
= execSync(
`git diff --no-color -- "${filePath}"`, { cwd, encoding:
"utf-8", timeout:
10000, stdio:
"pipe" });
190 - if (unstaged.
trim()) {
191 - diffOutput
= unstaged;
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;
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;
206 - if (
!diffOutput.
trim()) {
207 - return { lines: [
"No diff available - file may be untracked or unchanged"], renderedMarkdown:
false };
210 - if (
hasCommand(
"delta")) {
213 - const deltaOutput
= execSync(
214 - `delta --no-gitconfig --width=${termWidth} --line-numbers --wrap-max-lines=unlimited --max-line-length=0`,
220 - stdio: [
"pipe",
"pipe",
"pipe"],
223 - return { lines:
wrapDeltaLines(
stripLeadingEmptyLines(deltaOutput.
split(
"\n")), termWidth), renderedMarkdown:
false };
229 - return { lines:
wrapDiffLines(
stripLeadingEmptyLines(diffOutput.
split(
"\n")), termWidth), renderedMarkdown:
false };
231 - return { lines: [
`Diff error: ${e.message}`], renderedMarkdown:
false };
320 + if (
isMarkdownPath(filePath)
&& renderMarkdown) {
321 + const markdown
= renderMarkdownWithGlow(filePath, resolvedWidth, resolvedDeps);
322 + if (markdown)
return markdown;
235 - if (isMarkdown
&& renderMarkdown
&& hasCommand(
"glow")) {
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 };
325 + const bat
= renderWithBat(filePath, resolvedWidth, resolvedDeps);
326 + if (bat)
return bat;
246 - if (
hasCommand(
"bat")) {
250 - `bat --style=numbers --color=always --paging=never --wrap=auto --terminal-width=${termWidth} "${filePath}"`,
251 - { encoding:
"utf-8", timeout:
10000 }
253 - renderedMarkdown:
false,
259 - `bat --style=numbers --color=always --paging=never --terminal-width=${termWidth} "${filePath}"`,
260 - { encoding:
"utf-8", timeout:
10000 }
262 - renderedMarkdown:
false,
270 - const raw
= readFileSync(filePath,
"utf-8");
272 - lines: raw.
split(
"\n").
map((line, i)
=> `${String(i + 1).padStart(4)} │ ${line}`),
273 - renderedMarkdown:
false,
276 - return { lines: [
`Error loading file: ${e.message}`], renderedMarkdown:
false };
328 + return loadRawFile(filePath, resolvedDeps);
330 + return { lines: [
`Error loading file: ${commandErrorMessage(error)}`], renderedMarkdown:
false };
pi/agent/extensions/files-widget/package.json
Modified4 4 "name":
"@bugabinga/pi-ext-files-widget",
10 + "test":
"bun test ./__tests__/*.test.ts",
11 + "test:watch":
"bun test ./__tests__/*.test.ts --watch" 13 + "devDependencies": {
14 + "@mariozechner/pi-tui":
"^0.72.1"