// Save a document: writes the words it's given on stdin to " .md" in a folder, with the title as its // heading. A file of that name already there is left alone: this one gets " 2", " 3" and so on. Run it from its form // in CLIDE, or here: // echo "Some words" | bun save-a-document.ts --title "Notes" --folder ~/Documents // With no --folder, it saves in Documents/CLIDE Reports in your home folder. import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { parseArgs } from "node:util"; const { values } = parseArgs({ args: process.argv.slice(2), options: { title: { type: "string" }, folder: { type: "string" } } }); const title = (values.title ?? "").trim() || "Document"; const folder = values.folder?.trim() || join(homedir(), "Documents", "CLIDE Reports"); const words = (await Bun.stdin.text()).trim(); if (!words) { console.error("There are no words to save."); process.exit(2); } const now = new Date(); const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`; // A name every OS takes: no slashes, colons or the like, and not too long. const safe = title.replace(/[\\/:*?"<>|\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 80) || "Document"; mkdirSync(folder, { recursive: true }); let path = join(folder, `${day} ${safe}.md`); for (let n = 2; existsSync(path); n++) path = join(folder, `${day} ${safe} ${n}.md`); const heading = /^#\s/.test(words) ? "" : `# ${title}\n\n`; writeFileSync(path, `${heading}${words}\n`, { flag: "wx" }); console.log(`Saved to ${path}`);