Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d642ee6258 |
@@ -22,8 +22,7 @@ It doesnt implement a website friendly interface on its own. Thats one of the de
|
|||||||
[ref1]: https://nodejs.org/en/download
|
[ref1]: https://nodejs.org/en/download
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
wget https://git.gornodox.dev/ChaosMaker/termos/archive/unstable-async.zip
|
git clone https://git.gornodox.dev/ChaosMaker/termos.git
|
||||||
unzip -d termos unstable-async.zip
|
|
||||||
cd termos
|
cd termos
|
||||||
npm install
|
npm install
|
||||||
```
|
```
|
||||||
|
|||||||
+6
-1
@@ -3,7 +3,12 @@ import type { Result } from "./result";
|
|||||||
import type { ShellState } from "./shell_state";
|
import type { ShellState } from "./shell_state";
|
||||||
import type { ShellError } from "./util/errors";
|
import type { ShellError } from "./util/errors";
|
||||||
|
|
||||||
export type CommandFn = (io: CommandIO, state: ShellState, args: string[]) => Promise<CommandOutput<ShellError>>;
|
export type CommandFn = (
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
flags: string[],
|
||||||
|
args: string[],
|
||||||
|
) => Promise<CommandOutput<ShellError>>;
|
||||||
|
|
||||||
export interface CommandDescriptor {
|
export interface CommandDescriptor {
|
||||||
fn: CommandFn;
|
fn: CommandFn;
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import type { CommandDescriptor } from "./command";
|
import type { CommandDescriptor } from "./command";
|
||||||
import { descriptor as cat } from "./commands/cat";
|
import { descriptor as cat } from "./commands/cat";
|
||||||
import { descriptor as cd } from "./commands/cd";
|
import { descriptor as cd } from "./commands/cd";
|
||||||
import { descriptor as clear } from "./commands/clear";
|
|
||||||
import { descriptor as echo } from "./commands/echo";
|
import { descriptor as echo } from "./commands/echo";
|
||||||
import { descriptor as ls } from "./commands/ls";
|
import { descriptor as ls } from "./commands/ls";
|
||||||
import { descriptor as pwd } from "./commands/pwd";
|
|
||||||
import { descriptor as testasync } from "./commands/testasync";
|
import { descriptor as testasync } from "./commands/testasync";
|
||||||
|
|
||||||
const reg = new Map<string, CommandDescriptor>();
|
const reg = new Map<string, CommandDescriptor>();
|
||||||
@@ -14,8 +12,6 @@ reg.set(cd.name, cd);
|
|||||||
reg.set(testasync.name, testasync);
|
reg.set(testasync.name, testasync);
|
||||||
reg.set(ls.name, ls);
|
reg.set(ls.name, ls);
|
||||||
reg.set(cat.name, cat);
|
reg.set(cat.name, cat);
|
||||||
reg.set(pwd.name, pwd);
|
|
||||||
reg.set(clear.name, clear);
|
|
||||||
Object.freeze(reg);
|
Object.freeze(reg);
|
||||||
|
|
||||||
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
||||||
|
|||||||
@@ -6,7 +6,13 @@ import type { ShellError } from "@core/util/errors";
|
|||||||
|
|
||||||
export const COMMAND_NAME = "";
|
export const COMMAND_NAME = "";
|
||||||
|
|
||||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
//Need to implement escape sequences
|
||||||
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -10,7 +10,12 @@ import { resolvePath } from "@core/util/path_resolver";
|
|||||||
export const COMMAND_NAME = "cat";
|
export const COMMAND_NAME = "cat";
|
||||||
|
|
||||||
//Need to implement escape sequences
|
//Need to implement escape sequences
|
||||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
for (const arg of args) {
|
for (const arg of args) {
|
||||||
const inode = resolvePath(state, arg);
|
const inode = resolvePath(state, arg);
|
||||||
if (inode === -1) {
|
if (inode === -1) {
|
||||||
|
|||||||
@@ -13,7 +13,12 @@ import { resolvePath } from "@core/util/path_resolver";
|
|||||||
|
|
||||||
export const COMMAND_NAME = "cd";
|
export const COMMAND_NAME = "cd";
|
||||||
|
|
||||||
async function main(__io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
async function main(
|
||||||
|
__io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
__flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
|
||||||
import type { CommandIO } from "@core/command_io";
|
|
||||||
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
|
||||||
import type { ShellState } from "@core/shell_state";
|
|
||||||
import type { ShellError } from "@core/util/errors";
|
|
||||||
|
|
||||||
export const COMMAND_NAME = "clear";
|
|
||||||
|
|
||||||
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
|
|
||||||
io.writeStdout(new TextEncoder().encode("\x1b[2J\x1b[0;0H"));
|
|
||||||
|
|
||||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
|
||||||
|
|
||||||
return {
|
|
||||||
state: state,
|
|
||||||
result,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const descriptor: CommandDescriptor = {
|
|
||||||
fn: main,
|
|
||||||
name: COMMAND_NAME,
|
|
||||||
};
|
|
||||||
@@ -7,7 +7,12 @@ import type { ShellError } from "@core/util/errors";
|
|||||||
export const COMMAND_NAME = "echo";
|
export const COMMAND_NAME = "echo";
|
||||||
|
|
||||||
//Need to implement escape sequences
|
//Need to implement escape sequences
|
||||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
__flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
const joined = args.join(" ");
|
const joined = args.join(" ");
|
||||||
const encoded = new TextEncoder().encode(joined + "\n");
|
const encoded = new TextEncoder().encode(joined + "\n");
|
||||||
|
|
||||||
|
|||||||
+85
-263
@@ -7,230 +7,64 @@ import type { ShellState } from "@core/shell_state";
|
|||||||
import type { ShellError } from "@core/util/errors";
|
import type { ShellError } from "@core/util/errors";
|
||||||
import { resolvePath } from "@core/util/path_resolver";
|
import { resolvePath } from "@core/util/path_resolver";
|
||||||
import { SortTreeNodeBy, sortTreeNodes } from "@core/util/sort";
|
import { SortTreeNodeBy, sortTreeNodes } from "@core/util/sort";
|
||||||
import { concatUint8Arrays } from "@termos/util/concat";
|
|
||||||
import { convertToUnit } from "@termos/util/format_unit";
|
import { convertToUnit } from "@termos/util/format_unit";
|
||||||
|
|
||||||
export const COMMAND_NAME = "ls";
|
export const COMMAND_NAME = "ls";
|
||||||
|
|
||||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
const entries: { inode: number; path: string }[] = [];
|
const entries: { inode: number; path: string }[] = [];
|
||||||
const paths: string[] = [];
|
|
||||||
const e = new TextEncoder();
|
const e = new TextEncoder();
|
||||||
|
const vars = flags.filter(
|
||||||
|
// Match at least 1 character between each side of a singular = character
|
||||||
|
f =>
|
||||||
|
f.match(/\w+[=]{1}\w+/g) &&
|
||||||
|
// Check if descriptors flags array contains an object with the name as the flags key and has takesValue set to true
|
||||||
|
descriptor.flags?.some(flag => flag.name === f.split("=")[0] && flag.takesValue === true),
|
||||||
|
);
|
||||||
|
|
||||||
let options = {
|
const fSet = new Set(flags.filter(f => descriptor.flags?.some(flag => flag.name === f) && !vars.includes(f)));
|
||||||
all: false,
|
|
||||||
almostAll: false,
|
|
||||||
long: false,
|
|
||||||
noSort: false,
|
|
||||||
noOwner: false,
|
|
||||||
noGroup: false,
|
|
||||||
sortBy: SortTreeNodeBy.NAME,
|
|
||||||
humanReadable: false,
|
|
||||||
f: false,
|
|
||||||
x: false,
|
|
||||||
timestamp: "atime",
|
|
||||||
reverse: false,
|
|
||||||
recursive: false,
|
|
||||||
quoteName: false,
|
|
||||||
appendIndicator: false,
|
|
||||||
numericUidGid: false,
|
|
||||||
literal: false,
|
|
||||||
inode: false,
|
|
||||||
si: false,
|
|
||||||
dereference: false,
|
|
||||||
fullTime: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
for (let arg of args) {
|
if (fSet.size + vars.length < flags.length) {
|
||||||
let val;
|
|
||||||
if (arg.startsWith("--")) {
|
|
||||||
arg = arg.slice(2);
|
|
||||||
|
|
||||||
if (arg.match(/\w+[=]{1}\w+/g)) {
|
|
||||||
const flag = arg.split("=")[0];
|
|
||||||
val = arg.split("=")[1] ?? "";
|
|
||||||
|
|
||||||
if (flag === "time" && isValidTimestamp(val)) {
|
|
||||||
options.timestamp = val;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (flag === "sort" && isValidSortMethod(val)) {
|
|
||||||
options.sortBy = val as SortTreeNodeBy;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (arg) {
|
|
||||||
case "all":
|
|
||||||
options.all = true;
|
|
||||||
break;
|
|
||||||
case "almost-all":
|
|
||||||
options.almostAll = true;
|
|
||||||
break;
|
|
||||||
case "no-group":
|
|
||||||
options.noGroup = true;
|
|
||||||
break;
|
|
||||||
case "human-readable":
|
|
||||||
options.humanReadable = true;
|
|
||||||
break;
|
|
||||||
case "reverse":
|
|
||||||
options.reverse = true;
|
|
||||||
break;
|
|
||||||
case "recursive":
|
|
||||||
options.recursive = true;
|
|
||||||
break;
|
|
||||||
case "quote-name":
|
|
||||||
options.quoteName = true;
|
|
||||||
break;
|
|
||||||
case "numeric-uid-gid":
|
|
||||||
options.numericUidGid = true;
|
|
||||||
break;
|
|
||||||
case "inode":
|
|
||||||
options.inode = true;
|
|
||||||
break;
|
|
||||||
case "dereference":
|
|
||||||
options.dereference = true;
|
|
||||||
break;
|
|
||||||
case "literal":
|
|
||||||
options.literal = true;
|
|
||||||
break;
|
|
||||||
case "si":
|
|
||||||
options.si = true;
|
|
||||||
options.humanReadable = true;
|
|
||||||
break;
|
|
||||||
case "full-time":
|
|
||||||
options.fullTime = true;
|
|
||||||
break;
|
|
||||||
case "help":
|
|
||||||
// handled separately
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
return {
|
|
||||||
state,
|
|
||||||
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
|
||||||
};
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} else if (arg.startsWith("-")) {
|
|
||||||
arg = arg.slice(1);
|
|
||||||
|
|
||||||
for (const c of arg) {
|
|
||||||
switch (c) {
|
|
||||||
case "l":
|
|
||||||
options.long = true;
|
|
||||||
break;
|
|
||||||
case "a":
|
|
||||||
options.all = true;
|
|
||||||
break;
|
|
||||||
case "A":
|
|
||||||
options.almostAll = true;
|
|
||||||
break;
|
|
||||||
case "c":
|
|
||||||
options.timestamp = "ctime";
|
|
||||||
break;
|
|
||||||
case "U":
|
|
||||||
options.noSort = true;
|
|
||||||
break;
|
|
||||||
case "g":
|
|
||||||
options.noOwner = true;
|
|
||||||
options.long = true;
|
|
||||||
break;
|
|
||||||
case "G":
|
|
||||||
options.noGroup = true;
|
|
||||||
break;
|
|
||||||
case "h":
|
|
||||||
options.humanReadable = true;
|
|
||||||
break;
|
|
||||||
case "f":
|
|
||||||
options.f = true;
|
|
||||||
options.noSort = true;
|
|
||||||
options.all = true;
|
|
||||||
break;
|
|
||||||
case "x":
|
|
||||||
options.x = true;
|
|
||||||
break;
|
|
||||||
case "X":
|
|
||||||
options.sortBy = SortTreeNodeBy.EXTENSION;
|
|
||||||
break;
|
|
||||||
case "u":
|
|
||||||
options.timestamp = "atime";
|
|
||||||
break;
|
|
||||||
case "t":
|
|
||||||
options.sortBy = options.timestamp as SortTreeNodeBy;
|
|
||||||
break;
|
|
||||||
case "S":
|
|
||||||
options.sortBy = SortTreeNodeBy.SIZE;
|
|
||||||
break;
|
|
||||||
case "r":
|
|
||||||
options.reverse = true;
|
|
||||||
break;
|
|
||||||
case "R":
|
|
||||||
options.recursive = true;
|
|
||||||
break;
|
|
||||||
case "Q":
|
|
||||||
options.quoteName = true;
|
|
||||||
break;
|
|
||||||
case "p":
|
|
||||||
options.appendIndicator = true;
|
|
||||||
break;
|
|
||||||
case "o":
|
|
||||||
options.noGroup = true;
|
|
||||||
options.long = true;
|
|
||||||
break;
|
|
||||||
case "n":
|
|
||||||
options.numericUidGid = true;
|
|
||||||
break;
|
|
||||||
case "N":
|
|
||||||
options.literal = true;
|
|
||||||
break;
|
|
||||||
case "i":
|
|
||||||
options.inode = true;
|
|
||||||
break;
|
|
||||||
case "L":
|
|
||||||
options.dereference = true;
|
|
||||||
break;
|
|
||||||
case "m":
|
|
||||||
// -m: comma separated list (not in options yet)
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
return {
|
|
||||||
state,
|
|
||||||
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
paths.push(arg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const session = getCurrentSession(state);
|
const session = getCurrentSession(state);
|
||||||
|
const timeVar = vars.find(f => f.startsWith("time"))?.split("=")[1];
|
||||||
|
const sortVar = vars.find(f => f.startsWith("sort"))?.split("=")[1];
|
||||||
|
|
||||||
if (paths.length === 0) {
|
let sortBy: SortTreeNodeBy = sortVar && isValidSortMethod(sortVar) ? sortVar : SortTreeNodeBy.NAME;
|
||||||
|
let timestamp: SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME =
|
||||||
|
timeVar && isValidTimestamp(timeVar) ? timeVar : SortTreeNodeBy.ATIME;
|
||||||
|
|
||||||
|
if (args.length === 0) {
|
||||||
entries.push({ inode: session.cwd, path: "." });
|
entries.push({ inode: session.cwd, path: "." });
|
||||||
} else {
|
} else {
|
||||||
for (const path of paths) {
|
for (const arg of args) {
|
||||||
const inode = resolvePath(state, path);
|
const inode = resolvePath(state, arg);
|
||||||
if (inode === -1) {
|
if (inode === -1) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
result: createErrorResult(
|
result: createErrorResult(
|
||||||
"PathResolutionError",
|
"PathResolutionError",
|
||||||
`No such file or directory`,
|
`No such file or directory`,
|
||||||
{ path },
|
{ path: arg },
|
||||||
COMMAND_NAME,
|
COMMAND_NAME,
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
entries.push({ inode: inode, path });
|
entries.push({ inode: inode, path: arg });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.long) {
|
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
listDirEntries(entry);
|
listDirEntries(entry);
|
||||||
}
|
}
|
||||||
@@ -240,6 +74,7 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
|
|||||||
}
|
}
|
||||||
io.writeStdout(e.encode(`No support for short format yet\n`));
|
io.writeStdout(e.encode(`No support for short format yet\n`));
|
||||||
}
|
}
|
||||||
|
io.writeStdout(e.encode("\n"));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
@@ -249,20 +84,27 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
|
|||||||
function listDirEntries(entry: { inode: number; path: string }): void {
|
function listDirEntries(entry: { inode: number; path: string }): void {
|
||||||
const node = state.filesystem.getNode(entry.inode) as DirectoryNode;
|
const node = state.filesystem.getNode(entry.inode) as DirectoryNode;
|
||||||
|
|
||||||
if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`));
|
// This method of evaluating flags is faulty, it doesnt respect order;
|
||||||
|
if (fSet.has("t")) sortBy = timestamp;
|
||||||
|
if (fSet.has("S")) sortBy = SortTreeNodeBy.SIZE;
|
||||||
|
if (fSet.has("X")) sortBy = SortTreeNodeBy.EXTENSION;
|
||||||
|
|
||||||
|
if (fSet.has("R") || fSet.has("recursive")) io.writeStdout(e.encode(`${entry.path}:\n`));
|
||||||
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
|
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
|
||||||
|
|
||||||
let children: TreeNode[] = Object.entries(node.children).map(c => state.filesystem.getNode(c[1])!);
|
let children: TreeNode[] = Object.entries(node.children).map(c => state.filesystem.getNode(c[1])!);
|
||||||
if (!options.noSort) children = sortTreeNodes(state, children, options.reverse, options.sortBy);
|
if (!fSet.has("f") || !fSet.has("U"))
|
||||||
|
children = sortTreeNodes(state, children, fSet.has("r") || fSet.has("reverse"), sortBy);
|
||||||
|
|
||||||
if (!options.all && !options.almostAll) children = children.filter(c => !c.name.startsWith("."));
|
if (fSet.has("a") || fSet.has("A") || fSet.has("all") || fSet.has("almost-all") || fSet.has("f"))
|
||||||
|
children = children.filter(c => !c.name.startsWith("."));
|
||||||
|
|
||||||
if (options.long) {
|
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
|
||||||
longMode(io, state, children, node);
|
longMode(io, state, children, fSet);
|
||||||
if (options.recursive) io.writeStdout(e.encode("\n"));
|
io.writeStdout(e.encode("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.recursive) {
|
if (fSet.has("R") || fSet.has("recursive")) {
|
||||||
for (const child of children) {
|
for (const child of children) {
|
||||||
if (child.type === TreeNodeType.Directory) {
|
if (child.type === TreeNodeType.Directory) {
|
||||||
let path;
|
let path;
|
||||||
@@ -276,19 +118,21 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function longMode(io: CommandIO, state: ShellState, children: TreeNode[], current: TreeNode): void {
|
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
|
||||||
|
|
||||||
|
function longMode(io: CommandIO, state: ShellState, nodes: TreeNode[], flags: Set<string>): void {
|
||||||
const e = new TextEncoder();
|
const e = new TextEncoder();
|
||||||
const buff: Uint8Array[] = [];
|
|
||||||
const nodes: TreeNode[] = [...children];
|
|
||||||
|
|
||||||
if (options.all) {
|
if (flags.has("a") || flags.has("all") || flags.has("f")) {
|
||||||
const parentNode = state.filesystem.getNode(current.parent)!;
|
const cwdNode = state.filesystem.getNode(nodes[0]!.parent)!;
|
||||||
|
const parentNode = state.filesystem.getNode(cwdNode.parent)!;
|
||||||
|
|
||||||
const parent: TreeNode = { ...parentNode, name: ".." };
|
const parent: TreeNode = { ...parentNode, name: ".." };
|
||||||
nodes.unshift(parent);
|
nodes.unshift(parent);
|
||||||
|
|
||||||
const cwd: TreeNode = { ...current, name: "." };
|
const cwd: TreeNode = { ...cwdNode, name: "." };
|
||||||
nodes.unshift(cwd);
|
nodes.unshift(cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -306,56 +150,48 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const namePadding = nodes.every(c => !c.name.includes(" "));
|
|
||||||
|
|
||||||
for (const node of nodes) {
|
for (const node of nodes) {
|
||||||
//Inode
|
if (flags.has("i") || flags.has("inode")) {
|
||||||
if (options.inode) {
|
|
||||||
const inode = node.inode.toString().padStart(maxInodeWidth, " ");
|
const inode = node.inode.toString().padStart(maxInodeWidth, " ");
|
||||||
buff.push(e.encode(inode + " "));
|
io.writeStdout(e.encode(inode + " "));
|
||||||
//io.writeStdout(e.encode(inode + " "));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mode
|
|
||||||
const mode: string = parseMode(node.mode);
|
const mode: string = parseMode(node.mode);
|
||||||
|
|
||||||
switch (node.type) {
|
switch (node.type) {
|
||||||
case TreeNodeType.Directory:
|
case TreeNodeType.Directory:
|
||||||
buff.push(e.encode("d" + mode + " "));
|
io.writeStdout(e.encode("d" + mode + " "));
|
||||||
break;
|
break;
|
||||||
case TreeNodeType.File:
|
case TreeNodeType.File:
|
||||||
buff.push(e.encode("-" + mode + " "));
|
io.writeStdout(e.encode("-" + mode + " "));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Children amnt (later will be amnt of links)
|
|
||||||
const childAmnt =
|
const childAmnt =
|
||||||
node.type === TreeNodeType.Directory
|
node.type === TreeNodeType.Directory
|
||||||
? `${Object.entries(node.children).length.toString().padStart(maxChildrenWidth, " ")} `
|
? `${Object.entries(node.children).length.toString().padStart(maxChildrenWidth, " ")} `
|
||||||
: `${"10".padStart(maxChildrenWidth, " ")} `;
|
: `${"10".padStart(maxChildrenWidth, " ")} `;
|
||||||
|
|
||||||
buff.push(e.encode(childAmnt));
|
io.writeStdout(e.encode(childAmnt));
|
||||||
|
|
||||||
// owner group
|
if (flags.has("o") || flags.has("G") || flags.has("no-group")) {
|
||||||
if (options.noGroup) {
|
io.writeStdout(e.encode(`${state.users.get(node.owner)?.username} `));
|
||||||
buff.push(e.encode(`${state.users.get(node.owner)?.username} `));
|
} else if (flags.has("g")) {
|
||||||
} else if (options.noOwner) {
|
io.writeStdout(e.encode(`${state.groups.get(node.group)?.groupname} `));
|
||||||
buff.push(e.encode(`${state.groups.get(node.group)?.groupname} `));
|
} else if (flags.has("n") || flags.has("numeric-uid-gid")) {
|
||||||
} else if (options.numericUidGid) {
|
io.writeStdout(e.encode(`${node.owner} ${node.group} `));
|
||||||
buff.push(e.encode(`${node.owner} ${node.group} `));
|
|
||||||
} else {
|
} else {
|
||||||
buff.push(
|
io.writeStdout(
|
||||||
e.encode(`${state.users.get(node.owner)?.username} ${state.groups.get(node.group)?.groupname} `),
|
e.encode(`${state.users.get(node.owner)?.username} ${state.groups.get(node.group)?.groupname} `),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Size
|
|
||||||
// Holy abomination, pad the stringified bytesize number with whitespaces so the actual length of the string matches across all rows
|
// Holy abomination, pad the stringified bytesize number with whitespaces so the actual length of the string matches across all rows
|
||||||
// Sets the folder size to an arbitrary 4096, could change it later to smth else
|
// Sets the folder size to an arbitrary 4096, could change it later to smth else
|
||||||
let size;
|
let size;
|
||||||
if (options.humanReadable) {
|
if (flags.has("h") || flags.has("human-readable")) {
|
||||||
const bytes = node.type === TreeNodeType.File ? node.content.byteSize() : 4096;
|
const bytes = node.type === TreeNodeType.File ? node.content.byteSize() : 4096;
|
||||||
size = convertToUnit(bytes, 1, options.si ? 1000 : 1024);
|
size = convertToUnit(bytes, 1, flags.has("si") ? 1000 : 1024);
|
||||||
} else {
|
} else {
|
||||||
size =
|
size =
|
||||||
node.type === TreeNodeType.File
|
node.type === TreeNodeType.File
|
||||||
@@ -363,52 +199,43 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
|
|||||||
: `${"4096".padStart(maxSizeWidth, " ")} `;
|
: `${"4096".padStart(maxSizeWidth, " ")} `;
|
||||||
}
|
}
|
||||||
|
|
||||||
buff.push(e.encode(size));
|
io.writeStdout(e.encode(size));
|
||||||
|
|
||||||
//Timestamp
|
|
||||||
// for now only mtime, need a helper function for all the formatting later on
|
// for now only mtime, need a helper function for all the formatting later on
|
||||||
const date = getDateTimestamp(node, options.timestamp);
|
const mtime = new Date(node.mtime);
|
||||||
if (options.fullTime) {
|
if (flags.has("full-time")) {
|
||||||
buff.push(
|
io.writeStdout(
|
||||||
// Month + 1 because January is 0
|
// Month + 1 because January is 0
|
||||||
e.encode(
|
e.encode(
|
||||||
`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `,
|
`${mtime.getFullYear()}-${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
buff.push(
|
io.writeStdout(
|
||||||
// Month + 1 because January is 0
|
// Month + 1 because January is 0
|
||||||
e.encode(`${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `),
|
e.encode(`${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
const appendSlash = flags.has("p");
|
||||||
//Name
|
if (flags.has("Q") || flags.has("quote-name")) {
|
||||||
if (options.quoteName) {
|
io.writeStdout(
|
||||||
buff.push(
|
|
||||||
e.encode(
|
e.encode(
|
||||||
`"${node.type === TreeNodeType.Directory ? node.name + '"' + (options.appendIndicator ? "/" : "") : node.name + '"'}\n`,
|
`"${node.type === TreeNodeType.Directory ? node.name + '"' + (appendSlash ? "/" : "") : node.name + '"'}\n`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else if (!flags.has("N") || !flags.has("literal")) {
|
||||||
|
io.writeStdout(
|
||||||
|
e.encode(
|
||||||
|
`${node.type === TreeNodeType.Directory ? node.name + (appendSlash ? "/" : "") : node.name}\n`,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
const unpadded = `${node.name.includes(" ") && !options.literal ? "'" + node.name + "'" : node.name}`;
|
const name = `${node.name.includes(" ") ? "'" + node.name + "'" : node.name}`;
|
||||||
const name = `${!namePadding ? (unpadded.includes(" ") ? unpadded : " " + unpadded) : unpadded}`;
|
io.writeStdout(
|
||||||
buff.push(
|
e.encode(`${node.type === TreeNodeType.Directory ? name + (appendSlash ? "/" : "") : name}\n`),
|
||||||
e.encode(
|
|
||||||
`${node.type === TreeNodeType.Directory ? name + (options.appendIndicator ? "/" : "") : name}\n`,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const out = concatUint8Arrays(buff);
|
|
||||||
io.writeStdout(out);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getDateTimestamp(node: TreeNode, ts: string): Date {
|
|
||||||
if (ts === "atime") return new Date(node.atime);
|
|
||||||
if (ts === "ctime") return new Date(node.ctime);
|
|
||||||
if (ts === "mtime") return new Date(node.mtime);
|
|
||||||
return new Date();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseMode(mode: number) {
|
function parseMode(mode: number) {
|
||||||
@@ -431,16 +258,11 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
|
|||||||
return Object.values(SortTreeNodeBy).includes(value as SortTreeNodeBy);
|
return Object.values(SortTreeNodeBy).includes(value as SortTreeNodeBy);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isValidTimestamp(
|
function isValidTimestamp(value: string): value is SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME {
|
||||||
value: string,
|
|
||||||
): value is SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME {
|
|
||||||
return Object.values(SortTreeNodeBy).includes(
|
return Object.values(SortTreeNodeBy).includes(
|
||||||
value as SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME,
|
value as SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
|
|
||||||
|
|
||||||
export const descriptor: CommandDescriptor = {
|
export const descriptor: CommandDescriptor = {
|
||||||
fn: main,
|
fn: main,
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
|
||||||
import type { CommandIO } from "@core/command_io";
|
|
||||||
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
|
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
|
||||||
import type { ShellState } from "@core/shell_state";
|
|
||||||
import type { InvalidArgumentsError, ShellError } from "@core/util/errors";
|
|
||||||
import { resolveInode } from "@core/util/path_resolver";
|
|
||||||
|
|
||||||
export const COMMAND_NAME = "pwd";
|
|
||||||
|
|
||||||
//Need to implement escape sequences
|
|
||||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
|
||||||
if (args.length > 0) {
|
|
||||||
return {
|
|
||||||
state,
|
|
||||||
result: createErrorResult(
|
|
||||||
"InvalidArguments",
|
|
||||||
`Expected aruments 0, got ${args.length}.`,
|
|
||||||
{ expected: "pwd", actual: `pwd ${args.toString().replace(/[,]/g, " ")}` },
|
|
||||||
COMMAND_NAME,
|
|
||||||
),
|
|
||||||
} satisfies CommandOutput<InvalidArgumentsError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const session = getCurrentSession(state);
|
|
||||||
const path = resolveInode(state, session.cwd);
|
|
||||||
|
|
||||||
io.writeStdout(new TextEncoder().encode(path));
|
|
||||||
|
|
||||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
|
||||||
|
|
||||||
return {
|
|
||||||
state: state,
|
|
||||||
result,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const descriptor: CommandDescriptor = {
|
|
||||||
fn: main,
|
|
||||||
name: COMMAND_NAME,
|
|
||||||
};
|
|
||||||
@@ -8,7 +8,12 @@ import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
|||||||
|
|
||||||
const COMMAND_NAME = "async";
|
const COMMAND_NAME = "async";
|
||||||
|
|
||||||
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
__flags: string[],
|
||||||
|
__args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
while (true) {
|
while (true) {
|
||||||
const out = await io.getSignal();
|
const out = await io.getSignal();
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,12 @@ import { resolvePath } from "@core/util/path_resolver";
|
|||||||
export const COMMAND_NAME = "touch";
|
export const COMMAND_NAME = "touch";
|
||||||
|
|
||||||
//Need to implement escape sequences
|
//Need to implement escape sequences
|
||||||
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
for (const arg of args) {
|
for (const arg of args) {
|
||||||
const inode = resolvePath(state, arg);
|
const inode = resolvePath(state, arg);
|
||||||
const session = getCurrentSession(state);
|
const session = getCurrentSession(state);
|
||||||
|
|||||||
+52
-1
@@ -6,7 +6,13 @@ interface UnclosedQuoteError {
|
|||||||
timestamp: number;
|
timestamp: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function tokenize(input: string): string[] {
|
interface ParsedCommand {
|
||||||
|
command: string;
|
||||||
|
flags: string[];
|
||||||
|
args: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenize(input: string): string[] {
|
||||||
enum State {
|
enum State {
|
||||||
Normal,
|
Normal,
|
||||||
SingleQuote,
|
SingleQuote,
|
||||||
@@ -92,3 +98,48 @@ export function tokenize(input: string): string[] {
|
|||||||
flushBuffer();
|
flushBuffer();
|
||||||
return tokens;
|
return tokens;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function parseCommand(input: string): ParsedCommand {
|
||||||
|
const tokens = tokenize(input);
|
||||||
|
const command = tokens[0] ?? "";
|
||||||
|
const flags: string[] = [];
|
||||||
|
const args: string[] = [];
|
||||||
|
|
||||||
|
let pastEndOfOptions = false;
|
||||||
|
|
||||||
|
for (let i = 1; i < tokens.length; i++) {
|
||||||
|
const token = tokens[i]!;
|
||||||
|
|
||||||
|
if (pastEndOfOptions) {
|
||||||
|
args.push(token);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token === "--") {
|
||||||
|
pastEndOfOptions = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.startsWith("--")) {
|
||||||
|
flags.push(token.slice(2));
|
||||||
|
continue;
|
||||||
|
} else if (token.startsWith("-")) {
|
||||||
|
if (token.includes("=")) {
|
||||||
|
flags.push(token.slice(1));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const char of token.slice(1)) {
|
||||||
|
flags.push(char);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
args.push(token);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
command,
|
||||||
|
flags,
|
||||||
|
args,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -28,11 +28,6 @@ export function resolvePath(state: ShellState, path: string): number {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (name === "~") {
|
|
||||||
currentNode = state.filesystem.getNode(session.user.home) as DirectoryNode;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const inode = currentNode.children[name];
|
const inode = currentNode.children[name];
|
||||||
|
|
||||||
if (!inode)
|
if (!inode)
|
||||||
|
|||||||
+18
-20
File diff suppressed because one or more lines are too long
@@ -23,19 +23,20 @@ export class Process {
|
|||||||
readonly CommandDescriptor: CommandDescriptor;
|
readonly CommandDescriptor: CommandDescriptor;
|
||||||
readonly State: ShellState;
|
readonly State: ShellState;
|
||||||
readonly Args: string[];
|
readonly Args: string[];
|
||||||
|
readonly Flags: string[];
|
||||||
|
|
||||||
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, args: string[]) {
|
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) {
|
||||||
this.PID = pid;
|
this.PID = pid;
|
||||||
this.State = state;
|
this.State = state;
|
||||||
this.Name = descriptor.name;
|
this.Name = descriptor.name;
|
||||||
this.CommandDescriptor = descriptor;
|
this.CommandDescriptor = descriptor;
|
||||||
|
this.Flags = flags;
|
||||||
this.Args = args;
|
this.Args = args;
|
||||||
// Check if positive later and throw an error if so
|
// Check if positive later and throw an error if so
|
||||||
this._MaxChunkByteSize = 1024;
|
this._MaxChunkByteSize = 1024;
|
||||||
this._EventEmitter = new EventEmitter<ShellEventMap>();
|
this._EventEmitter = new EventEmitter<ShellEventMap>();
|
||||||
}
|
}
|
||||||
|
|
||||||
// WARNING, CHUNKING OUTPUT BREAKS FORMATING
|
|
||||||
private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void {
|
private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void {
|
||||||
if (this._Settled) return;
|
if (this._Settled) return;
|
||||||
|
|
||||||
@@ -67,7 +68,7 @@ export class Process {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const promise = this.CommandDescriptor.fn(io, this.State, this.Args);
|
const promise = this.CommandDescriptor.fn(io, this.State, this.Flags, this.Args);
|
||||||
|
|
||||||
promise
|
promise
|
||||||
.then(output => {
|
.then(output => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { CommandDescriptor } from "@core/command";
|
import type { CommandDescriptor } from "@core/command";
|
||||||
import type { ShellState } from "@core/shell_state";
|
import type { ShellState } from "@core/shell_state";
|
||||||
import { SIGNAL_MAP, type Signal } from "@core/signal";
|
import type { Signal } from "@core/signal";
|
||||||
import { EventEmitter } from "./event_emitter";
|
import { EventEmitter } from "./event_emitter";
|
||||||
import { Process } from "./process";
|
import { Process } from "./process";
|
||||||
import type { ShellEventMap } from "./shell";
|
import type { ShellEventMap } from "./shell";
|
||||||
@@ -11,9 +11,9 @@ export class ProcessManager {
|
|||||||
|
|
||||||
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
||||||
|
|
||||||
public createProcess(state: ShellState, descriptor: CommandDescriptor, args: string[]): number {
|
public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): number {
|
||||||
const pid = ++this._PIDIndex;
|
const pid = ++this._PIDIndex;
|
||||||
const process = new Process(pid, state, descriptor, args);
|
const process = new Process(pid, state, descriptor, flags, args);
|
||||||
this._Processes.set(pid, process);
|
this._Processes.set(pid, process);
|
||||||
|
|
||||||
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
||||||
@@ -51,7 +51,7 @@ export class ProcessManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Make global signals an enum later
|
//Make global signals an enum later
|
||||||
process.sendSignal({ type: SIGNAL_MAP.SIGKILL } satisfies Signal);
|
process.sendSignal({ type: "SIGKILL" } satisfies Signal);
|
||||||
}
|
}
|
||||||
|
|
||||||
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
|||||||
+36
-25
@@ -5,12 +5,13 @@ import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
|
|||||||
import { SIGNAL_MAP } from "@core/signal";
|
import { SIGNAL_MAP } from "@core/signal";
|
||||||
import type { ShellError } from "@core/util/errors";
|
import type { ShellError } from "@core/util/errors";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
import { tokenize } from "@core/util/parser";
|
import { parseCommand } from "@core/util/parser";
|
||||||
import { EventEmitter } from "./event_emitter";
|
import { EventEmitter } from "./event_emitter";
|
||||||
import { ProcessManager } from "./process_manager";
|
import { ProcessManager } from "./process_manager";
|
||||||
|
|
||||||
export class Shell {
|
export class Shell {
|
||||||
static #Instance: Shell | null;
|
static #Instance: Shell;
|
||||||
|
static #Promise: Promise<Shell> | null = null;
|
||||||
private _State: Readonly<ShellState>;
|
private _State: Readonly<ShellState>;
|
||||||
private _ProcessManager: ProcessManager = new ProcessManager();
|
private _ProcessManager: ProcessManager = new ProcessManager();
|
||||||
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
||||||
@@ -42,37 +43,51 @@ export class Shell {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
static destroy(): void {
|
static async init(initialState: ShellState): Promise<Shell> {
|
||||||
Shell.#Instance = null;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
static init(initialState: ShellState): Shell {
|
|
||||||
if (Shell.#Instance) {
|
if (Shell.#Instance) {
|
||||||
console.warn("Shell already initialized");
|
console.warn("Shell already initialized");
|
||||||
return Shell.#Instance;
|
return this.#Instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (Shell.#Promise) return Shell.#Promise;
|
||||||
|
|
||||||
|
Shell.#Promise = (async () => {
|
||||||
|
try {
|
||||||
Shell.#Instance = new Shell(initialState);
|
Shell.#Instance = new Shell(initialState);
|
||||||
return Shell.#Instance;
|
return Shell.#Instance;
|
||||||
|
} finally {
|
||||||
|
Shell.#Promise = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return Shell.#Promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async execute(input: string): Promise<void> {
|
public async execute(input: string): Promise<void> {
|
||||||
const parsed = tokenize(input);
|
let parsed;
|
||||||
|
try {
|
||||||
|
parsed = parseCommand(input);
|
||||||
|
} catch {
|
||||||
|
const result = createErrorResult("ParseError", `Parsing error - ${input}`, {});
|
||||||
|
|
||||||
if (!parsed[0]) return;
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parsed.command === "") return;
|
||||||
|
|
||||||
this._State = withHistory(this._State, input);
|
this._State = withHistory(this._State, input);
|
||||||
const command = COMMAND_REGISTRY.get(parsed[0]);
|
const command = COMMAND_REGISTRY.get(parsed.command);
|
||||||
|
|
||||||
if (!command) {
|
if (!command) {
|
||||||
const encoded = new TextEncoder().encode(`Command ${parsed[0]} not found`);
|
const encoded = new TextEncoder().encode(`Command ${parsed.command} not found`);
|
||||||
|
|
||||||
const result = createErrorResult(
|
const result = createErrorResult(
|
||||||
"CommandNotFound",
|
"CommandNotFound",
|
||||||
`Command ${parsed[0]} not found`,
|
`Command ${parsed.command} not found`,
|
||||||
{ command: parsed[0] },
|
{ command: parsed.command },
|
||||||
parsed[0],
|
parsed.command,
|
||||||
createImmutableBuffer(encoded),
|
createImmutableBuffer(encoded),
|
||||||
createImmutableBuffer(new Uint8Array()),
|
createImmutableBuffer(new Uint8Array()),
|
||||||
);
|
);
|
||||||
@@ -87,7 +102,7 @@ export class Shell {
|
|||||||
"PermissionDenied",
|
"PermissionDenied",
|
||||||
`Permission Denied`,
|
`Permission Denied`,
|
||||||
{ resource: `Execution of the ${command.name} command` },
|
{ resource: `Execution of the ${command.name} command` },
|
||||||
parsed[0],
|
parsed.command,
|
||||||
);
|
);
|
||||||
|
|
||||||
this._State = withExitCode(this._State, result.error.exitCode);
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
@@ -95,9 +110,7 @@ export class Shell {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
parsed.shift();
|
const pid = this._ProcessManager.createProcess(this._State, command, parsed.flags, parsed.args);
|
||||||
|
|
||||||
const pid = this._ProcessManager.createProcess(this._State, command, parsed);
|
|
||||||
this.BoundPID = pid;
|
this.BoundPID = pid;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,12 +132,10 @@ export class Shell {
|
|||||||
return this._State;
|
return this._State;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Instance(initialState?: ShellState): Shell {
|
public static get Instance(): Shell | undefined {
|
||||||
if (!Shell.#Instance) {
|
if (!Shell.#Instance) {
|
||||||
if (!initialState) {
|
console.error("Shell has not been initialised yet. Call `await Shell.init()` first.");
|
||||||
throw new Error("Shell needs to be initialized first");
|
return;
|
||||||
}
|
|
||||||
Shell.#Instance = new Shell(initialState);
|
|
||||||
}
|
}
|
||||||
return Shell.#Instance;
|
return Shell.#Instance;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user