Skip to content

Commit

Permalink
Merge pull request #112 from llagerlof/shell_history
Browse files Browse the repository at this point in the history
Add executed commands to shell history
  • Loading branch information
steve8708 authored Jul 9, 2024
2 parents ce1fcfb + 947e143 commit 2d2c6bd
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 5 deletions.
52 changes: 52 additions & 0 deletions src/helpers/shell-history.ts
Original file line number Diff line number Diff line change
@@ -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
}
});
}
}
}
14 changes: 9 additions & 5 deletions src/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -38,12 +39,15 @@ const sample = <T>(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) {
Expand Down

0 comments on commit 2d2c6bd

Please sign in to comment.