bigass changes
- ls beginnings, - added groups to shellstate - made buffers optional in result factory functions, - made an enum signal map, - fixed a minor bug in path resolver that didnt output the '/' if the inode was at root (inode 0) from the moment it was called - added code that attaches the shell to the built-in IDE terminal -- tests need fixing, new code needs testing
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
import type { CommandDescriptor } from "./command";
|
import type { CommandDescriptor } from "./command";
|
||||||
import { descriptor as cd } from "./commands/cd";
|
import { descriptor as cd } from "./commands/cd";
|
||||||
import { descriptor as echo } from "./commands/echo";
|
import { descriptor as echo } from "./commands/echo";
|
||||||
|
import { descriptor as ls } from "./commands/ls";
|
||||||
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>();
|
||||||
@@ -8,6 +9,7 @@ const reg = new Map<string, CommandDescriptor>();
|
|||||||
reg.set(echo.name, echo);
|
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);
|
||||||
Object.freeze(reg);
|
Object.freeze(reg);
|
||||||
|
|
||||||
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
||||||
|
|||||||
+1
-15
@@ -10,7 +10,6 @@ import {
|
|||||||
type PermissionDeniedError,
|
type PermissionDeniedError,
|
||||||
type ShellError,
|
type ShellError,
|
||||||
} from "@core/util/errors";
|
} from "@core/util/errors";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
|
||||||
import { resolveInode, resolvePath } from "@core/util/path_resolver";
|
import { resolveInode, resolvePath } from "@core/util/path_resolver";
|
||||||
|
|
||||||
export const COMMAND_NAME = "cd";
|
export const COMMAND_NAME = "cd";
|
||||||
@@ -28,8 +27,6 @@ async function main(
|
|||||||
"InvalidArguments",
|
"InvalidArguments",
|
||||||
"The maximum ammount of arguments for this command is 1",
|
"The maximum ammount of arguments for this command is 1",
|
||||||
{ expected: "cd <path>", actual: `cd ${args.toString().replace(/[,]/g, " ")}` },
|
{ expected: "cd <path>", actual: `cd ${args.toString().replace(/[,]/g, " ")}` },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
COMMAND_NAME,
|
COMMAND_NAME,
|
||||||
),
|
),
|
||||||
} satisfies CommandOutput<InvalidArgumentsError>;
|
} satisfies CommandOutput<InvalidArgumentsError>;
|
||||||
@@ -51,8 +48,6 @@ async function main(
|
|||||||
"PathResolutionError",
|
"PathResolutionError",
|
||||||
"No such file or directory",
|
"No such file or directory",
|
||||||
{ path: args[0]! },
|
{ path: args[0]! },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
COMMAND_NAME,
|
COMMAND_NAME,
|
||||||
),
|
),
|
||||||
} satisfies CommandOutput<PathResolutionError>;
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
@@ -67,8 +62,6 @@ async function main(
|
|||||||
"PathResolutionError",
|
"PathResolutionError",
|
||||||
"No such file or directory",
|
"No such file or directory",
|
||||||
{ path: resolveInode(state.filesystem, inode) },
|
{ path: resolveInode(state.filesystem, inode) },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
COMMAND_NAME,
|
COMMAND_NAME,
|
||||||
),
|
),
|
||||||
} satisfies CommandOutput<PathResolutionError>;
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
@@ -77,14 +70,7 @@ async function main(
|
|||||||
if (!state.filesystem.canExecute(inode, session.user)) {
|
if (!state.filesystem.canExecute(inode, session.user)) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
result: createErrorResult(
|
result: createErrorResult("PermissionDenied", "Permission denied", { resource: args[0]! }, COMMAND_NAME),
|
||||||
"PermissionDenied",
|
|
||||||
"Permission denied",
|
|
||||||
{ resource: args[0]! },
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
COMMAND_NAME,
|
|
||||||
),
|
|
||||||
} satisfies CommandOutput<PermissionDeniedError>;
|
} satisfies CommandOutput<PermissionDeniedError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
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 { ResultSuccess } from "@core/result";
|
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||||
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 { createImmutableBuffer } from "@core/util/immutable_buffer";
|
|
||||||
|
|
||||||
export const COMMAND_NAME = "echo";
|
export const COMMAND_NAME = "echo";
|
||||||
|
|
||||||
@@ -15,17 +14,11 @@ async function main(
|
|||||||
args: string[],
|
args: string[],
|
||||||
): Promise<CommandOutput<ShellError>> {
|
): Promise<CommandOutput<ShellError>> {
|
||||||
const joined = args.join(" ");
|
const joined = args.join(" ");
|
||||||
const encoded = new TextEncoder().encode(joined);
|
const encoded = new TextEncoder().encode(joined + "\n");
|
||||||
|
|
||||||
io.writeStdout(encoded);
|
io.writeStdout(encoded);
|
||||||
|
|
||||||
const result: ResultSuccess = {
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
type: "success",
|
|
||||||
exitCode: 0,
|
|
||||||
stdout: createImmutableBuffer(new Uint8Array()),
|
|
||||||
stderr: createImmutableBuffer(new Uint8Array()),
|
|
||||||
commandName: COMMAND_NAME,
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
state: state,
|
state: state,
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { TreeNodeType, type DirectoryNode, type TreeNode } from "@core/filesystem/treenode";
|
||||||
|
import { createErrorResult, createSuccessResult } 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";
|
||||||
|
import { dnTraverseTree } from "@core/util/tree_traversal";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "ls";
|
||||||
|
|
||||||
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
|
const nodes: number[] = [];
|
||||||
|
|
||||||
|
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),
|
||||||
|
);
|
||||||
|
|
||||||
|
const fSet = new Set(flags.filter(f => descriptor.flags?.some(flag => flag.name === f) && !vars.includes(f)));
|
||||||
|
|
||||||
|
if (fSet.size + vars.length < flags.length) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
|
nodes.push(session.cwd);
|
||||||
|
|
||||||
|
for (const arg of args) {
|
||||||
|
let inode;
|
||||||
|
try {
|
||||||
|
inode = resolvePath(state.filesystem, session.cwd, arg);
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult(
|
||||||
|
"PathResolutionError",
|
||||||
|
`No such file or directory`,
|
||||||
|
{ path: arg },
|
||||||
|
COMMAND_NAME,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (const node of nodes) {
|
||||||
|
const treenode: DirectoryNode = state.filesystem.getNode(node) as DirectoryNode;
|
||||||
|
|
||||||
|
// 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"));
|
||||||
|
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createSuccessResult(COMMAND_NAME),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
//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
|
||||||
|
io.writeStdout(
|
||||||
|
e.encode(
|
||||||
|
node.type === TreeNodeType.File
|
||||||
|
? node.content.byteSize().toString().padStart(maxSizeWidth, " ") + " "
|
||||||
|
: "4096".padStart(maxSizeWidth, " ") + " ",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// 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 = {
|
||||||
|
fn: main,
|
||||||
|
flags: [
|
||||||
|
{ name: "l" },
|
||||||
|
{ name: "a" },
|
||||||
|
{ name: "A" },
|
||||||
|
{ name: "c" },
|
||||||
|
{ name: "U" },
|
||||||
|
{ name: "g" },
|
||||||
|
{ name: "G" },
|
||||||
|
{ name: "h" },
|
||||||
|
{ name: "f" },
|
||||||
|
{ name: "x" },
|
||||||
|
{ name: "X" },
|
||||||
|
{ name: "u" },
|
||||||
|
{ name: "t" },
|
||||||
|
{ name: "S" },
|
||||||
|
{ name: "r" },
|
||||||
|
{ name: "R" },
|
||||||
|
{ name: "Q" },
|
||||||
|
{ name: "p" },
|
||||||
|
{ name: "o" },
|
||||||
|
{ name: "n" },
|
||||||
|
{ name: "N" },
|
||||||
|
{ name: "L" },
|
||||||
|
{ name: "m" },
|
||||||
|
{ name: "i" },
|
||||||
|
{ name: "sort", takesValue: true },
|
||||||
|
{ name: "time", takesValue: true },
|
||||||
|
{ name: "help" },
|
||||||
|
{ name: "all" },
|
||||||
|
{ name: "almost-all" },
|
||||||
|
{ name: "no-group" },
|
||||||
|
{ name: "human-readable" },
|
||||||
|
{ name: "reverse" },
|
||||||
|
{ name: "recursive" },
|
||||||
|
{ name: "quote-name" },
|
||||||
|
{ name: "indicator-style" },
|
||||||
|
{ name: "literal" },
|
||||||
|
{ name: "numeric-uid-gid" },
|
||||||
|
{ name: "inode" },
|
||||||
|
{ name: "si" },
|
||||||
|
{ name: "dereference" },
|
||||||
|
],
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
@@ -2,6 +2,7 @@ import type { CommandDescriptor, CommandOutput } from "@core/command";
|
|||||||
import type { CommandIO } from "@core/command_io";
|
import type { CommandIO } from "@core/command_io";
|
||||||
import type { ResultSuccess } from "@core/result";
|
import type { ResultSuccess } from "@core/result";
|
||||||
import type { ShellState } from "@core/shell_state";
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
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";
|
||||||
|
|
||||||
@@ -16,11 +17,11 @@ async function main(
|
|||||||
while (true) {
|
while (true) {
|
||||||
const out = await io.getSignal();
|
const out = await io.getSignal();
|
||||||
|
|
||||||
if (out.type === "INPUT") {
|
if (out.type === SIGNAL_MAP.INPUT) {
|
||||||
const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string);
|
const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string);
|
||||||
io.writeStdout(encoded);
|
io.writeStdout(encoded);
|
||||||
|
|
||||||
if (out.payload === "ctrl+c") {
|
if (out.payload === "x") {
|
||||||
const result: ResultSuccess = {
|
const result: ResultSuccess = {
|
||||||
type: "success",
|
type: "success",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
|
|||||||
+4
-4
@@ -24,16 +24,16 @@ export function createErrorResult<E extends ShellError>(
|
|||||||
message: string,
|
message: string,
|
||||||
// Omit - includes all properties of E except the ones that are already inside ShellError - basically skipping duplicates and allowing this to be a one-liner
|
// Omit - includes all properties of E except the ones that are already inside ShellError - basically skipping duplicates and allowing this to be a one-liner
|
||||||
extraProps: Omit<E, keyof ShellError>,
|
extraProps: Omit<E, keyof ShellError>,
|
||||||
stdout: ImmutableBuffer,
|
|
||||||
stderr: ImmutableBuffer,
|
|
||||||
commandName?: string,
|
commandName?: string,
|
||||||
|
stdout?: ImmutableBuffer,
|
||||||
|
stderr?: ImmutableBuffer,
|
||||||
cause?: { name: string; message: string },
|
cause?: { name: string; message: string },
|
||||||
): ResultError<E> {
|
): ResultError<E> {
|
||||||
const error = createShellError<E>(errorType, message, extraProps, cause);
|
const error = createShellError<E>(errorType, message, extraProps, cause);
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
type: "error",
|
type: "error",
|
||||||
stdout,
|
stdout: stdout ?? createImmutableBuffer(new Uint8Array()),
|
||||||
stderr,
|
stderr: stderr ?? createImmutableBuffer(new Uint8Array()),
|
||||||
error,
|
error,
|
||||||
// commandName is either undefined or string but when undefined - has to be ommited - we achieve that with a condition wrapped in a spread
|
// commandName is either undefined or string but when undefined - has to be ommited - we achieve that with a condition wrapped in a spread
|
||||||
...(commandName !== undefined && { commandName }),
|
...(commandName !== undefined && { commandName }),
|
||||||
|
|||||||
@@ -2,6 +2,12 @@ import { type HistoryState } from "./history_state";
|
|||||||
import { createShellState, type ShellState } from "./shell_state";
|
import { createShellState, type ShellState } from "./shell_state";
|
||||||
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
|
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
|
||||||
|
|
||||||
|
export interface GroupInfo {
|
||||||
|
readonly groupname: string;
|
||||||
|
readonly gid: number;
|
||||||
|
readonly members: number[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface UserInfo {
|
export interface UserInfo {
|
||||||
readonly username: string;
|
readonly username: string;
|
||||||
readonly uid: number;
|
readonly uid: number;
|
||||||
@@ -59,7 +65,7 @@ export function login(
|
|||||||
|
|
||||||
const stack = [...state.sessionStack];
|
const stack = [...state.sessionStack];
|
||||||
stack.push(createInitialSessionState(user));
|
stack.push(createInitialSessionState(user));
|
||||||
return createShellState(state.filesystem, state.users, stack);
|
return createShellState(state.filesystem, state.users, state.groups, stack);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function logout(state: ShellState): ShellState {
|
export function logout(state: ShellState): ShellState {
|
||||||
@@ -67,7 +73,7 @@ export function logout(state: ShellState): ShellState {
|
|||||||
const stack = [...state.sessionStack];
|
const stack = [...state.sessionStack];
|
||||||
stack.pop();
|
stack.pop();
|
||||||
|
|
||||||
return createShellState(state.filesystem, state.users, stack);
|
return createShellState(state.filesystem, state.users, state.groups, stack);
|
||||||
}
|
}
|
||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-1
@@ -1,22 +1,25 @@
|
|||||||
import type { FileSystem } from "./filesystem/filesystem";
|
import type { FileSystem } from "./filesystem/filesystem";
|
||||||
import { addHistoryEntry } from "./history_state";
|
import { addHistoryEntry } from "./history_state";
|
||||||
import type { UserInfo } from "./session_manager";
|
import type { GroupInfo, UserInfo } from "./session_manager";
|
||||||
import { createInitialSessionState, getCurrentSession, type SessionState } from "./session_manager";
|
import { createInitialSessionState, getCurrentSession, type SessionState } from "./session_manager";
|
||||||
|
|
||||||
export interface ShellState {
|
export interface ShellState {
|
||||||
readonly filesystem: FileSystem;
|
readonly filesystem: FileSystem;
|
||||||
readonly users: ReadonlyMap<number, UserInfo>;
|
readonly users: ReadonlyMap<number, UserInfo>;
|
||||||
|
readonly groups: ReadonlyMap<number, GroupInfo>;
|
||||||
readonly sessionStack: ReadonlyArray<SessionState>;
|
readonly sessionStack: ReadonlyArray<SessionState>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createInitialShellState(
|
export function createInitialShellState(
|
||||||
filesystem: FileSystem,
|
filesystem: FileSystem,
|
||||||
users: ReadonlyMap<number, UserInfo>,
|
users: ReadonlyMap<number, UserInfo>,
|
||||||
|
groups: ReadonlyMap<number, GroupInfo>,
|
||||||
user: UserInfo,
|
user: UserInfo,
|
||||||
): ShellState {
|
): ShellState {
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem,
|
filesystem,
|
||||||
users,
|
users,
|
||||||
|
groups,
|
||||||
sessionStack: Object.freeze([createInitialSessionState(user)]),
|
sessionStack: Object.freeze([createInitialSessionState(user)]),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -24,11 +27,13 @@ export function createInitialShellState(
|
|||||||
export function createShellState(
|
export function createShellState(
|
||||||
filesystem: FileSystem,
|
filesystem: FileSystem,
|
||||||
users: ReadonlyMap<number, UserInfo>,
|
users: ReadonlyMap<number, UserInfo>,
|
||||||
|
groups: ReadonlyMap<number, GroupInfo>,
|
||||||
sessionStack: ReadonlyArray<SessionState>,
|
sessionStack: ReadonlyArray<SessionState>,
|
||||||
): ShellState {
|
): ShellState {
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem,
|
filesystem,
|
||||||
users,
|
users,
|
||||||
|
groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -52,6 +57,7 @@ export function withCwd(state: ShellState, inode: number): ShellState {
|
|||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem: state.filesystem,
|
filesystem: state.filesystem,
|
||||||
users: state.users,
|
users: state.users,
|
||||||
|
groups: state.groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
} satisfies ShellState);
|
} satisfies ShellState);
|
||||||
}
|
}
|
||||||
@@ -75,6 +81,7 @@ export function withHistory(state: ShellState, input: string): ShellState {
|
|||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem: state.filesystem,
|
filesystem: state.filesystem,
|
||||||
users: state.users,
|
users: state.users,
|
||||||
|
groups: state.groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
} satisfies ShellState);
|
} satisfies ShellState);
|
||||||
}
|
}
|
||||||
@@ -101,6 +108,7 @@ export function withEnv(state: ShellState, key: string, value: string): ShellSta
|
|||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem: state.filesystem,
|
filesystem: state.filesystem,
|
||||||
users: state.users,
|
users: state.users,
|
||||||
|
groups: state.groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
} satisfies ShellState);
|
} satisfies ShellState);
|
||||||
}
|
}
|
||||||
@@ -124,6 +132,7 @@ export function withExitCode(state: ShellState, exitCode: number): ShellState {
|
|||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem: state.filesystem,
|
filesystem: state.filesystem,
|
||||||
users: state.users,
|
users: state.users,
|
||||||
|
groups: state.groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
} satisfies ShellState);
|
} satisfies ShellState);
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-1
@@ -3,6 +3,13 @@ export type Input = string;
|
|||||||
//Payload optional because command that handles that signal
|
//Payload optional because command that handles that signal
|
||||||
// is going to know what shape it is, therefore also able to cast it;
|
// is going to know what shape it is, therefore also able to cast it;
|
||||||
export type Signal = {
|
export type Signal = {
|
||||||
type: string;
|
type: SIGNAL_MAP;
|
||||||
payload?: unknown;
|
payload?: unknown;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export enum SIGNAL_MAP {
|
||||||
|
SIGINT = 2,
|
||||||
|
SIGTERM = 3,
|
||||||
|
SIGKILL = 9,
|
||||||
|
INPUT = 10,
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ export interface ImmutableBuffer {
|
|||||||
readonly length: number;
|
readonly length: number;
|
||||||
get(index: number): number;
|
get(index: number): number;
|
||||||
slice(start?: number, end?: number): ImmutableBuffer;
|
slice(start?: number, end?: number): ImmutableBuffer;
|
||||||
|
byteSize(): number;
|
||||||
toArray(): Uint8Array;
|
toArray(): Uint8Array;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,10 +23,15 @@ export function createImmutableBuffer(input: Uint8Array): ImmutableBuffer {
|
|||||||
return Uint8Array.from(buffer);
|
return Uint8Array.from(buffer);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const byteSize = (): number => {
|
||||||
|
return buffer.byteLength;
|
||||||
|
};
|
||||||
|
|
||||||
const result: ImmutableBuffer = {
|
const result: ImmutableBuffer = {
|
||||||
length: buffer.length,
|
length: buffer.length,
|
||||||
get,
|
get,
|
||||||
slice,
|
slice,
|
||||||
|
byteSize,
|
||||||
toArray,
|
toArray,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -67,6 +67,11 @@ export function resolveInode(fs: FileSystem, inode: number): string {
|
|||||||
components.push(node.name);
|
components.push(node.name);
|
||||||
currentInode = node.parent;
|
currentInode = node.parent;
|
||||||
}
|
}
|
||||||
|
if (components.length === 0) {
|
||||||
|
components.push("/");
|
||||||
|
return components.join("");
|
||||||
|
}
|
||||||
|
|
||||||
components.reverse();
|
components.reverse();
|
||||||
components.unshift("");
|
components.unshift("");
|
||||||
return components.join("/");
|
return components.join("/");
|
||||||
|
|||||||
+63
-5
@@ -10,13 +10,71 @@ namespace Termos {
|
|||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const message: string = "Hello, World!";
|
import { FileSystem } from "@core/filesystem/filesystem";
|
||||||
console.log(message);
|
import type { TreeNode } from "@core/filesystem/treenode";
|
||||||
|
import { getCurrentSession, type GroupInfo, type UserInfo } from "@core/session_manager";
|
||||||
|
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||||
|
import { resolveInode } from "@core/util/path_resolver";
|
||||||
|
import { deserializeFileSystem } from "@shell/serializer";
|
||||||
|
import { Shell } from "@shell/shell";
|
||||||
|
import { printTree } from "./util/tree_visualizer";
|
||||||
|
|
||||||
|
const rawJson = `{"atime": 1786341244,"children": [{"atime": 1786341264,"children": [{"atime": 1786341330,"children": [],"content": null,"ctime": 1786341330,"group": 1000,"inode": 2,"mode": 493,"mtime": 1786341330,"name": "subdir1","owner": 1000,"parent": 1,"type": "directory"}],"content": null,"ctime": 1786341330,"group": 1000,"inode": 1,"mode": 493,"mtime": 1786341330,"name": "folder1","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341269,"children": [{"atime": 1786341344,"children": [],"content": null,"ctime": 1786341344,"group": 1000,"inode": 4,"mode": 493,"mtime": 1786341344,"name": "subdir2","owner": 1000,"parent": 3,"type": "directory"},{"atime": 1786341345,"children": [{"atime": 1786341356,"children": [],"content": [],"ctime": 1786341356,"group": 1000,"inode": 6,"mode": 420,"mtime": 1786341356,"name": "empty-foo","owner": 1000,"parent": 5,"type": "regular"}],"content": null,"ctime": 1786341356,"group": 1000,"inode": 5,"mode": 493,"mtime": 1786341356,"name": "subdir3","owner": 1000,"parent": 3,"type": "directory"}],"content": null,"ctime": 1786341345,"group": 1000,"inode": 3,"mode": 493,"mtime": 1786341345,"name": "folder2","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341312,"children": [],"content": [72,101,108,108,111,44,32,87,111,114,108,100,33,10],"ctime": 1786341312,"group": 1000,"inode": 7,"mode": 420,"mtime": 1786341312,"name": "some-file","owner": 1000,"parent": 0,"type": "regular"}],"content": null,"ctime": 1786341312,"group": 1000,"inode": 0,"mode": 493,"mtime": 1786341312,"name": "root","owner": 1000,"parent": 0,"type": "directory"}`;
|
||||||
|
const base = deserializeFileSystem(rawJson);
|
||||||
|
|
||||||
|
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
|
||||||
|
|
||||||
|
const fs = FileSystem.init(base, overlay, base.size - 1);
|
||||||
|
|
||||||
|
console.log(printTree(fs, 0));
|
||||||
|
|
||||||
|
const users: Map<number, UserInfo> = new Map();
|
||||||
|
const groups: Map<number, GroupInfo> = new Map();
|
||||||
|
const user: UserInfo = {
|
||||||
|
username: "root",
|
||||||
|
uid: 1000,
|
||||||
|
gid: 0,
|
||||||
|
group: [1000],
|
||||||
|
home: 0,
|
||||||
|
};
|
||||||
|
const group: GroupInfo = {
|
||||||
|
groupname: "root",
|
||||||
|
gid: 1000,
|
||||||
|
members: [0],
|
||||||
|
};
|
||||||
|
users.set(1000, user);
|
||||||
|
groups.set(1000, group);
|
||||||
|
|
||||||
|
const state: ShellState = createInitialShellState(fs, users, groups, user);
|
||||||
|
await Shell.init(state);
|
||||||
|
|
||||||
|
Shell.Instance?.on("result", payload => {
|
||||||
|
const decoded = new TextDecoder().decode(payload.result.stdout.toArray());
|
||||||
|
process.stdout.write(decoded + "\n");
|
||||||
|
process.stdout.write(resolveInode(payload.state.filesystem, getCurrentSession(payload.state).cwd) + "\n> ");
|
||||||
|
});
|
||||||
|
|
||||||
|
/*
|
||||||
|
Cant do it like this because commands also use the stdout event right before returning a result so e.g. echo will print twice
|
||||||
|
|
||||||
|
Need to use this only if a continuous process is running
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Shell.Instance?.on("stdout", payload => {
|
||||||
|
const decoded = new TextDecoder().decode(payload.data);
|
||||||
|
process.stdout.write(decoded + "\n");
|
||||||
|
}); */
|
||||||
|
|
||||||
|
//console.clear();
|
||||||
|
process.stdout.write(resolveInode(Shell.Instance?.State.filesystem!, getCurrentSession(state).cwd) + "\n> ");
|
||||||
|
process.stdin.on("data", async data => {
|
||||||
|
if (Shell.Instance?.BoundPID !== null) {
|
||||||
|
Shell.Instance?.sendInput(data.toString().trim());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
console.clear();
|
|
||||||
process.stdout.write("> ");
|
|
||||||
process.stdin.on("data", data => {
|
|
||||||
const input = data.toString().trim();
|
const input = data.toString().trim();
|
||||||
|
await Shell.Instance?.execute(input);
|
||||||
});
|
});
|
||||||
|
|
||||||
//export { Termos };
|
//export { Termos };
|
||||||
|
|||||||
+31
-15
@@ -2,7 +2,7 @@ import type { CommandDescriptor } from "@core/command";
|
|||||||
import type { CommandIO } from "@core/command_io";
|
import type { CommandIO } from "@core/command_io";
|
||||||
import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result";
|
import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result";
|
||||||
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 type { ShellError, SignalTerminationError } from "@core/util/errors";
|
import type { ShellError, SignalTerminationError } from "@core/util/errors";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
import { EventEmitter } from "./event_emitter";
|
import { EventEmitter } from "./event_emitter";
|
||||||
@@ -128,9 +128,9 @@ export class Process {
|
|||||||
"GenericError",
|
"GenericError",
|
||||||
"Promised output from command function rejected",
|
"Promised output from command function rejected",
|
||||||
{},
|
{},
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
this.CommandDescriptor.name,
|
this.CommandDescriptor.name,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
{
|
{
|
||||||
name: "Caught error",
|
name: "Caught error",
|
||||||
message: String(error),
|
message: String(error),
|
||||||
@@ -144,26 +144,42 @@ export class Process {
|
|||||||
public sendSignal(signal: Signal): void {
|
public sendSignal(signal: Signal): void {
|
||||||
if (this._Settled) return;
|
if (this._Settled) return;
|
||||||
|
|
||||||
//Make global signals an enum later on
|
const result: ResultError<SignalTerminationError> = createErrorResult(
|
||||||
if (signal.type === "SIGKILL") {
|
"SignalTermination",
|
||||||
|
`Process ${this.PID} killed by a ${signal.type}`,
|
||||||
|
{ signalNumber: signal.type, signalName: SIGNAL_MAP[signal.type] },
|
||||||
|
this.CommandDescriptor.name,
|
||||||
|
);
|
||||||
|
|
||||||
|
switch (signal.type) {
|
||||||
|
case SIGNAL_MAP.SIGKILL:
|
||||||
|
this._SignalHandler = null;
|
||||||
|
this._Settled = true;
|
||||||
|
|
||||||
|
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||||
|
return;
|
||||||
|
|
||||||
|
case SIGNAL_MAP.SIGTERM:
|
||||||
if (this._SignalHandler !== null) {
|
if (this._SignalHandler !== null) {
|
||||||
this._SignalHandler(signal);
|
this._SignalHandler(signal);
|
||||||
this._SignalHandler = null;
|
this._SignalHandler = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
this._Settled = true;
|
this._Settled = true;
|
||||||
const result: ResultError<SignalTerminationError> = createErrorResult(
|
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||||
"SignalTermination",
|
|
||||||
`Process ${this.PID} killed by signal sigkill`,
|
|
||||||
{ signalNumber: 9, signalName: signal.type },
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
this.CommandDescriptor.name,
|
|
||||||
);
|
|
||||||
|
|
||||||
this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
|
|
||||||
return;
|
return;
|
||||||
} else {
|
case SIGNAL_MAP.SIGINT:
|
||||||
|
if (this._SignalHandler !== null) {
|
||||||
|
this._SignalHandler(signal);
|
||||||
|
this._SignalHandler = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
this._Settled = true;
|
||||||
|
|
||||||
|
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||||
|
return;
|
||||||
|
default:
|
||||||
if (this._SignalHandler !== null) {
|
if (this._SignalHandler !== null) {
|
||||||
this._SignalHandler(signal);
|
this._SignalHandler(signal);
|
||||||
this._SignalHandler = null;
|
this._SignalHandler = null;
|
||||||
|
|||||||
+14
-15
@@ -2,6 +2,7 @@ import { COMMAND_REGISTRY } from "@core/command_registry";
|
|||||||
import { createErrorResult, type Result } from "@core/result";
|
import { createErrorResult, type Result } from "@core/result";
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
|
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
|
||||||
|
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 { parseCommand } from "@core/util/parser";
|
||||||
@@ -14,13 +15,18 @@ export class Shell {
|
|||||||
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();
|
||||||
private _GlobalKeyMap: ReadonlyMap<string, string>;
|
private _GlobalKeyMap: ReadonlyMap<string, SIGNAL_MAP>;
|
||||||
|
|
||||||
public BoundPID: number | null = null;
|
public BoundPID: number | null = null;
|
||||||
|
|
||||||
private constructor(state: ShellState) {
|
private constructor(state: ShellState) {
|
||||||
this._State = Object.freeze(state);
|
this._State = Object.freeze(state);
|
||||||
this._GlobalKeyMap = new Map();
|
|
||||||
|
//Temporary solution for sigint keybind
|
||||||
|
const map = new Map();
|
||||||
|
map.set("ctrl+c", SIGNAL_MAP.SIGINT);
|
||||||
|
|
||||||
|
this._GlobalKeyMap = map;
|
||||||
|
|
||||||
this._ProcessManager.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
this._ProcessManager.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
||||||
this._ProcessManager.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
|
this._ProcessManager.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
|
||||||
@@ -62,14 +68,7 @@ export class Shell {
|
|||||||
try {
|
try {
|
||||||
parsed = parseCommand(input);
|
parsed = parseCommand(input);
|
||||||
} catch {
|
} catch {
|
||||||
const result = createErrorResult(
|
const result = createErrorResult("ParseError", `Parsing error - ${input}`, {});
|
||||||
"ParseError",
|
|
||||||
`Parsing error - ${input}`,
|
|
||||||
{},
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
"",
|
|
||||||
);
|
|
||||||
|
|
||||||
this._State = withExitCode(this._State, result.error.exitCode);
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
@@ -82,13 +81,15 @@ export class Shell {
|
|||||||
const command = COMMAND_REGISTRY.get(parsed.command);
|
const command = COMMAND_REGISTRY.get(parsed.command);
|
||||||
|
|
||||||
if (!command) {
|
if (!command) {
|
||||||
|
const encoded = new TextEncoder().encode(`Command ${parsed.command} not found`);
|
||||||
|
|
||||||
const result = createErrorResult(
|
const result = createErrorResult(
|
||||||
"CommandNotFound",
|
"CommandNotFound",
|
||||||
`Command ${parsed.command} not found`,
|
`Command ${parsed.command} not found`,
|
||||||
{ command: parsed.command },
|
{ command: parsed.command },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
parsed.command,
|
parsed.command,
|
||||||
|
createImmutableBuffer(encoded),
|
||||||
|
createImmutableBuffer(new Uint8Array()),
|
||||||
);
|
);
|
||||||
|
|
||||||
this._State = withExitCode(this._State, result.error.exitCode);
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
@@ -101,8 +102,6 @@ export class Shell {
|
|||||||
"PermissionDenied",
|
"PermissionDenied",
|
||||||
`Permission Denied`,
|
`Permission Denied`,
|
||||||
{ resource: `Execution of the ${command.name} command` },
|
{ resource: `Execution of the ${command.name} command` },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
parsed.command,
|
parsed.command,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -124,7 +123,7 @@ export class Shell {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (this.BoundPID !== null) {
|
if (this.BoundPID !== null) {
|
||||||
this._ProcessManager.sendSignal(this.BoundPID, { type: "INPUT", payload: input });
|
this._ProcessManager.sendSignal(this.BoundPID, { type: SIGNAL_MAP.INPUT, payload: input });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user