3 Commits
10 changed files with 527 additions and 18 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Result, ShellError } from "./result"; import type { ShellError } from "./errors";
import type { Result } from "./result";
import type { ShellState } from "./shell_state"; import type { ShellState } from "./shell_state";
type CommandFn = (state: ShellState, flags: string[], args: string[]) => CommandOutput<ShellError>; type CommandFn = (state: ShellState, flags: string[], args: string[]) => CommandOutput<ShellError>;
+2
View File
@@ -1,9 +1,11 @@
import type { CommandDescriptor } from "./command"; import type { CommandDescriptor } from "./command";
import { descriptor as cd } from "./commands/cd";
import { descriptor as echo } from "./commands/echo"; import { descriptor as echo } from "./commands/echo";
const reg = new Map<string, CommandDescriptor>(); const reg = new Map<string, CommandDescriptor>();
//reg.set(descriptor.name, descriptor <- imported const from command implementation file); //reg.set(descriptor.name, descriptor <- imported const from command implementation file);
reg.set(echo.name, echo); reg.set(echo.name, echo);
reg.set(cd.name, cd);
Object.freeze(reg); Object.freeze(reg);
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg; export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
+112
View File
@@ -0,0 +1,112 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import {
type InvalidArgumentsError,
type PathResolutionError,
type PermissionDeniedError,
type ShellError,
} from "@core/errors";
import type { FileSystem } from "@core/filesystem/filesystem";
import { resolveInode, resolvePath } from "@core/path_resolver";
import { createErrorResult, createSuccessResult } from "@core/result";
import { getCurrentSession } from "@core/session";
import { ShellState, withCwd } from "@core/shell_state";
import { createImmutableBuffer } from "@core/util/immutable_buffer";
export const COMMAND_NAME = "cd";
function main(state: ShellState, __flags: string[], args: string[]): CommandOutput<ShellError> {
if (args.length > 1) {
return {
state,
result: createErrorResult(
"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>;
}
let inode: number;
const session = getCurrentSession(state);
switch (args[0]) {
case undefined:
inode = session.user.home;
break;
case "-":
inode = session.pwd;
break;
default:
const result = safeResolvePath(state.filesystem, session.cwd, args[0]);
if (result.type === "error") {
return {
state,
result: createErrorResult(
"PathResolutionError",
"No such file or directory",
{ path: args[0]! },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
COMMAND_NAME,
),
} satisfies CommandOutput<PathResolutionError>;
}
inode = result.inode;
break;
}
if (state.filesystem.isFile(inode)) {
return {
state,
result: createErrorResult(
"PathResolutionError",
"No such file or directory",
{ path: resolveInode(state.filesystem, inode) },
createImmutableBuffer(new Uint8Array()),
createImmutableBuffer(new Uint8Array()),
COMMAND_NAME,
),
} satisfies CommandOutput<PathResolutionError>;
}
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,
),
} satisfies CommandOutput<PermissionDeniedError>;
}
const returnState = withCwd(state, inode);
return {
state: returnState,
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 = {
fn: main,
name: COMMAND_NAME,
};
+3 -1
View File
@@ -1,10 +1,12 @@
import type { CommandDescriptor, CommandOutput } from "@core/command"; import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { ResultSuccess, ShellError } from "@core/result"; import type { ShellError } from "@core/errors";
import type { ResultSuccess } from "@core/result";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import { createImmutableBuffer } from "@core/util/immutable_buffer"; import { createImmutableBuffer } from "@core/util/immutable_buffer";
export const COMMAND_NAME = "echo"; export const COMMAND_NAME = "echo";
//Need to implement escape sequences
function main(state: ShellState, flags: string[], args: string[]): CommandOutput<ShellError> { function main(state: ShellState, flags: string[], args: string[]): CommandOutput<ShellError> {
const joined = args.join(" "); const joined = args.join(" ");
const encoded = new TextEncoder().encode(joined); const encoded = new TextEncoder().encode(joined);
+223
View File
@@ -0,0 +1,223 @@
export interface ShellError {
readonly errorType: string;
readonly message: string;
readonly timestamp: number;
readonly exitCode: number;
readonly cause?: {
readonly name: string;
readonly message: string;
};
}
export function createShellError<E extends ShellError>(
errorType: E["errorType"],
message: string,
extraProps: Omit<E, keyof ShellError>,
cause?: { name: string; message: string },
): E {
let exitCode = EXIT_CODE_MAP[errorType] ?? 1;
// Special handling for signal termination
if (errorType === "SIGNAL_TERMINATION") {
const signalError = extraProps as unknown as { signalNumber: number };
exitCode = 128 + signalError.signalNumber;
}
const base: ShellError = Object.freeze({
errorType,
message,
timestamp: Date.now(),
exitCode,
...Object.freeze(cause !== undefined && { cause }),
});
return Object.freeze({ ...base, ...extraProps }) as E;
}
const EXIT_CODE_MAP: Record<string, number> = {
GenericError: 1,
InvalidArguments: 2,
UsageError: 63,
PathResolutionError: 64,
DataFormatError: 65,
FileNotFound: 66,
UserNotFound: 67,
HostNotFound: 68,
ServiceUnavailable: 69,
InternalSoftwareError: 70,
OperatingSystemError: 71,
SystemFileError: 72,
CannotCreateOutput: 73,
IoError: 74,
TemporaryFailure: 75,
TimeoutError: 75, // Same as TEMPFAIL
ProtocolError: 76,
PermissionDenied: 77,
ConfigurationError: 78,
CommandNotFound: 127,
NotExecutable: 126,
// SIGNAL_TERMINATION is handled dynamically (128 + signal)
};
/** Generic catch-all error (Exit 1) */
// Its actually the ShellError itself - no need for a custom type
/* export interface GenericError extends ShellError {
errorType: "GENERIC_ERROR";
} */
export interface InvalidArgumentsError extends ShellError {
errorType: "InvalidArguments";
expected: string; // e.g., "Usage: command <file>"
actual: string; // e.g., the user's input
}
// Codes 3 - 63 reserved for currently running processes, and their specific error handling.
/** Command used incorrectly (bad flag, wrong arg count) - maps to EX_USAGE (Exit 64) */
export interface UsageError extends ShellError {
errorType: "UsageError";
usageHint: string; // e.g., "command [-a] [-b] <filename>"
}
// ===================== 2. FILE / I/O ERRORS (Exit: 65, 66, 72, 73, 74) =====================
/** Input file does not exist or is unreadable (Exit 66 - EX_NOINPUT) */
export interface FileNotFoundError extends ShellError {
errorType: "FileNotFound";
path: string;
}
export interface PathResolutionError extends ShellError {
errorType: "PathResolutionError";
path: string;
}
/** Input data has invalid format (Exit 65 - EX_DATAERR) */
export interface DataFormatError extends ShellError {
errorType: "DataFormatError";
path?: string; // Optional: which file had bad data
line?: number; // Optional: line number if applicable
}
/** System file (e.g., /etc/passwd, /etc/hosts) is broken or missing (Exit 72 - EX_OSFILE) */
export interface SystemFileError extends ShellError {
errorType: "SystemFileError";
path: string;
}
/** Cannot create user-specified output file (Exit 73 - EX_CANTCREAT) */
export interface CannotCreateOutputError extends ShellError {
errorType: "CannotCreateOutput";
path: string;
reason: string; // e.g., "Directory does not exist", "Read-only filesystem"
}
/** I/O error while reading/writing a file (Exit 74 - EX_IOERR) */
export interface IOError extends ShellError {
errorType: "IoError";
path: string;
operation: "read" | "write" | "seek";
}
// ===================== 3. PERMISSION / USER ERRORS (Exit: 67, 77) =====================
/** Insufficient permission to access a resource (Exit 77 - EX_NOPERM) */
export interface PermissionDeniedError extends ShellError {
errorType: "PermissionDenied";
resource: string; // File path, port, socket, etc.
}
/** Specified user does not exist (Exit 67 - EX_NOUSER) */
export interface UserNotFoundError extends ShellError {
errorType: "UserNotFound";
username: string;
}
// ===================== 4. NETWORK / HOST / SERVICE ERRORS (Exit: 68, 69) =====================
/** Specified host does not exist or is unreachable (Exit 68 - EX_NOHOST) */
export interface HostNotFoundError extends ShellError {
errorType: "HostNotFound";
hostname: string;
}
/** Required service is unavailable (Exit 69 - EX_UNAVAILABLE) */
export interface ServiceUnavailableError extends ShellError {
errorType: "ServiceUnavailable";
service: string; // e.g., "database", "DNS", "SSH"
port?: number;
}
// ===================== 5. PROCESS / EXECUTION ERRORS (Exit: 126, 127, 71) =====================
/** Command not found (Exit 127 - POSIX standard) */
export interface CommandNotFoundError extends ShellError {
errorType: "CommandNotFound";
command: string;
}
/** Command found but not executable (Exit 126 - POSIX standard) */
export interface NotExecutableError extends ShellError {
errorType: "NotExecutable";
path: string;
}
/** Operating system error (fork, pipe, process table full) (Exit 71 - EX_OSERR) */
export interface OperatingSystemError extends ShellError {
errorType: "OperatingSystemError";
syscall: string; // e.g., "fork", "pipe", "execve"
errno?: number; // Optional: underlying OS error code
}
// ===================== 6. TIMING / RETRY ERRORS (Exit: 75) =====================
/** Temporary failure; user should retry (Exit 75 - EX_TEMPFAIL) */
export interface TemporaryFailureError extends ShellError {
errorType: "TemporaryFailure";
retryAfter?: number; // Optional: recommended seconds to wait
resource?: string; // Optional: what resource is temporarily busy
}
/** Operation timed out (Often mapped to EX_TEMPFAIL, Exit 75) */
export interface TimeoutError extends ShellError {
errorType: "TimeoutError";
timeoutSeconds: number;
operation: string; // e.g., "HTTP request", "Database query"
}
// ===================== 7. INTERNAL / CONFIGURATION ERRORS (Exit: 70, 78) =====================
/** Internal software error (bug, assertion failed) (Exit 70 - EX_SOFTWARE) */
export interface InternalSoftwareError extends ShellError {
errorType: "InternalSoftwareError";
component: string; // e.g., "parser", "network layer"
}
/** Configuration error in the program or system (Exit 78 - EX_CONFIG) */
export interface ConfigurationError extends ShellError {
errorType: "ConfigurationError";
configFile?: string;
key?: string; // Which config key is wrong
}
// ===================== 8. PROTOCOL / REMOTE ERRORS (Exit: 76) =====================
/** Remote system protocol error (Exit 76 - EX_PROTOCOL) */
export interface ProtocolError extends ShellError {
errorType: "ProtocolError";
remoteHost?: string;
protocol: string; // e.g., "HTTP", "SSH", "FTP"
statusCode?: number; // Optional: e.g., HTTP 400/500
}
// ===================== 9. SIGNAL TERMINATION (Exit: 128 + signal) =====================
/** Process was killed by a signal (Exit = 128 + signalNumber) */
export interface SignalTerminationError extends ShellError {
errorType: "SignalTermination";
signalNumber: number; // e.g., 9 (SIGKILL), 15 (SIGTERM), 2 (SIGINT)
signalName: string; // e.g., "SIGTERM", "SIGKILL"
}
+20 -1
View File
@@ -1,6 +1,6 @@
import type { NodeNotFoundError, NotADirectoryError } from "./filesystem/errors"; import type { NodeNotFoundError, NotADirectoryError } from "./filesystem/errors";
import type { FileSystem } from "./filesystem/filesystem"; import type { FileSystem } from "./filesystem/filesystem";
import { TreeNodeType, type DirectoryNode } 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(fs: FileSystem, cwd: number, path: string): number {
const isAbsolute = path.startsWith("/"); const isAbsolute = path.startsWith("/");
@@ -52,3 +52,22 @@ export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
return currentNode.inode; return currentNode.inode;
} }
export function resolveInode(fs: FileSystem, inode: number): string {
const node = fs.getNode(inode);
const components: string[] = [];
if (node === undefined) return "";
let currentInode = inode;
while (currentInode !== 0) {
const node = fs.getNode(currentInode) as TreeNode;
if (!node) break;
components.push(node.name);
currentInode = node.parent;
}
components.reverse();
components.unshift("");
return components.join("/");
}
+40 -13
View File
@@ -1,18 +1,8 @@
import type { ImmutableBuffer } from "./util/immutable_buffer"; import { createShellError, type ShellError } from "./errors";
import { createImmutableBuffer, type ImmutableBuffer } from "./util/immutable_buffer";
export interface ShellError {
readonly errorType: string;
readonly message: string;
readonly timestamp: number;
readonly cause?: {
readonly name: string;
readonly message: string;
};
}
export interface ResultError<E extends ShellError> { export interface ResultError<E extends ShellError> {
readonly type: "error"; readonly type: "error";
readonly exitCode: number;
readonly stdout: ImmutableBuffer; readonly stdout: ImmutableBuffer;
readonly stderr: ImmutableBuffer; readonly stderr: ImmutableBuffer;
readonly commandName?: string; readonly commandName?: string;
@@ -21,10 +11,47 @@ export interface ResultError<E extends ShellError> {
export interface ResultSuccess { export interface ResultSuccess {
readonly type: "success"; readonly type: "success";
readonly exitCode: number;
readonly stdout: ImmutableBuffer; readonly stdout: ImmutableBuffer;
readonly stderr: ImmutableBuffer; readonly stderr: ImmutableBuffer;
readonly exitCode: number;
readonly commandName?: string; readonly commandName?: string;
} }
export type Result<E extends ShellError> = ResultSuccess | ResultError<E>; export type Result<E extends ShellError> = ResultSuccess | ResultError<E>;
export function createErrorResult<E extends ShellError>(
errorType: E["errorType"],
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,
cause?: { name: string; message: string },
): ResultError<E> {
const error = createShellError<E>(errorType, message, extraProps, cause);
return Object.freeze({
type: "error",
stdout,
stderr,
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 }),
});
}
export function createSuccessResult(
commandName?: string,
exitCode?: number,
stdout?: ImmutableBuffer,
stderr?: ImmutableBuffer,
): ResultSuccess {
return Object.freeze({
type: "success",
stdout: stdout ?? createImmutableBuffer(new Uint8Array()),
stderr: stderr ?? createImmutableBuffer(new Uint8Array()),
exitCode: exitCode ?? 0,
// 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 }),
});
}
+112
View File
@@ -0,0 +1,112 @@
import { descriptor as cd } from "@core/commands/cd";
import type { ResultSuccess } from "@core/result";
import { getCurrentSession } from "@core/session";
import { createInitialShellState, withCwd, type ShellState } from "@core/shell_state";
import type { UserInfo } from "@core/user_info";
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
import { expect, test } from "vitest";
const testTree: FixtureNode = {
inode: 0,
name: "root",
type: "Dir",
children: [
{
inode: 1,
name: "hello.txt",
type: "File",
content: "Goodbye World!",
children: [],
},
{
inode: 2,
name: "sub",
type: "Dir",
children: [
{
inode: 3,
name: "world.txt",
type: "File",
content: "Goodbye!",
children: [],
},
{
inode: 4,
name: "bye",
type: "Dir",
children: [],
},
],
},
],
};
const fs = buildTestFS(testTree);
const users: Map<number, UserInfo> = new Map();
const user: UserInfo = {
name: "root",
uid: 0,
gid: 0,
group: [0],
home: 0,
};
users.set(0, user);
const state: ShellState = createInitialShellState(fs, users, user);
test("changes cwd to home", () => {
withCwd(state, 2);
const output = cd.fn(state, [], []);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultSuccess).exitCode).toBe(0);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(2);
});
test("changes cwd to pwd", () => {
withCwd(state, 2);
const output = cd.fn(state, [], ["-"]);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect(session.exitCode).toBe(0);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(2);
});
test("changes cwd to 4", () => {
const output = cd.fn(state, [], ["/sub/bye"]);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect(session.exitCode).toBe(0);
expect(session.cwd).toBe(4);
expect(session.pwd).toBe(0);
});
test("returns an error result (tried to enter a non existent location)", () => {
const output = cd.fn(state, [], ["/not/real"]);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
console.log(result);
expect(session.exitCode).toBe(0);
expect(session.cwd).toBe(4);
expect(session.pwd).toBe(0);
});
test("returns an error result (tried to enter a file)", () => {
const newState = cd.fn(state, [], ["/hello.txt"]).state;
const session = getCurrentSession(newState);
expect(session.exitCode).toBe(0);
expect(session.cwd).toBe(4);
expect(session.pwd).toBe(0);
});
+2 -1
View File
@@ -1,4 +1,5 @@
import { descriptor as echo } from "@core/commands/echo"; import { descriptor as echo } from "@core/commands/echo";
import type { ResultSuccess } from "@core/result";
import { createInitialShellState, type ShellState } from "@core/shell_state"; import { createInitialShellState, type ShellState } from "@core/shell_state";
import type { UserInfo } from "@core/user_info"; import type { UserInfo } from "@core/user_info";
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture"; import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
@@ -58,6 +59,6 @@ test("returns a Result of type success", () => {
const string = new TextDecoder().decode(output.result.stdout.toArray()); const string = new TextDecoder().decode(output.result.stdout.toArray());
expect(output.result.type).toBe("success"); expect(output.result.type).toBe("success");
expect(output.result.exitCode).toBe(0); expect((output.result as ResultSuccess).exitCode).toBe(0);
expect(string).toBe("hello world"); expect(string).toBe("hello world");
}); });
+11 -1
View File
@@ -1,4 +1,4 @@
import { resolvePath } from "@core/path_resolver"; import { resolveInode, resolvePath } from "@core/path_resolver";
import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers"; import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers";
import { buildTestFS } from "@tests/helpers/filesystems_fixture"; import { buildTestFS } from "@tests/helpers/filesystems_fixture";
import { depth7Tree } from "@tests/helpers/tree_fixture"; import { depth7Tree } from "@tests/helpers/tree_fixture";
@@ -61,3 +61,13 @@ describe("resolvePath", () => {
expectNodeNotFoundError(() => resolvePath(fs, 69, "/d3")); expectNodeNotFoundError(() => resolvePath(fs, 69, "/d3"));
}); });
}); });
describe("resolveInode", () => {
test("returns an the path from the d4 node", () => {
expect(resolveInode(fs, 4)).toBe("/d1/d2/d3/d4");
});
test("returns an empty string from a non existent inode", () => {
expect(resolveInode(fs, 999)).toBe("");
});
});