repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/q/editor.ts

Raw
import { spawnSync } from "node:child_process";
import { readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

export function openEditor(initial: string): string | undefined {
	const path = join(
		tmpdir(),
		`pi-q-${Date.now()}-${Math.random().toString(16).slice(2)}.txt`,
	);
	writeFileSync(path, initial, "utf8");
	try {
		const editor = parseEditorCommand(
			process.env.VISUAL || process.env.EDITOR || "vi",
		);
		if (!editor) return undefined;
		const result = spawnSync(editor.command, [...editor.args, path], {
			stdio: "inherit",
		});
		if (result.error || result.status !== 0) return undefined;
		return readFileSync(path, "utf8").trim() || undefined;
	} finally {
		try {
			unlinkSync(path);
		} catch {}
	}
}

export function parseEditorCommand(
	input: string,
): { command: string; args: string[] } | undefined {
	const parts = splitCommandLine(input.trim());
	const command = parts[0];
	if (!command) return undefined;
	return { command, args: parts.slice(1) };
}

function splitCommandLine(input: string): string[] {
	const parts: string[] = [];
	let current = "";
	let quote: "'" | '"' | undefined;
	let escaping = false;

	for (const char of input) {
		if (escaping) {
			current += char;
			escaping = false;
			continue;
		}
		if (char === "\\" && quote !== "'") {
			escaping = true;
			continue;
		}
		if ((char === "'" || char === '"') && !quote) {
			quote = char;
			continue;
		}
		if (char === quote) {
			quote = undefined;
			continue;
		}
		if (/\s/.test(char) && !quote) {
			if (current) parts.push(current);
			current = "";
			continue;
		}
		current += char;
	}
	if (escaping) current += "\\";
	if (current) parts.push(current);
	return parts;
}