From f71cd1fd46e4690ea0f71ce938a7d658f8be15ea Mon Sep 17 00:00:00 2001 From: Lawrence Lagerlof Date: Wed, 3 Jul 2024 08:53:40 -0300 Subject: [PATCH] Add executed commands to shell history --- src/helpers/shell-history.ts | 52 ++++++++++++++++++++++++++++++++++++ src/prompt.ts | 14 ++++++---- 2 files changed, 61 insertions(+), 5 deletions(-) create mode 100644 src/helpers/shell-history.ts diff --git a/src/helpers/shell-history.ts b/src/helpers/shell-history.ts new file mode 100644 index 0000000..b72c732 --- /dev/null +++ b/src/helpers/shell-history.ts @@ -0,0 +1,52 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +// Function to get the history file based on the shell +function getHistoryFile(): string | null { + const shell = process.env.SHELL || ''; + const homeDir = os.homedir(); + + switch (path.basename(shell)) { + case 'bash': + case 'sh': + return path.join(homeDir, '.bash_history'); + case 'zsh': + return path.join(homeDir, '.zsh_history'); + case 'fish': + return path.join(homeDir, '.local', 'share', 'fish', 'fish_history'); + case 'ksh': + return path.join(homeDir, '.ksh_history'); + case 'tcsh': + return path.join(homeDir, '.history'); + default: + return null; + } +} + +// Function to get the last command from the history file +function getLastCommand(historyFile: string): string | null { + try { + const data = fs.readFileSync(historyFile, 'utf8'); + const commands = data.trim().split('\n'); + return commands[commands.length - 1]; + } catch (err) { + // Ignore any errors + return null; + } +} + +// Function to append the command to the history file if it's not the same as the last command +export function appendToShellHistory(command: string): void { + const historyFile = getHistoryFile(); + if (historyFile) { + const lastCommand = getLastCommand(historyFile); + if (lastCommand !== command) { + fs.appendFile(historyFile, `${command}\n`, (err) => { + if (err) { + // Ignore any errors + } + }); + } + } +} diff --git a/src/prompt.ts b/src/prompt.ts index aed70c7..dc80d22 100644 --- a/src/prompt.ts +++ b/src/prompt.ts @@ -11,6 +11,7 @@ import { projectName } from './helpers/constants'; import { KnownError } from './helpers/error'; import clipboardy from 'clipboardy'; import i18n from './helpers/i18n'; +import { appendToShellHistory } from './helpers/shell-history'; const init = async () => { try { @@ -38,12 +39,15 @@ const sample = (arr: T[]): T | undefined => { async function runScript(script: string) { p.outro(`${i18n.t('Running')}: ${script}`); console.log(''); - await execaCommand(script, { - stdio: 'inherit', - shell: process.env.SHELL || true, - }).catch(() => { + try { + await execaCommand(script, { + stdio: 'inherit', + shell: process.env.SHELL || true, + }); + appendToShellHistory(script); + } catch (error) { // Nothing needed, it'll output to stderr - }); + } } async function getPrompt(prompt?: string) {