Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2ade5de29 | ||
|
|
b75e691a0b | ||
|
|
776a93e21b | ||
|
|
6cc9727091 | ||
|
|
2715e5e28e | ||
|
|
8a349330b0 | ||
|
|
2e9227f6d8 | ||
|
|
8e054a220d | ||
|
|
4776232377 |
+1
-6
@@ -3,12 +3,7 @@ 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 = (
|
export type CommandFn = (io: CommandIO, state: ShellState, args: string[]) => Promise<CommandOutput<ShellError>>;
|
||||||
io: CommandIO,
|
|
||||||
state: ShellState,
|
|
||||||
flags: string[],
|
|
||||||
args: string[],
|
|
||||||
) => Promise<CommandOutput<ShellError>>;
|
|
||||||
|
|
||||||
export interface CommandDescriptor {
|
export interface CommandDescriptor {
|
||||||
fn: CommandFn;
|
fn: CommandFn;
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import type { CommandDescriptor } from "./command";
|
import type { CommandDescriptor } from "./command";
|
||||||
|
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>();
|
||||||
@@ -10,6 +13,9 @@ reg.set(echo.name, echo);
|
|||||||
reg.set(cd.name, cd);
|
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(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;
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
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 = "";
|
||||||
|
|
||||||
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { TreeNodeType, type FileNode, type TreeNode } from "@core/filesystem/treenode";
|
||||||
|
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
|
||||||
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { PathResolutionError, PermissionDeniedError, ShellError } from "@core/util/errors";
|
||||||
|
import { resolvePath } from "@core/util/path_resolver";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "cat";
|
||||||
|
|
||||||
|
//Need to implement escape sequences
|
||||||
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
|
for (const arg of args) {
|
||||||
|
const inode = resolvePath(state, arg);
|
||||||
|
if (inode === -1) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult(
|
||||||
|
"PathResolutionError",
|
||||||
|
"No such file or directory",
|
||||||
|
{ path: arg },
|
||||||
|
COMMAND_NAME,
|
||||||
|
),
|
||||||
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Casting to TreeNode because the resolvePath already ensures the inode is correct;
|
||||||
|
const node = state.filesystem.getNode(inode) as TreeNode;
|
||||||
|
|
||||||
|
if (node.type != TreeNodeType.File) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult(
|
||||||
|
"PathResolutionError",
|
||||||
|
`${node.name} is a directory`,
|
||||||
|
{ path: arg },
|
||||||
|
COMMAND_NAME,
|
||||||
|
),
|
||||||
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
|
if (!state.filesystem.canRead(inode, session.user)) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult("PermissionDenied", "Permission denied", { resource: arg }, COMMAND_NAME),
|
||||||
|
} satisfies CommandOutput<PermissionDeniedError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
node as FileNode;
|
||||||
|
io.writeStdout(node.content.toArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
+3
-22
@@ -1,6 +1,5 @@
|
|||||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
import type { CommandIO } from "@core/command_io";
|
import type { CommandIO } from "@core/command_io";
|
||||||
import type { FileSystem } from "@core/filesystem/filesystem";
|
|
||||||
import { createErrorResult, createSuccessResult } from "@core/result";
|
import { createErrorResult, createSuccessResult } from "@core/result";
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
import { ShellState, withCwd } from "@core/shell_state";
|
import { ShellState, withCwd } from "@core/shell_state";
|
||||||
@@ -14,12 +13,7 @@ import { resolvePath } from "@core/util/path_resolver";
|
|||||||
|
|
||||||
export const COMMAND_NAME = "cd";
|
export const COMMAND_NAME = "cd";
|
||||||
|
|
||||||
async function main(
|
async function main(__io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
__io: CommandIO,
|
|
||||||
state: ShellState,
|
|
||||||
__flags: string[],
|
|
||||||
args: string[],
|
|
||||||
): Promise<CommandOutput<ShellError>> {
|
|
||||||
if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
@@ -40,8 +34,8 @@ async function main(
|
|||||||
} else if (args[0] === "-") {
|
} else if (args[0] === "-") {
|
||||||
inode = session.pwd;
|
inode = session.pwd;
|
||||||
} else {
|
} else {
|
||||||
const result = safeResolvePath(state.filesystem, session.cwd, args[0]);
|
inode = resolvePath(state, args[0]);
|
||||||
if (result.type === "error") {
|
if (inode === -1) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
result: createErrorResult(
|
result: createErrorResult(
|
||||||
@@ -52,7 +46,6 @@ async function main(
|
|||||||
),
|
),
|
||||||
} satisfies CommandOutput<PathResolutionError>;
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
}
|
}
|
||||||
inode = result.inode;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (state.filesystem.isFile(inode)) {
|
if (state.filesystem.isFile(inode)) {
|
||||||
@@ -75,18 +68,6 @@ async function main(
|
|||||||
state: returnState,
|
state: returnState,
|
||||||
result: createSuccessResult(COMMAND_NAME),
|
result: createSuccessResult(COMMAND_NAME),
|
||||||
};
|
};
|
||||||
|
|
||||||
function safeResolvePath(
|
|
||||||
fs: FileSystem,
|
|
||||||
cwd: number,
|
|
||||||
path: string,
|
|
||||||
): { type: "success"; inode: number } | { type: "error" } {
|
|
||||||
try {
|
|
||||||
return { type: "success", inode: resolvePath(fs, cwd, path) };
|
|
||||||
} catch {
|
|
||||||
return { type: "error" };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const descriptor: CommandDescriptor = {
|
export const descriptor: CommandDescriptor = {
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
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,12 +7,7 @@ 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(
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
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");
|
||||||
|
|
||||||
|
|||||||
+448
-170
@@ -6,207 +6,485 @@ import { getCurrentSession } from "@core/session_manager";
|
|||||||
import type { ShellState } from "@core/shell_state";
|
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 { dnTraverseTree } from "@core/util/tree_traversal";
|
import { SortTreeNodeBy, sortTreeNodes } from "@core/util/sort";
|
||||||
|
import { concatUint8Arrays } from "@termos/util/concat";
|
||||||
|
import { convertToUnit } from "@termos/util/format_unit";
|
||||||
|
|
||||||
export const COMMAND_NAME = "ls";
|
export const COMMAND_NAME = "ls";
|
||||||
|
|
||||||
async function main(
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
io: CommandIO,
|
const entries: { inode: number; path: string }[] = [];
|
||||||
state: ShellState,
|
const paths: string[] = [];
|
||||||
flags: string[],
|
const e = new TextEncoder();
|
||||||
args: string[],
|
|
||||||
): Promise<CommandOutput<ShellError>> {
|
|
||||||
const nodes: number[] = [];
|
|
||||||
|
|
||||||
const vars = flags.filter(
|
let options = {
|
||||||
// Match at least 1 character between each side of a singular = character
|
all: false,
|
||||||
f =>
|
almostAll: false,
|
||||||
f.match(/\w+[=]{1}\w+/g) &&
|
long: false,
|
||||||
// Check if descriptors flags array contains an object with the name as the flags key and has takesValue set to true
|
noSort: false,
|
||||||
descriptor.flags?.some(flag => flag.name === f.split("=")[0] && flag.takesValue === true),
|
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,
|
||||||
|
};
|
||||||
|
|
||||||
const fSet = new Set(flags.filter(f => descriptor.flags?.some(flag => flag.name === f) && !vars.includes(f)));
|
for (let arg of args) {
|
||||||
|
let val;
|
||||||
|
if (arg.startsWith("--")) {
|
||||||
|
arg = arg.slice(2);
|
||||||
|
|
||||||
if (fSet.size + vars.length < flags.length) {
|
if (arg.match(/\w+[=]{1}\w+/g)) {
|
||||||
return {
|
const flag = arg.split("=")[0];
|
||||||
state,
|
val = arg.split("=")[1] ?? "";
|
||||||
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
|
||||||
};
|
if (flag === "time" && isValidTimestamp(val)) {
|
||||||
|
options.timestamp = val;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (flag === "sort" && isValidSortMethod(val)) {
|
||||||
|
options.sortBy = val as SortTreeNodeBy;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
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);
|
||||||
|
|
||||||
nodes.push(session.cwd);
|
if (paths.length === 0) {
|
||||||
|
entries.push({ inode: session.cwd, path: "." });
|
||||||
for (const arg of args) {
|
} else {
|
||||||
let inode;
|
for (const path of paths) {
|
||||||
try {
|
const inode = resolvePath(state, path);
|
||||||
inode = resolvePath(state.filesystem, session.cwd, arg);
|
if (inode === -1) {
|
||||||
} catch {
|
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 });
|
||||||
|
|
||||||
nodes.push(inode);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fSet.has("R") || fSet.has("recursive")) {
|
|
||||||
const treeArray = [];
|
|
||||||
|
|
||||||
for (const inode of nodes) {
|
|
||||||
treeArray.push(...dnTraverseTree(state.filesystem, inode));
|
|
||||||
}
|
|
||||||
|
|
||||||
nodes.length = 0;
|
|
||||||
nodes.push(...treeArray.filter(node => state.filesystem.getNode(node)?.type !== TreeNodeType.File));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = 0; i < nodes.length; i++) {
|
|
||||||
const treenode: DirectoryNode = state.filesystem.getNode(nodes[i]!) as DirectoryNode;
|
|
||||||
|
|
||||||
io.writeStdout(new TextEncoder().encode(`total ${Object.entries(treenode.children).length}\n`));
|
|
||||||
|
|
||||||
// Object.entries returns the touple of Record<string, number> so we get the number by doing c[1] as index 1 in the touple is the number
|
|
||||||
// We do null assertion because we already made sure in the recursive check that all inodes are correct
|
|
||||||
let children: TreeNode[] = Object.entries(treenode.children).map(c => state.filesystem.getNode(c[1])!);
|
|
||||||
|
|
||||||
if (fSet.has("A")) children = children.filter(c => !c.name.startsWith("."));
|
|
||||||
|
|
||||||
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
|
|
||||||
longMode(io, state, children, fSet);
|
|
||||||
io.writeStdout(new TextEncoder().encode("\n"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
io.writeStdout(new TextEncoder().encode("\n"));
|
if (options.long) {
|
||||||
|
for (const entry of entries) {
|
||||||
|
listDirEntries(entry);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const entry of entries) {
|
||||||
|
//shortDirEntries(entry);
|
||||||
|
}
|
||||||
|
io.writeStdout(e.encode(`No support for short format yet\n`));
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
result: createSuccessResult(COMMAND_NAME),
|
result: createSuccessResult(COMMAND_NAME),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function listDirEntries(entry: { inode: number; path: string }): void {
|
||||||
|
const node = state.filesystem.getNode(entry.inode) as DirectoryNode;
|
||||||
|
|
||||||
|
if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\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])!);
|
||||||
|
if (!options.noSort) children = sortTreeNodes(state, children, options.reverse, options.sortBy);
|
||||||
|
|
||||||
|
if (!options.all && !options.almostAll) children = children.filter(c => !c.name.startsWith("."));
|
||||||
|
|
||||||
|
if (options.long) {
|
||||||
|
longMode(io, state, children, node);
|
||||||
|
if (options.recursive) io.writeStdout(e.encode("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.recursive) {
|
||||||
|
for (const child of children) {
|
||||||
|
if (child.type === TreeNodeType.Directory) {
|
||||||
|
let path;
|
||||||
|
if (entry.path === "/") {
|
||||||
|
path = "/" + child.name;
|
||||||
|
} else if (entry.path.endsWith("/")) {
|
||||||
|
path = entry.path + child.name;
|
||||||
|
} else path = entry.path + "/" + child.name;
|
||||||
|
listDirEntries({ inode: child.inode, path });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function longMode(io: CommandIO, state: ShellState, children: TreeNode[], current: TreeNode): void {
|
||||||
|
const e = new TextEncoder();
|
||||||
|
const buff: Uint8Array[] = [];
|
||||||
|
const nodes: TreeNode[] = [...children];
|
||||||
|
|
||||||
|
if (options.all) {
|
||||||
|
const parentNode = state.filesystem.getNode(current.parent)!;
|
||||||
|
|
||||||
|
const parent: TreeNode = { ...parentNode, name: ".." };
|
||||||
|
nodes.unshift(parent);
|
||||||
|
|
||||||
|
const cwd: TreeNode = { ...current, name: "." };
|
||||||
|
nodes.unshift(cwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate the string size of the biggerst node in the array;
|
||||||
|
// Sets 4 length for directories because the arbitrary size is 4096 later in the code
|
||||||
|
const maxInodeWidth = Math.max(...nodes.map(c => c.inode.toString().length));
|
||||||
|
|
||||||
|
const maxSizeWidth = Math.max(
|
||||||
|
...nodes.map(c => (c.type === TreeNodeType.File ? c.content.byteSize().toString().length : 4)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const maxChildrenWidth = Math.max(
|
||||||
|
...nodes.map(c =>
|
||||||
|
c.type === TreeNodeType.Directory ? Object.entries(c.children).length.toString().length : 2,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const namePadding = nodes.every(c => !c.name.includes(" "));
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
//Inode
|
||||||
|
if (options.inode) {
|
||||||
|
const inode = node.inode.toString().padStart(maxInodeWidth, " ");
|
||||||
|
buff.push(e.encode(inode + " "));
|
||||||
|
//io.writeStdout(e.encode(inode + " "));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mode
|
||||||
|
const mode: string = parseMode(node.mode);
|
||||||
|
|
||||||
|
switch (node.type) {
|
||||||
|
case TreeNodeType.Directory:
|
||||||
|
buff.push(e.encode("d" + mode + " "));
|
||||||
|
break;
|
||||||
|
case TreeNodeType.File:
|
||||||
|
buff.push(e.encode("-" + mode + " "));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Children amnt (later will be amnt of links)
|
||||||
|
const childAmnt =
|
||||||
|
node.type === TreeNodeType.Directory
|
||||||
|
? `${Object.entries(node.children).length.toString().padStart(maxChildrenWidth, " ")} `
|
||||||
|
: `${"10".padStart(maxChildrenWidth, " ")} `;
|
||||||
|
|
||||||
|
buff.push(e.encode(childAmnt));
|
||||||
|
|
||||||
|
// owner group
|
||||||
|
if (options.noGroup) {
|
||||||
|
buff.push(e.encode(`${state.users.get(node.owner)?.username} `));
|
||||||
|
} else if (options.noOwner) {
|
||||||
|
buff.push(e.encode(`${state.groups.get(node.group)?.groupname} `));
|
||||||
|
} else if (options.numericUidGid) {
|
||||||
|
buff.push(e.encode(`${node.owner} ${node.group} `));
|
||||||
|
} else {
|
||||||
|
buff.push(
|
||||||
|
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
|
||||||
|
// Sets the folder size to an arbitrary 4096, could change it later to smth else
|
||||||
|
let size;
|
||||||
|
if (options.humanReadable) {
|
||||||
|
const bytes = node.type === TreeNodeType.File ? node.content.byteSize() : 4096;
|
||||||
|
size = convertToUnit(bytes, 1, options.si ? 1000 : 1024);
|
||||||
|
} else {
|
||||||
|
size =
|
||||||
|
node.type === TreeNodeType.File
|
||||||
|
? `${node.content.byteSize().toString().padStart(maxSizeWidth, " ")} `
|
||||||
|
: `${"4096".padStart(maxSizeWidth, " ")} `;
|
||||||
|
}
|
||||||
|
|
||||||
|
buff.push(e.encode(size));
|
||||||
|
|
||||||
|
//Timestamp
|
||||||
|
// for now only mtime, need a helper function for all the formatting later on
|
||||||
|
const date = getDateTimestamp(node, options.timestamp);
|
||||||
|
if (options.fullTime) {
|
||||||
|
buff.push(
|
||||||
|
// Month + 1 because January is 0
|
||||||
|
e.encode(
|
||||||
|
`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
buff.push(
|
||||||
|
// Month + 1 because January is 0
|
||||||
|
e.encode(`${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Name
|
||||||
|
if (options.quoteName) {
|
||||||
|
buff.push(
|
||||||
|
e.encode(
|
||||||
|
`"${node.type === TreeNodeType.Directory ? node.name + '"' + (options.appendIndicator ? "/" : "") : node.name + '"'}\n`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const unpadded = `${node.name.includes(" ") && !options.literal ? "'" + node.name + "'" : node.name}`;
|
||||||
|
const name = `${!namePadding ? (unpadded.includes(" ") ? unpadded : " " + unpadded) : unpadded}`;
|
||||||
|
buff.push(
|
||||||
|
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) {
|
||||||
|
const owner = (mode >> 6) & 7;
|
||||||
|
const group = (mode >> 3) & 7;
|
||||||
|
const other = mode & 7;
|
||||||
|
|
||||||
|
const map = (bits: number) => {
|
||||||
|
let s = "";
|
||||||
|
s += bits & 4 ? "r" : "-";
|
||||||
|
s += bits & 2 ? "w" : "-";
|
||||||
|
s += bits & 1 ? "x" : "-";
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
|
||||||
|
return map(owner) + map(group) + map(other);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidSortMethod(value: string): value is SortTreeNodeBy {
|
||||||
|
return Object.values(SortTreeNodeBy).includes(value as SortTreeNodeBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidTimestamp(
|
||||||
|
value: string,
|
||||||
|
): value is SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME {
|
||||||
|
return Object.values(SortTreeNodeBy).includes(
|
||||||
|
value as SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): 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();
|
|
||||||
// Calculate the string size of the biggerst node in the array;
|
|
||||||
// Sets 4 length for directories because the arbitrary size is 4096 later in the code
|
|
||||||
const maxSizeWidth = Math.max(
|
|
||||||
...nodes.map(c => (c.type === TreeNodeType.File ? c.content.byteSize().toString().length : 4)),
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const node of nodes) {
|
|
||||||
if (flags.has("i") || flags.has("inode")) {
|
|
||||||
io.writeStdout(e.encode(node.inode.toString() + " "));
|
|
||||||
}
|
|
||||||
|
|
||||||
const mode: string = parseMode(node.mode);
|
|
||||||
|
|
||||||
switch (node.type) {
|
|
||||||
case TreeNodeType.Directory:
|
|
||||||
io.writeStdout(e.encode("d" + mode + " "));
|
|
||||||
break;
|
|
||||||
case TreeNodeType.File:
|
|
||||||
io.writeStdout(e.encode("-" + mode + " "));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.type === TreeNodeType.File) {
|
|
||||||
io.writeStdout(e.encode("0" + " "));
|
|
||||||
} else {
|
|
||||||
io.writeStdout(e.encode(Object.entries(node.children).length.toString() + " "));
|
|
||||||
}
|
|
||||||
|
|
||||||
io.writeStdout(
|
|
||||||
e.encode(state.users.get(node.owner)?.username + " " + state.groups.get(node.group)?.groupname + " "),
|
|
||||||
);
|
|
||||||
// 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
|
|
||||||
const size =
|
|
||||||
node.type === TreeNodeType.File
|
|
||||||
? node.content.byteSize().toString().padStart(maxSizeWidth, " ") + " "
|
|
||||||
: "4096".padStart(maxSizeWidth, " ") + " ";
|
|
||||||
|
|
||||||
io.writeStdout(e.encode(size));
|
|
||||||
|
|
||||||
// for now only mtime, need a helper function for all the formatting later on
|
|
||||||
const mtime = new Date(node.mtime);
|
|
||||||
io.writeStdout(
|
|
||||||
// Month + 1 because January is 0
|
|
||||||
e.encode(`${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}-${mtime.getMinutes()} `),
|
|
||||||
);
|
|
||||||
io.writeStdout(e.encode(node.name + "\n"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseMode(mode: number) {
|
|
||||||
const owner = (mode >> 6) & 7;
|
|
||||||
const group = (mode >> 3) & 7;
|
|
||||||
const other = mode & 7;
|
|
||||||
|
|
||||||
const map = (bits: number) => {
|
|
||||||
let s = "";
|
|
||||||
s += bits & 4 ? "r" : "-";
|
|
||||||
s += bits & 2 ? "w" : "-";
|
|
||||||
s += bits & 1 ? "x" : "-";
|
|
||||||
return s;
|
|
||||||
};
|
|
||||||
|
|
||||||
return map(owner) + map(group) + map(other);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const descriptor: CommandDescriptor = {
|
export const descriptor: CommandDescriptor = {
|
||||||
fn: main,
|
fn: main,
|
||||||
flags: [
|
flags: [
|
||||||
{ name: "l" },
|
{ name: "l" }, // done
|
||||||
{ name: "a" },
|
{ name: "a" }, // done
|
||||||
{ name: "A" },
|
{ name: "A" }, // done
|
||||||
{ name: "c" },
|
{ name: "c" },
|
||||||
{ name: "U" },
|
{ name: "U" }, // done
|
||||||
{ name: "g" },
|
{ name: "g" }, // done
|
||||||
{ name: "G" },
|
{ name: "G" }, // done
|
||||||
{ name: "h" },
|
{ name: "h" }, // done
|
||||||
{ name: "f" },
|
{ name: "f" }, // done
|
||||||
{ name: "x" },
|
{ name: "x" },
|
||||||
{ name: "X" },
|
{ name: "X" }, // done
|
||||||
{ name: "u" },
|
{ name: "u" },
|
||||||
{ name: "t" },
|
{ name: "t" }, // done
|
||||||
{ name: "S" },
|
{ name: "S" }, // done
|
||||||
{ name: "r" },
|
{ name: "r" }, // done
|
||||||
{ name: "R" },
|
{ name: "R" }, // done
|
||||||
{ name: "Q" },
|
{ name: "Q" }, // done
|
||||||
{ name: "p" },
|
{ name: "p" }, // done
|
||||||
{ name: "o" },
|
{ name: "o" }, // done
|
||||||
{ name: "n" },
|
{ name: "n" }, // done
|
||||||
{ name: "N" },
|
{ name: "N" }, // done
|
||||||
{ name: "L" },
|
{ name: "L" },
|
||||||
{ name: "m" },
|
{ name: "m" },
|
||||||
{ name: "i" },
|
{ name: "i" }, // done
|
||||||
{ name: "sort", takesValue: true },
|
{ name: "sort", takesValue: true }, // done
|
||||||
{ name: "time", takesValue: true },
|
{ name: "time", takesValue: true }, // done
|
||||||
{ name: "help" },
|
{ name: "help" },
|
||||||
{ name: "all" },
|
{ name: "all" }, // done
|
||||||
{ name: "almost-all" },
|
{ name: "almost-all" }, // done
|
||||||
{ name: "no-group" },
|
{ name: "full-time" }, // done
|
||||||
{ name: "human-readable" },
|
{ name: "no-group" }, // done
|
||||||
{ name: "reverse" },
|
{ name: "human-readable" }, // done
|
||||||
{ name: "recursive" },
|
{ name: "reverse" }, // done
|
||||||
{ name: "quote-name" },
|
{ name: "recursive" }, // done
|
||||||
{ name: "indicator-style" },
|
{ name: "quote-name" }, // done
|
||||||
{ name: "literal" },
|
{ name: "literal" }, // done
|
||||||
{ name: "numeric-uid-gid" },
|
{ name: "numeric-uid-gid" }, // done
|
||||||
{ name: "inode" },
|
{ name: "inode" }, // done
|
||||||
{ name: "si" },
|
{ name: "si" }, // done
|
||||||
{ name: "dereference" },
|
{ name: "dereference" },
|
||||||
],
|
],
|
||||||
name: COMMAND_NAME,
|
name: "ls",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
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,12 +8,7 @@ import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
|||||||
|
|
||||||
const COMMAND_NAME = "async";
|
const COMMAND_NAME = "async";
|
||||||
|
|
||||||
async function main(
|
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
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();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { TreeNodeType } from "@core/filesystem/treenode";
|
||||||
|
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||||
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { ShellError } from "@core/util/errors";
|
||||||
|
import { resolvePath } from "@core/util/path_resolver";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "touch";
|
||||||
|
|
||||||
|
//Need to implement escape sequences
|
||||||
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
|
for (const arg of args) {
|
||||||
|
const inode = resolvePath(state, arg);
|
||||||
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
|
let newState;
|
||||||
|
|
||||||
|
if (inode === -1) {
|
||||||
|
const index = arg.lastIndexOf("/");
|
||||||
|
let parentPath;
|
||||||
|
if (index === -1) {
|
||||||
|
parentPath = "./";
|
||||||
|
} else {
|
||||||
|
parentPath = arg.slice(0, index);
|
||||||
|
}
|
||||||
|
const fileName = arg.slice(index + 1);
|
||||||
|
const parent = resolvePath(state, parentPath);
|
||||||
|
|
||||||
|
newState = state.filesystem.createNode(
|
||||||
|
parent,
|
||||||
|
fileName,
|
||||||
|
TreeNodeType.File,
|
||||||
|
0o644,
|
||||||
|
session.user.uid,
|
||||||
|
session.user.gid,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
+1
-52
@@ -6,13 +6,7 @@ interface UnclosedQuoteError {
|
|||||||
timestamp: number;
|
timestamp: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ParsedCommand {
|
export function tokenize(input: string): string[] {
|
||||||
command: string;
|
|
||||||
flags: string[];
|
|
||||||
args: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
function tokenize(input: string): string[] {
|
|
||||||
enum State {
|
enum State {
|
||||||
Normal,
|
Normal,
|
||||||
SingleQuote,
|
SingleQuote,
|
||||||
@@ -98,48 +92,3 @@ 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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,33 +1,35 @@
|
|||||||
import { getCurrentSession } from "@core/session_manager";
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
import type { ShellState } from "@core/shell_state";
|
import type { ShellState } from "@core/shell_state";
|
||||||
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
|
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
|
||||||
import type { FileSystem } from "../filesystem/filesystem";
|
|
||||||
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
|
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
|
||||||
|
|
||||||
export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
|
export function resolvePath(state: ShellState, path: string): number {
|
||||||
|
const session = getCurrentSession(state);
|
||||||
const isAbsolute = path.startsWith("/");
|
const isAbsolute = path.startsWith("/");
|
||||||
|
|
||||||
const normalizedPath: string = path.replace(/^\/+|\/+$/g, "");
|
const normalizedPath: string = path.replace(/^\/+|\/+$/g, "");
|
||||||
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0);
|
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0);
|
||||||
|
|
||||||
if (pathComponents.length === 0 && isAbsolute) return 0;
|
if (pathComponents.length === 0 && isAbsolute) return 0;
|
||||||
if (pathComponents.length === 0) return cwd;
|
if (pathComponents.length === 0) return session.cwd;
|
||||||
|
|
||||||
let currentNode = isAbsolute ? fs.getRoot() : (fs.getNode(cwd) as DirectoryNode);
|
let currentNode = isAbsolute
|
||||||
if (!currentNode) {
|
? state.filesystem.getRoot()
|
||||||
throw {
|
: (state.filesystem.getNode(session.cwd) as DirectoryNode);
|
||||||
type: "NodeNotFound",
|
|
||||||
message: `CWD node under inode ${cwd} not found`,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
inode: cwd,
|
|
||||||
} satisfies NodeNotFoundError;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const name of pathComponents) {
|
if (!currentNode) return -1;
|
||||||
|
|
||||||
|
for (let i = 0; i < pathComponents.length; i++) {
|
||||||
|
const name = pathComponents[i]!;
|
||||||
if (name === ".") continue;
|
if (name === ".") continue;
|
||||||
|
|
||||||
if (name === "..") {
|
if (name === "..") {
|
||||||
currentNode = fs.getNode(currentNode.parent) as DirectoryNode;
|
currentNode = state.filesystem.getNode(currentNode.parent) as DirectoryNode;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name === "~") {
|
||||||
|
currentNode = state.filesystem.getNode(session.user.home) as DirectoryNode;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,7 +42,7 @@ export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
|
|||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
inode: currentNode.inode,
|
inode: currentNode.inode,
|
||||||
} satisfies NodeNotFoundError;
|
} satisfies NodeNotFoundError;
|
||||||
if (fs.isFile(inode))
|
if (state.filesystem.isFile(inode) && !(i === pathComponents.length - 1))
|
||||||
throw {
|
throw {
|
||||||
type: "NotADirectory",
|
type: "NotADirectory",
|
||||||
message: `Child node ${name} is not a directory`,
|
message: `Child node ${name} is not a directory`,
|
||||||
@@ -49,13 +51,13 @@ export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
|
|||||||
nodeType: TreeNodeType.File,
|
nodeType: TreeNodeType.File,
|
||||||
} satisfies NotADirectoryError;
|
} satisfies NotADirectoryError;
|
||||||
|
|
||||||
currentNode = fs.getNode(inode) as DirectoryNode;
|
currentNode = state.filesystem.getNode(inode) as DirectoryNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
return currentNode.inode;
|
return currentNode.inode;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveInode(state: ShellState, inode: number, abs: boolean = false): string {
|
export function resolveInode(state: ShellState, inode: number): string {
|
||||||
const node = state.filesystem.getNode(inode);
|
const node = state.filesystem.getNode(inode);
|
||||||
const components: string[] = [];
|
const components: string[] = [];
|
||||||
|
|
||||||
@@ -77,16 +79,38 @@ export function resolveInode(state: ShellState, inode: number, abs: boolean = fa
|
|||||||
components.reverse().unshift("");
|
components.reverse().unshift("");
|
||||||
let result = components.join("/");
|
let result = components.join("/");
|
||||||
|
|
||||||
if (abs) return result;
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
const home = resolveInode(state, getCurrentSession(state).user.home, true);
|
export function resolveInodeToHome(state: ShellState, inode: number): string {
|
||||||
const cwd = resolveInode(state, getCurrentSession(state).cwd, true);
|
const home = resolveInode(state, getCurrentSession(state).user.home);
|
||||||
|
let result = resolveInode(state, inode);
|
||||||
|
|
||||||
if (result.startsWith(home)) {
|
if (result.startsWith(home)) {
|
||||||
result = `~${result.slice(home.length)}`;
|
result = `~${result.slice(home.length)}`;
|
||||||
} else if (result.startsWith(cwd) && cwd !== "/") {
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveInodeToCwd(state: ShellState, inode: number): string {
|
||||||
|
const cwd = resolveInode(state, getCurrentSession(state).cwd);
|
||||||
|
let result = resolveInode(state, inode);
|
||||||
|
|
||||||
|
if (result.startsWith(cwd)) {
|
||||||
result = `.${result.slice(cwd.length)}`;
|
result = `.${result.slice(cwd.length)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function resolveInodeRelative(state: ShellState, inode: number, relative: number): string {
|
||||||
|
const rel = resolveInode(state, relative);
|
||||||
|
let result = resolveInode(state, inode);
|
||||||
|
|
||||||
|
if (result.startsWith(rel)) {
|
||||||
|
result = `.${result.slice(rel.length)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ export function dnTraverseTree(fs: FileSystem, root: number): number[] {
|
|||||||
const node = fs.getNode(stack.pop() as number);
|
const node = fs.getNode(stack.pop() as number);
|
||||||
if (node === undefined) continue;
|
if (node === undefined) continue;
|
||||||
|
|
||||||
if (node.inode !== 0) result.push(node.inode);
|
result.push(node.inode);
|
||||||
|
|
||||||
if (node.type === TreeNodeType.Directory) {
|
if (node.type === TreeNodeType.Directory) {
|
||||||
const children = Object.values(node.children);
|
const children = Object.values(node.children);
|
||||||
|
|||||||
+22
-20
File diff suppressed because one or more lines are too long
@@ -23,20 +23,19 @@ 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, flags: string[], args: string[]) {
|
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, 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;
|
||||||
|
|
||||||
@@ -68,7 +67,7 @@ export class Process {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const promise = this.CommandDescriptor.fn(io, this.State, this.Flags, this.Args);
|
const promise = this.CommandDescriptor.fn(io, this.State, 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 type { Signal } from "@core/signal";
|
import { SIGNAL_MAP, 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, flags: string[], args: string[]): number {
|
public createProcess(state: ShellState, descriptor: CommandDescriptor, args: string[]): number {
|
||||||
const pid = ++this._PIDIndex;
|
const pid = ++this._PIDIndex;
|
||||||
const process = new Process(pid, state, descriptor, flags, args);
|
const process = new Process(pid, state, descriptor, 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: "SIGKILL" } satisfies Signal);
|
process.sendSignal({ type: SIGNAL_MAP.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 {
|
||||||
|
|||||||
+27
-38
@@ -5,13 +5,12 @@ 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 { parseCommand } from "@core/util/parser";
|
import { tokenize } 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;
|
static #Instance: Shell | null;
|
||||||
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();
|
||||||
@@ -43,51 +42,37 @@ export class Shell {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
static async init(initialState: ShellState): Promise<Shell> {
|
static destroy(): void {
|
||||||
|
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 this.#Instance;
|
return Shell.#Instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Shell.#Promise) return Shell.#Promise;
|
Shell.#Instance = new Shell(initialState);
|
||||||
|
return Shell.#Instance;
|
||||||
Shell.#Promise = (async () => {
|
|
||||||
try {
|
|
||||||
Shell.#Instance = new Shell(initialState);
|
|
||||||
return Shell.#Instance;
|
|
||||||
} finally {
|
|
||||||
Shell.#Promise = null;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
return Shell.#Promise;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async execute(input: string): Promise<void> {
|
public async execute(input: string): Promise<void> {
|
||||||
let parsed;
|
const parsed = tokenize(input);
|
||||||
try {
|
|
||||||
parsed = parseCommand(input);
|
|
||||||
} catch {
|
|
||||||
const result = createErrorResult("ParseError", `Parsing error - ${input}`, {});
|
|
||||||
|
|
||||||
this._State = withExitCode(this._State, result.error.exitCode);
|
if (!parsed[0]) return;
|
||||||
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.command);
|
const command = COMMAND_REGISTRY.get(parsed[0]);
|
||||||
|
|
||||||
if (!command) {
|
if (!command) {
|
||||||
const encoded = new TextEncoder().encode(`Command ${parsed.command} not found`);
|
const encoded = new TextEncoder().encode(`Command ${parsed[0]} not found`);
|
||||||
|
|
||||||
const result = createErrorResult(
|
const result = createErrorResult(
|
||||||
"CommandNotFound",
|
"CommandNotFound",
|
||||||
`Command ${parsed.command} not found`,
|
`Command ${parsed[0]} not found`,
|
||||||
{ command: parsed.command },
|
{ command: parsed[0] },
|
||||||
parsed.command,
|
parsed[0],
|
||||||
createImmutableBuffer(encoded),
|
createImmutableBuffer(encoded),
|
||||||
createImmutableBuffer(new Uint8Array()),
|
createImmutableBuffer(new Uint8Array()),
|
||||||
);
|
);
|
||||||
@@ -102,7 +87,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.command,
|
parsed[0],
|
||||||
);
|
);
|
||||||
|
|
||||||
this._State = withExitCode(this._State, result.error.exitCode);
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
@@ -110,7 +95,9 @@ export class Shell {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const pid = this._ProcessManager.createProcess(this._State, command, parsed.flags, parsed.args);
|
parsed.shift();
|
||||||
|
|
||||||
|
const pid = this._ProcessManager.createProcess(this._State, command, parsed);
|
||||||
this.BoundPID = pid;
|
this.BoundPID = pid;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,10 +119,12 @@ export class Shell {
|
|||||||
return this._State;
|
return this._State;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static get Instance(): Shell | undefined {
|
public static Instance(initialState?: ShellState): Shell {
|
||||||
if (!Shell.#Instance) {
|
if (!Shell.#Instance) {
|
||||||
console.error("Shell has not been initialised yet. Call `await Shell.init()` first.");
|
if (!initialState) {
|
||||||
return;
|
throw new Error("Shell needs to be initialized first");
|
||||||
|
}
|
||||||
|
Shell.#Instance = new Shell(initialState);
|
||||||
}
|
}
|
||||||
return Shell.#Instance;
|
return Shell.#Instance;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export function convertToUnit(bytes: number, decimalPoint?: number, pow: 1024 | 1000 = 1024): string {
|
||||||
|
if (!+bytes) return "0";
|
||||||
|
|
||||||
|
const k: number = pow;
|
||||||
|
const dp: number = decimalPoint ? (decimalPoint < 0 ? 0 : decimalPoint) : 1;
|
||||||
|
const units: string[] = ["", "K", "M", "G", "T", "P"];
|
||||||
|
|
||||||
|
const i: number = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
|
||||||
|
return `${(bytes / Math.pow(k, i)).toFixed(dp)}${units[i]}`;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user