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 b72d596..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) { @@ -120,7 +124,6 @@ export async function prompt({ spin.stop(`${i18n.t('Your script')}:`); console.log(''); const script = await readScript(process.stdout.write.bind(process.stdout)); - console.log('script', script); console.log(''); console.log(''); console.log(dim('•'));