@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
193 lines • 9.56 kB
JavaScript
/**
* Diff Extension
*
* /diff command shows modified/deleted/new files from git status and opens
* the selected file in VS Code's diff view.
*/
import { Container, Key, matchesKey, SelectList, Text } from "@earendil-works/pi-tui";
import { DynamicBorder } from "../../../modes/interactive/components/dynamic-border.js";
export default function (pi) {
pi.registerCommand("diff", {
description: "Show git changes and open in VS Code diff view",
handler: async (_args, ctx) => {
if (!ctx.hasUI) {
ctx.ui.notify("No UI available", "error");
return;
}
// Get changed files from git status
const result = await pi.exec("git", ["status", "--porcelain"], { cwd: ctx.cwd });
if (result.code !== 0) {
ctx.ui.notify(`git status failed: ${result.stderr}`, "error");
return;
}
if (!result.stdout?.trim()) {
ctx.ui.notify("No changes in working tree", "info");
return;
}
// Parse git status output
// Format: XY filename (where XY is two-letter status, then space, then filename)
const lines = result.stdout.split("\n");
const files = [];
for (const line of lines) {
if (line.length < 4)
continue; // Need at least "XY f"
const status = line.slice(0, 2);
const file = line.slice(2).trimStart();
// Translate status codes to short labels
let statusLabel;
if (status.includes("M"))
statusLabel = "M";
else if (status.includes("A"))
statusLabel = "A";
else if (status.includes("D"))
statusLabel = "D";
else if (status.includes("?"))
statusLabel = "?";
else if (status.includes("R"))
statusLabel = "R";
else if (status.includes("C"))
statusLabel = "C";
else
statusLabel = status.trim() || "~";
files.push({ status: statusLabel, statusLabel, file });
}
if (files.length === 0) {
ctx.ui.notify("No changes found", "info");
return;
}
const WINDOWS_UNSAFE_CMD_CHARS_RE = /[&|<>^%\r\n]/;
const quoteCmdArg = (value) => `"${value.replace(/"/g, '""')}"`;
const openWithCode = async (file) => {
if (process.platform === "win32") {
if (WINDOWS_UNSAFE_CMD_CHARS_RE.test(file)) {
ctx.ui.notify(`Refusing to open ${file}: path contains Windows cmd metacharacters (& | < > ^ % or newline).`, "error");
return null;
}
// VS Code's --goto parser rejects drive-letter paths (and still exits 0), so pass a plain file argument.
const commandLine = `code ${quoteCmdArg(file)}`;
return pi.exec("cmd", ["/d", "/s", "/c", commandLine], { cwd: ctx.cwd });
}
return pi.exec("code", ["-g", file], { cwd: ctx.cwd });
};
// `code` can print a usage error and still exit 0 (senpi#2646), so stderr on success is reported too.
const reportOpen = (file, openResult) => {
const openStderr = openResult.stderr.trim();
if (openResult.code !== 0) {
ctx.ui.notify(`Failed to open ${file} (exit ${openResult.code})${openStderr ? `: ${openStderr}` : ""}`, "error");
}
else if (openStderr) {
ctx.ui.notify(`code reported a problem opening ${file}: ${openStderr}`, "warning");
}
};
const openSelected = async (fileInfo) => {
try {
// Open in VS Code diff view.
// For untracked files, git difftool won't work, so fall back to just opening the file.
if (fileInfo.status === "?") {
const openResult = await openWithCode(fileInfo.file);
if (!openResult)
return;
reportOpen(fileInfo.file, openResult);
return;
}
const diffResult = await pi.exec("git", ["difftool", "-y", "--tool=vscode", fileInfo.file], {
cwd: ctx.cwd,
});
if (diffResult.code !== 0) {
const diffStderr = diffResult.stderr.trim();
ctx.ui.notify(`Failed to show diff with vscode for ${fileInfo.file} (exit ${diffResult.code})${diffStderr ? `: ${diffStderr}` : ""}`, "error");
ctx.ui.notify("Troubleshooting: check git difftool config (e.g. `git config --get difftool.vscode.cmd`).", "info");
const openResult = await openWithCode(fileInfo.file);
if (!openResult)
return;
reportOpen(fileInfo.file, openResult);
}
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.ui.notify(`Failed to open ${fileInfo.file}: ${message}`, "error");
}
};
// Show file picker with SelectList
await ctx.ui.custom((tui, theme, _kb, done) => {
const container = new Container();
// Top border
container.addChild(new DynamicBorder((s) => theme.fg("accent", s)));
// Title
container.addChild(new Text(theme.fg("accent", theme.bold(" Select file to diff")), 0, 0));
// Build select items with colored status
const filesByValue = new Map();
const items = files.map((f, i) => {
const key = String(i);
filesByValue.set(key, f);
let statusColor;
switch (f.status) {
case "M":
statusColor = theme.fg("warning", f.status);
break;
case "A":
statusColor = theme.fg("success", f.status);
break;
case "D":
statusColor = theme.fg("error", f.status);
break;
case "?":
statusColor = theme.fg("muted", f.status);
break;
default:
statusColor = theme.fg("dim", f.status);
}
return {
value: key,
label: `${statusColor} ${f.file}`,
};
});
const visibleRows = Math.min(files.length, 15);
let currentIndex = 0;
const selectList = new SelectList(items, visibleRows, {
selectedPrefix: (t) => theme.fg("accent", t),
selectedText: (t) => t, // Keep existing colors
description: (t) => theme.fg("muted", t),
scrollInfo: (t) => theme.fg("dim", t),
noMatch: (t) => theme.fg("warning", t),
});
selectList.onSelect = (item) => {
const fileInfo = filesByValue.get(item.value);
if (fileInfo)
void openSelected(fileInfo);
};
selectList.onCancel = () => done();
selectList.onSelectionChange = (item) => {
currentIndex = items.indexOf(item);
};
container.addChild(selectList);
// Help text
container.addChild(new Text(theme.fg("dim", " ↑↓ navigate • ←→ page • enter open • esc close"), 0, 0));
// Bottom border
container.addChild(new DynamicBorder((s) => theme.fg("accent", s)));
return {
render: (w) => container.render(w),
invalidate: () => container.invalidate(),
handleInput: (data) => {
// Add paging with left/right
if (matchesKey(data, Key.left)) {
// Page up - clamp to 0
currentIndex = Math.max(0, currentIndex - visibleRows);
selectList.setSelectedIndex(currentIndex);
}
else if (matchesKey(data, Key.right)) {
// Page down - clamp to last
currentIndex = Math.min(items.length - 1, currentIndex + visibleRows);
selectList.setSelectedIndex(currentIndex);
}
else {
selectList.handleInput(data);
}
tui.requestRender();
},
};
});
},
});
}
//# sourceMappingURL=diff.js.map