pdf-tools/cli/index.ts
2025-04-24 21:40:59 -06:00

86 lines
2.5 KiB
TypeScript

import { getAsciiArt } from "../util/asciiArt.ts";
import { toCase } from "util/caseManagement.ts";
import { ArgParser } from "./argParser.ts";
import { colorize } from "./colorize.ts";
import { selectMenuInteractive } from "./selectMenu.ts";
import { TerminalBlock, TerminalLayout } from "./TerminalLayout.ts";
export class PdfToolsCli {
private tools: Map<string, ITool> = new Map();
private terminalLayout = new TerminalLayout();
private args = ArgParser.parse(Deno.args);
async importTools(tools?: string) {
tools = tools?.replace(/\/$/, "").replace(/^\.?\//, "") || "tools";
for (const toolfile of Deno.readDirSync(tools)) {
if (toolfile.isFile) {
const tool = await import(
Deno.cwd() + "/" + tools + "/" + toolfile.name
);
if (tool.default) {
this.tools.set(
toCase(toolfile.name.replace(".ts", ""), "title"),
tool.default,
);
}
}
}
}
private async banana() {
const asciiArt = await getAsciiArt("banana");
console.log(colorize(asciiArt, "yellow"));
}
private help() {
console.log("BearMetal PDF CLI");
}
public async run() {
try {
const lines: string[] = [];
for (const t of ["bearmetal:porple", "pdftools:cyan"]) {
const [name, color] = t.split(":");
const asciiArt = await getAsciiArt(name);
lines.push(...colorize(asciiArt, color).split("\n"));
}
const titleBlock = new TerminalBlock();
this.terminalLayout.register("title", titleBlock);
const bodyBlock = new TerminalBlock();
this.terminalLayout.register("body", bodyBlock);
titleBlock.setFixedHeight(lines.length);
titleBlock.setLines(lines);
if (Deno.args.length === 0) {
// console.log(
// colorize("No tool specified. Importing all tools...", "gray"),
// );
await this.importTools();
}
this.toolMenu();
} finally {
this.terminalLayout.clearAll();
}
}
private async toolMenu() {
const tools = this.tools.keys().toArray();
const bodyBlock = this.terminalLayout.getBlock("body");
const selected = await selectMenuInteractive("Choose a tool", tools, {
terminalBlock: bodyBlock,
});
bodyBlock.clear();
if (!selected) return;
await this.runTool(selected);
this.toolMenu();
}
private async runTool(toolName: string) {
const tool = this.tools.get(toolName);
if (tool) {
await tool.run();
await tool.done?.();
}
}
}