Implement history command and the shell expansion partially.

pull/11/head
Attacktive 3 years ago
parent 1f2e543bdb
commit 5d147beb30

@ -2,6 +2,7 @@
import * as bin from './index';
import config from '../../../config.json';
import { list as listHistory } from '../history';
// Help
export const help = async (args: string[]): Promise<string> => {
@ -138,6 +139,11 @@ export const sudo = async (args?: string[]): Promise<string> => {
return `Permission denied: with little power comes... no responsibility? `;
};
// history
export const history = async (args: string[]): Promise<string> => {
return listHistory();
};
// Banner
export const banner = (args?: string[]): string => {
return `

@ -0,0 +1,44 @@
type History = Record<string, string>;
const history: History = {};
let historyIndex = 0;
export function list(): string {
const array: Array<string> = [];
for (const key in history) {
const value: string = history[key];
array.push(`${key}: ${value}`);
}
return array.join('\n');
}
export function push(command: string): History {
if (getLast() !== command) {
history[++historyIndex] = command;
}
return history;
}
export function getCommandIfHistoryExpansion(input): string {
let command = undefined;
const regExpExecArray = /!(?:(\d+)|!)/.exec(input);
if (regExpExecArray) {
const index = regExpExecArray[1];
if (index === '!') {
command = getLast();
} else {
command = get(index);
}
}
return command;
}
function get(index: string): string {
return history[index];
}
function getLast(): string {
return history[historyIndex];
}

@ -1,5 +1,6 @@
import React from 'react';
import * as bin from './bin';
import { getCommandIfHistoryExpansion, push as pushHistory } from './history';
export const shell = async (
command: string,
@ -8,17 +9,28 @@ export const shell = async (
setCommand: React.Dispatch<React.SetStateAction<string>>,
) => {
const args = command.split(' ');
args[0] = args[0].toLowerCase();
args[0] = args[0].toLowerCase().trim();
let expandedCommand = getCommandIfHistoryExpansion(args[0]);
if (expandedCommand) {
// like bash with histverify on or zsh default
setCommand(expandedCommand);
return;
}
if (args[0] === 'clear') {
pushHistory(args[0]);
clearHistory();
} else if (command === '') {
setHistory('');
} else if (Object.keys(bin).indexOf(args[0]) === -1) {
pushHistory(args[0]);
setHistory(
`shell: command not found: ${args[0]}. Try 'help' to get started.`,
);
} else {
pushHistory(args[0]);
const output = await bin[args[0]](args.slice(1));
setHistory(output);
}

Loading…
Cancel
Save