Skip to content

Commit

Permalink
FE-6024 Implement shell history
Browse files Browse the repository at this point in the history
  • Loading branch information
ptpaterson authored and echo-bravo-yahoo committed Nov 23, 2024
1 parent 40d10bd commit f3486f1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
41 changes: 41 additions & 0 deletions src/commands/shell.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
//@ts-check

import repl from "node:repl";
import path from "node:path";
import fs from "node:fs";
import os from "node:os";

import { container } from "../cli.mjs";
import {
// ensureDbScopeClient,
commonConfigurableQueryOptions,
} from "../lib/command-helpers.mjs";
import { performQuery } from "./eval.mjs";
import { dirExists, fileExists } from "../lib/file-util.mjs";

async function doShell(argv) {
const logger = container.resolve("logger");
Expand All @@ -16,6 +20,16 @@ async function doShell(argv) {
if (argv.dbPath) logger.stdout(`Starting shell for database ${argv.dbPath}`);
logger.stdout("Type Ctrl+D or .exit to exit the shell");

// Setup history file
const historyDir = path.join(os.homedir(), ".fauna");
if (!dirExists(historyDir)) {
fs.mkdirSync(historyDir, { recursive: true });
}
const historyFile = path.join(historyDir, "history");
if (!fileExists(historyFile)) {
fs.writeFileSync(historyFile, "{}");
}

/** @type {import('node:repl').ReplOptions} */
const replArgs = {
prompt: `${argv.db_path || ""}> `,
Expand All @@ -30,6 +44,14 @@ async function doShell(argv) {
};

const shell = repl.start(replArgs);

// Setup history
shell.setupHistory(historyFile, (err) => {
if (err) {
logger.stderr(`Error setting up history: ${err.message}`);
}
});

// eslint-disable-next-line no-console
shell.on("error", console.error);

Expand All @@ -55,6 +77,25 @@ async function doShell(argv) {
shell.prompt();
},
},
{
cmd: "clearhistory",
help: "Clear command history",
action: async () => {
try {
await fs.writeFileSync(historyFile, '');
logger.stdout('History cleared');
// Reinitialize history
shell.setupHistory(historyFile, (err) => {
if (err) {
logger.stderr(`Error reinitializing history: ${err.message}`);
}
});
} catch (err) {
logger.stderr(`Error clearing history: ${err.message}`);
}
shell.prompt();
},
}
].forEach(({ cmd, ...cmdOptions }) => shell.defineCommand(cmd, cmdOptions));

return completionPromise;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/file-util.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export function dirIsWriteable(path) {
* @param {string} path - The path to the file.
* @returns {boolean} - Returns true if the file exists, otherwise false.
*/
function fileExists(path) {
export function fileExists(path) {
try {
fs.readFileSync(fixPath(path));
return true;
Expand Down

0 comments on commit f3486f1

Please sign in to comment.