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 { descriptor as cd } from "./commands/cd";
|
||||
import { descriptor as echo } from "./commands/echo";
|
||||
import { descriptor as ls } from "./commands/ls";
|
||||
import { descriptor as testasync } from "./commands/testasync";
|
||||
|
||||
const reg = new Map<string, CommandDescriptor>();
|
||||
@@ -8,6 +9,7 @@ const reg = new Map<string, CommandDescriptor>();
|
||||
reg.set(echo.name, echo);
|
||||
reg.set(cd.name, cd);
|
||||
reg.set(testasync.name, testasync);
|
||||
reg.set(ls.name, ls);
|
||||
Object.freeze(reg);
|
||||
|
||||
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
||||
|
||||
+1
-15
@@ -10,7 +10,6 @@ import {
|
||||
type PermissionDeniedError,
|
||||
type ShellError,
|
||||
} from "@core/util/errors";
|
||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
import { resolveInode, resolvePath } from "@core/util/path_resolver";
|
||||
|
||||
export const COMMAND_NAME = "cd";
|
||||
@@ -28,8 +27,6 @@ async function main(
|
||||
"InvalidArguments",
|
||||
"The maximum ammount of arguments for this command is 1",
|
||||
{ expected: "cd <path>", actual: `cd ${args.toString().replace(/[,]/g, " ")}` },
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
COMMAND_NAME,
|
||||
),
|
||||
} satisfies CommandOutput<InvalidArgumentsError>;
|
||||
@@ -51,8 +48,6 @@ async function main(
|
||||
"PathResolutionError",
|
||||
"No such file or directory",
|
||||
{ path: args[0]! },
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
COMMAND_NAME,
|
||||
),
|
||||
} satisfies CommandOutput<PathResolutionError>;
|
||||
@@ -67,8 +62,6 @@ async function main(
|
||||
"PathResolutionError",
|
||||
"No such file or directory",
|
||||
{ path: resolveInode(state.filesystem, inode) },
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
COMMAND_NAME,
|
||||
),
|
||||
} satisfies CommandOutput<PathResolutionError>;
|
||||
@@ -77,14 +70,7 @@ async function main(
|
||||
if (!state.filesystem.canExecute(inode, session.user)) {
|
||||
return {
|
||||
state,
|
||||
result: createErrorResult(
|
||||
"PermissionDenied",
|
||||
"Permission denied",
|
||||
{ resource: args[0]! },
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
COMMAND_NAME,
|
||||
),
|
||||
result: createErrorResult("PermissionDenied", "Permission denied", { resource: args[0]! }, COMMAND_NAME),
|
||||
} satisfies CommandOutput<PermissionDeniedError>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||
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 { ShellError } from "@core/util/errors";
|
||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
|
||||
export const COMMAND_NAME = "echo";
|
||||
|
||||
@@ -15,17 +14,11 @@ async function main(
|
||||
args: string[],
|
||||
): Promise<CommandOutput<ShellError>> {
|
||||
const joined = args.join(" ");
|
||||
const encoded = new TextEncoder().encode(joined);
|
||||
const encoded = new TextEncoder().encode(joined + "\n");
|
||||
|
||||
io.writeStdout(encoded);
|
||||
|
||||
const result: ResultSuccess = {
|
||||
type: "success",
|
||||
exitCode: 0,
|
||||
stdout: createImmutableBuffer(new Uint8Array()),
|
||||
stderr: createImmutableBuffer(new Uint8Array()),
|
||||
commandName: COMMAND_NAME,
|
||||
};
|
||||
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||
|
||||
return {
|
||||
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 { ResultSuccess } from "@core/result";
|
||||
import type { ShellState } from "@core/shell_state";
|
||||
import { SIGNAL_MAP } from "@core/signal";
|
||||
import type { ShellError } from "@core/util/errors";
|
||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
|
||||
@@ -16,11 +17,11 @@ async function main(
|
||||
while (true) {
|
||||
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);
|
||||
io.writeStdout(encoded);
|
||||
|
||||
if (out.payload === "ctrl+c") {
|
||||
if (out.payload === "x") {
|
||||
const result: ResultSuccess = {
|
||||
type: "success",
|
||||
exitCode: 0,
|
||||
|
||||
+4
-4
@@ -24,16 +24,16 @@ export function createErrorResult<E extends ShellError>(
|
||||
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
|
||||
extraProps: Omit<E, keyof ShellError>,
|
||||
stdout: ImmutableBuffer,
|
||||
stderr: ImmutableBuffer,
|
||||
commandName?: string,
|
||||
stdout?: ImmutableBuffer,
|
||||
stderr?: ImmutableBuffer,
|
||||
cause?: { name: string; message: string },
|
||||
): ResultError<E> {
|
||||
const error = createShellError<E>(errorType, message, extraProps, cause);
|
||||
return Object.freeze({
|
||||
type: "error",
|
||||
stdout,
|
||||
stderr,
|
||||
stdout: stdout ?? createImmutableBuffer(new Uint8Array()),
|
||||
stderr: stderr ?? createImmutableBuffer(new Uint8Array()),
|
||||
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 !== undefined && { commandName }),
|
||||
|
||||
@@ -2,6 +2,12 @@ import { type HistoryState } from "./history_state";
|
||||
import { createShellState, type ShellState } from "./shell_state";
|
||||
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
|
||||
|
||||
export interface GroupInfo {
|
||||
readonly groupname: string;
|
||||
readonly gid: number;
|
||||
readonly members: number[];
|
||||
}
|
||||
|
||||
export interface UserInfo {
|
||||
readonly username: string;
|
||||
readonly uid: number;
|
||||
@@ -59,7 +65,7 @@ export function login(
|
||||
|
||||
const stack = [...state.sessionStack];
|
||||
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 {
|
||||
@@ -67,7 +73,7 @@ export function logout(state: ShellState): ShellState {
|
||||
const stack = [...state.sessionStack];
|
||||
stack.pop();
|
||||
|
||||
return createShellState(state.filesystem, state.users, stack);
|
||||
return createShellState(state.filesystem, state.users, state.groups, stack);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
+10
-1
@@ -1,22 +1,25 @@
|
||||
import type { FileSystem } from "./filesystem/filesystem";
|
||||
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";
|
||||
|
||||
export interface ShellState {
|
||||
readonly filesystem: FileSystem;
|
||||
readonly users: ReadonlyMap<number, UserInfo>;
|
||||
readonly groups: ReadonlyMap<number, GroupInfo>;
|
||||
readonly sessionStack: ReadonlyArray<SessionState>;
|
||||
}
|
||||
|
||||
export function createInitialShellState(
|
||||
filesystem: FileSystem,
|
||||
users: ReadonlyMap<number, UserInfo>,
|
||||
groups: ReadonlyMap<number, GroupInfo>,
|
||||
user: UserInfo,
|
||||
): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem,
|
||||
users,
|
||||
groups,
|
||||
sessionStack: Object.freeze([createInitialSessionState(user)]),
|
||||
});
|
||||
}
|
||||
@@ -24,11 +27,13 @@ export function createInitialShellState(
|
||||
export function createShellState(
|
||||
filesystem: FileSystem,
|
||||
users: ReadonlyMap<number, UserInfo>,
|
||||
groups: ReadonlyMap<number, GroupInfo>,
|
||||
sessionStack: ReadonlyArray<SessionState>,
|
||||
): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem,
|
||||
users,
|
||||
groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
});
|
||||
}
|
||||
@@ -52,6 +57,7 @@ export function withCwd(state: ShellState, inode: number): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem: state.filesystem,
|
||||
users: state.users,
|
||||
groups: state.groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
} satisfies ShellState);
|
||||
}
|
||||
@@ -75,6 +81,7 @@ export function withHistory(state: ShellState, input: string): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem: state.filesystem,
|
||||
users: state.users,
|
||||
groups: state.groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
} satisfies ShellState);
|
||||
}
|
||||
@@ -101,6 +108,7 @@ export function withEnv(state: ShellState, key: string, value: string): ShellSta
|
||||
return Object.freeze({
|
||||
filesystem: state.filesystem,
|
||||
users: state.users,
|
||||
groups: state.groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
} satisfies ShellState);
|
||||
}
|
||||
@@ -124,6 +132,7 @@ export function withExitCode(state: ShellState, exitCode: number): ShellState {
|
||||
return Object.freeze({
|
||||
filesystem: state.filesystem,
|
||||
users: state.users,
|
||||
groups: state.groups,
|
||||
sessionStack: Object.freeze(sessionStack),
|
||||
} satisfies ShellState);
|
||||
}
|
||||
|
||||
+8
-1
@@ -3,6 +3,13 @@ export type Input = string;
|
||||
//Payload optional because command that handles that signal
|
||||
// is going to know what shape it is, therefore also able to cast it;
|
||||
export type Signal = {
|
||||
type: string;
|
||||
type: SIGNAL_MAP;
|
||||
payload?: unknown;
|
||||
};
|
||||
|
||||
export enum SIGNAL_MAP {
|
||||
SIGINT = 2,
|
||||
SIGTERM = 3,
|
||||
SIGKILL = 9,
|
||||
INPUT = 10,
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ export interface ImmutableBuffer {
|
||||
readonly length: number;
|
||||
get(index: number): number;
|
||||
slice(start?: number, end?: number): ImmutableBuffer;
|
||||
byteSize(): number;
|
||||
toArray(): Uint8Array;
|
||||
}
|
||||
|
||||
@@ -22,10 +23,15 @@ export function createImmutableBuffer(input: Uint8Array): ImmutableBuffer {
|
||||
return Uint8Array.from(buffer);
|
||||
};
|
||||
|
||||
const byteSize = (): number => {
|
||||
return buffer.byteLength;
|
||||
};
|
||||
|
||||
const result: ImmutableBuffer = {
|
||||
length: buffer.length,
|
||||
get,
|
||||
slice,
|
||||
byteSize,
|
||||
toArray,
|
||||
};
|
||||
|
||||
|
||||
@@ -67,6 +67,11 @@ export function resolveInode(fs: FileSystem, inode: number): string {
|
||||
components.push(node.name);
|
||||
currentInode = node.parent;
|
||||
}
|
||||
if (components.length === 0) {
|
||||
components.push("/");
|
||||
return components.join("");
|
||||
}
|
||||
|
||||
components.reverse();
|
||||
components.unshift("");
|
||||
return components.join("/");
|
||||
|
||||
Reference in New Issue
Block a user