UNPKG

codetainer

Version:

A clean and simple CLI to manage and store code snippets with ease.

52 lines (46 loc) 1.58 kB
import fs from "fs"; import os from "os"; import path from "path"; import chalk from "chalk"; import { loadSnippets, saveSnippets } from "../utils/snippetStore.js"; import { getExt } from "../utils/languageUtils.js"; import { openFile } from "../utils/openFile.js"; export function registerWatchCommand(program) { program .command("watch <snippetName>") .description("Watch and edit a snippet") .action((name) => { const snippets = loadSnippets(); const snippet = snippets[name]; if (!snippet) { console.log(chalk.red(`❌ Snippet "${name}" not found.`)); return; } const tmpPath = path.join( os.tmpdir(), `${name}-snippet.${getExt(snippet.language)}` ); fs.writeFileSync(tmpPath, snippet.code); console.log( chalk.green(`👀 Watching "${name}" in VS Code or default editor...`) ); openFile(tmpPath); let debounce; fs.watch(tmpPath, { encoding: "utf-8" }, (eventType) => { if (eventType === "change") { clearTimeout(debounce); debounce = setTimeout(() => { const updatedCode = fs.readFileSync(tmpPath, "utf-8"); if (updatedCode !== snippet.code) { snippet.code = updatedCode; snippets[name] = snippet; saveSnippets(snippets); console.log( chalk.blue(`💾 Snippet "${name}" updated from editor.`) ); } }, 300); } }); }); }