From 73ca51f45769d3802c1afba2ab7e32600a85a656 Mon Sep 17 00:00:00 2001 From: Chapman Pendery Date: Sat, 7 Oct 2023 19:14:44 -0700 Subject: [PATCH] feat: add command caching and loading for history injection Signed-off-by: Chapman Pendery --- src/commands/root.ts | 9 +++++++++ src/index.ts | 1 + src/utils/cache.ts | 21 +++++++++++++++++++++ 3 files changed, 31 insertions(+) create mode 100644 src/utils/cache.ts diff --git a/src/commands/root.ts b/src/commands/root.ts index 9675b82..d31b4fc 100644 --- a/src/commands/root.ts +++ b/src/commands/root.ts @@ -1,5 +1,6 @@ import { render } from "../ui/ui-root.js"; import { executeShellCommandTTY } from "../runtime/utils.js"; +import { saveCommand, loadCommand } from "../utils/cache.js"; const shells = ["bash", "powershell", "pwsh"]; export const supportedShells = shells.join(", "); @@ -7,9 +8,15 @@ export const supportedShells = shells.join(", "); type RootCommandOptions = { shell: string | undefined; command: string | undefined; + history: boolean | undefined; }; export const action = async (options: RootCommandOptions) => { + if (options.history) { + process.stdout.write(await loadCommand()); + process.exit(0); + } + const shell = options.shell ?? ""; if (!shells.includes(shell)) { console.error(`Unsupported shell: '${shell}', supported shells: ${supportedShells}`); @@ -17,6 +24,8 @@ export const action = async (options: RootCommandOptions) => { } const commandToExecute = await render(options.command); + await saveCommand(commandToExecute); + const result = await executeShellCommandTTY(shell, commandToExecute); if (result.code) { process.exit(result.code); diff --git a/src/index.ts b/src/index.ts index 01fa2ee..cf030db 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ program .version("0.0.0", "-v, --version", "output the current version") .option("-s, --shell ", `shell to use for command execution, supported shells: ${supportedShells}`) .option("-c, --command ", "command to use as initial input") + .option("--history", "get the last command execute") .action(action); program.addCommand(bind); diff --git a/src/utils/cache.ts b/src/utils/cache.ts new file mode 100644 index 0000000..2cb88f8 --- /dev/null +++ b/src/utils/cache.ts @@ -0,0 +1,21 @@ +import os from "node:os"; +import path from "node:path"; +import fsAsync from "node:fs/promises"; +import fs from "node:fs"; + +const folderPath = path.join(os.homedir(), ".clac"); +const cachePath = path.join(os.homedir(), ".clac", "clac.cache"); + +export const saveCommand = async (command: string) => { + if (!fs.existsSync(folderPath)) { + await fsAsync.mkdir(folderPath); + } + await fsAsync.writeFile(cachePath, command); +}; + +export const loadCommand = async (): Promise => { + if (!fs.existsSync(folderPath)) { + await fsAsync.mkdir(folderPath); + } + return fsAsync.readFile(cachePath, { encoding: "utf-8" }); +};