feat: add command caching and loading for history injection

Signed-off-by: Chapman Pendery <cpendery@vt.edu>
This commit is contained in:
Chapman Pendery
2023-10-07 19:14:44 -07:00
parent 31ca9b28a2
commit 73ca51f457
3 changed files with 31 additions and 0 deletions
+9
View File
@@ -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);
+1
View File
@@ -11,6 +11,7 @@ program
.version("0.0.0", "-v, --version", "output the current version")
.option("-s, --shell <shell>", `shell to use for command execution, supported shells: ${supportedShells}`)
.option("-c, --command <commmand>", "command to use as initial input")
.option("--history", "get the last command execute")
.action(action);
program.addCommand(bind);
+21
View File
@@ -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<string> => {
if (!fs.existsSync(folderPath)) {
await fsAsync.mkdir(folderPath);
}
return fsAsync.readFile(cachePath, { encoding: "utf-8" });
};