9 Commits
Author SHA1 Message Date
ChaosMaker 41739d7cf9 - Reworked internal signals
- Separated input passing from signal calling
- Exposed command registry to the broader codebase
- Moved command execution call to internal shell logic
- TTY is now expected to watch for stdout escape sequences to perform tasks
2026-11-23 13:31:22 +01:00
ChaosMaker dbffe5375e - Fixed default inode sorting order from being highest to lowes to lowest to highest (bug) 2026-11-22 12:55:41 +01:00
ChaosMaker 57773fc2ef - Fixed a bug where the current session stored in the shell instance wasnt getting updated after each state change 2026-11-20 15:14:47 +01:00
ChaosMaker 9a31a5985b - Updated package.json to contain the new version tag 2026-11-20 12:28:04 +01:00
ChaosMaker d825299e26 - Cleaned up old tests
- Changed `node:buffer` and `node:streams` imports to native `WebWorkers` imports;
- Fixed tests that used old `toPtr` and `fromPtr` functions to use the new NodePointer class methods
- Exposed pointer resolution helper functions to the consumer
2026-11-20 12:22:23 +01:00
ChaosMaker 2cf84ccd2f Exported Shell as a type in the index 2026-11-20 11:00:14 +01:00
ChaosMaker 204d713f91 - Fixed a bug in serializer that didnt account for parsed inodes to the inode index on the vdisk
- Fixed the touch command (for now only creates files)
- Fixed a minor bug in ls where it wouldnt return the correct result when a path provided in the args wouldnt resolve
2026-11-20 10:35:44 +01:00
ChaosMaker af6a9c8bda Update README.md 2026-11-17 22:59:04 +01:00
ChaosMaker 7310ae9671 Update README.md 2026-11-17 22:56:31 +01:00
38 changed files with 433 additions and 911 deletions
+32 -11
View File
@@ -25,19 +25,40 @@ It doesnt implement a website friendly interface on its own. Thats one of the de
[ref2]: https://pnpm.io/installation [ref2]: https://pnpm.io/installation
```bash ```bash
git clone https://git.gornodox.dev/ChaosMaker/termos.git pnpm add "https://git.gornodox.dev/ChaosMaker/termos/releases/download/0.1.0/termos-0.1.0.tgz"
cd termos
npm install
``` ```
## Running the project ## Minimal usecase
```bash ```typescript
npm run dev import { Termos } from "termos";
const shell = await Termos.getShell({
filesystem: {
// an example json representation of the filesystem
json: `{"dev": [{"id":0,"tree": {"atime": 1788458541,"children": [{"atime": 1794947961,"children": [],"content": [87,101,108,99,111,109,101,32,116,111,32,84,101,114,109,111,115,33,32,240,144,148,140,213,158,46,32,46,213,158,240,144,166,175,10],"ctime": 1794948078,"group": 0,"inode": 1,"link_count": 1,"mode": 420,"mtime": 1794948078,"name": "hello_world.txt","owner": 0,"parent": 0,"size": 35,"type": "regular"}],"content": null,"ctime": 1794947961,"group": 0,"inode": 0,"link_count": 2,"mode": 493,"mtime": 1794947961,"name": "root","owner": 0,"parent": 0,"size": 29,"type": "directory"}}]}`,
},
users: [{ username: "root", groups: ["root"], home: "/" }],
groups: ["root"],
general: { user: "root" },
});
// Subscribtion needed to recive command results and print out error messages
shell.on("result", payload => {
if (payload.result.type === "error") {
console.log(payload.result.error.message + "\n");
}
process.stdout.write("\n" + "Hello~\n> ");
});
// Subscribtion needed to recieve stdout buffer contents from shell
shell.on("stdout", payload => {
const decoded = new TextDecoder().decode(payload.data);
process.stdout.write(decoded);
});
// Takes in a string and executes it as a command
shell.execute("ls -l");
``` ```
## Running the test suite For more information, reference the [wiki]()
```bash
npm run test
```
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "termos", "name": "termos",
"version": "0.1.0", "version": "0.1.1",
"description": "Emulation library for a unix-like operating-system written in pure typescript", "description": "Emulation library for a unix-like operating-system written in pure typescript",
"files": [ "files": [
"dist" "dist"
+2 -2
View File
@@ -1,7 +1,7 @@
import type { Signal } from "./signal"; import type { Input } from "@shell/shell";
export interface CommandIO { export interface CommandIO {
writeStdout(data: Uint8Array): void; writeStdout(data: Uint8Array): void;
writeStderr(data: Uint8Array): void; writeStderr(data: Uint8Array): void;
getSignal(): Promise<Signal>; onInput(): Promise<Input>;
} }
+6
View File
@@ -3,9 +3,13 @@ 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 clear } from "./commands/clear";
import { descriptor as echo } from "./commands/echo"; import { descriptor as echo } from "./commands/echo";
import { descriptor as help } from "./commands/help";
import { descriptor as ls } from "./commands/ls"; import { descriptor as ls } from "./commands/ls";
import { descriptor as pwd } from "./commands/pwd"; import { descriptor as pwd } from "./commands/pwd";
import { descriptor as testasync } from "./commands/testasync"; import { descriptor as testasync } from "./commands/testasync";
import { descriptor as touch } from "./commands/touch";
export type CommandRegistry = ReadonlyMap<string, CommandDescriptor>;
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);
@@ -16,6 +20,8 @@ reg.set(ls.name, ls);
reg.set(cat.name, cat); reg.set(cat.name, cat);
reg.set(pwd.name, pwd); reg.set(pwd.name, pwd);
reg.set(clear.name, clear); reg.set(clear.name, clear);
reg.set(touch.name, touch);
reg.set(help.name, help);
Object.freeze(reg); Object.freeze(reg);
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg; export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
+2 -1
View File
@@ -7,7 +7,8 @@ import type { ShellError } from "@core/util/errors";
export const COMMAND_NAME = "clear"; export const COMMAND_NAME = "clear";
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> { async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
io.writeStdout(new TextEncoder().encode("\x1b[2J\x1b[0;0H")); const encoded = new TextEncoder().encode("\x1b[2J\x1b[0;0H");
io.writeStdout(encoded);
const result: ResultSuccess = createSuccessResult(COMMAND_NAME); const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
+27
View File
@@ -0,0 +1,27 @@
import type { CommandDescriptor, CommandOutput } from "@core/command";
import type { CommandIO } from "@core/command_io";
import { COMMAND_REGISTRY } from "@core/command_registry";
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 = "help";
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const e = new TextEncoder();
for (const entry of COMMAND_REGISTRY.keys()) {
io.writeStdout(e.encode(` ${entry}\n`));
}
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return {
state: state,
result,
};
}
export const descriptor: CommandDescriptor = {
fn: main,
name: COMMAND_NAME,
};
+14 -16
View File
@@ -219,8 +219,10 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
entries.push({ ptr: session.cwd, path: "." }); entries.push({ ptr: session.cwd, path: "." });
} else { } else {
for (const path of paths) { for (const path of paths) {
const ptr = resolvePath(state, path); let ptr;
if (!state.filesystem.exists(ptr)) { try {
ptr = resolvePath(state, path);
} catch {
return { return {
state, state,
result: createErrorResult( result: createErrorResult(
@@ -235,15 +237,8 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
} }
} }
if (options.long) { for (const entry of entries) {
for (const entry of entries) { listDirEntries(entry);
listDirEntries(entry);
}
} else {
for (const entry of entries) {
//shortDirEntries(entry);
}
io.writeStdout(e.encode(`No support for short format yet\n`));
} }
return { return {
@@ -255,7 +250,7 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
const node = state.filesystem.getNode(entry.ptr) as DirectoryNode; const node = state.filesystem.getNode(entry.ptr) as DirectoryNode;
if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`)); if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`));
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`)); if (options.long) io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
let children: DirEntry[] = Array.from(node.children.entries()).map(([name, inode]) => ({ let children: DirEntry[] = Array.from(node.children.entries()).map(([name, inode]) => ({
name, name,
@@ -269,11 +264,15 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
if (options.long) { if (options.long) {
longMode(io, state, children); longMode(io, state, children);
if (options.recursive) io.writeStdout(e.encode("\n")); } else {
//shortMode(io, state, children);
} }
if (options.recursive) { if (options.recursive) {
io.writeStdout(e.encode("\n"));
for (const c of children) { for (const c of children) {
// Skip if names match . or ..
if (c.name.match(/^[.]{1,2}$/)) continue; if (c.name.match(/^[.]{1,2}$/)) continue;
const child = state.filesystem.getNode(c.ptr)!; const child = state.filesystem.getNode(c.ptr)!;
if (child.type === NodeType.Directory) { if (child.type === NodeType.Directory) {
@@ -289,8 +288,9 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
} }
} }
function shortMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {}
function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void { function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {
const e = new TextEncoder();
const buff: Uint8Array[] = []; const buff: Uint8Array[] = [];
const nodes: DirEntry[] = [...children]; const nodes: DirEntry[] = [...children];
@@ -438,8 +438,6 @@ async function main(io: CommandIO, state: ShellState, args: string[]): Promise<C
} }
} }
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
export const descriptor: CommandDescriptor = { export const descriptor: CommandDescriptor = {
fn: main, fn: main,
flags: [ flags: [
+15 -18
View File
@@ -2,7 +2,6 @@ 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";
@@ -10,26 +9,24 @@ const COMMAND_NAME = "async";
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> { async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
while (true) { while (true) {
const out = await io.getSignal(); const sig = await io.onInput();
if (out.type === SIGNAL_MAP.INPUT) { const encoded = new TextEncoder().encode(("user pressed: " + sig.sequence + "\n") as string);
const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string); io.writeStdout(encoded);
io.writeStdout(encoded);
if (out.payload === "x") { if (sig.sequence === "\x03") {
const result: ResultSuccess = { const result: ResultSuccess = {
type: "success", type: "success",
exitCode: 0, exitCode: 0,
stdout: createImmutableBuffer(new Uint8Array()), stdout: createImmutableBuffer(new Uint8Array()),
stderr: createImmutableBuffer(new Uint8Array()), stderr: createImmutableBuffer(new Uint8Array()),
commandName: COMMAND_NAME, commandName: COMMAND_NAME,
}; };
return { return {
state: state, state: state,
result, result,
}; };
}
} }
} }
} }
+23 -24
View File
@@ -1,6 +1,7 @@
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 { createSuccessResult, type ResultSuccess } from "@core/result"; import { NodeType } from "@core/filesystem/node";
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
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 { ShellError } from "@core/util/errors"; import type { ShellError } from "@core/util/errors";
@@ -10,35 +11,33 @@ export const COMMAND_NAME = "touch";
//Need to implement escape sequences //Need to implement escape sequences
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> { async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
const session = getCurrentSession(state);
for (const arg of args) { for (const arg of args) {
const inode = resolvePath(state, arg); try {
const session = getCurrentSession(state); resolvePath(state, arg);
} catch {
let newState;
if (inode === -1) {
const index = arg.lastIndexOf("/"); const index = arg.lastIndexOf("/");
let parentPath;
if (index === -1) {
parentPath = "./";
} else {
parentPath = arg.slice(0, index);
}
const fileName = arg.slice(index + 1); const fileName = arg.slice(index + 1);
const parent = resolvePath(state, parentPath); const parentPath = index === -1 ? "./" : arg.slice(0, index + 1);
const pptr = resolvePath(state, parentPath);
newState = state.filesystem.createNode( state.filesystem.createNode(pptr, fileName, {
parent, type: NodeType.File,
fileName, mode: 0o644,
TreeNodeType.File, owner: session.user.uid,
0o644, group: session.user.gid,
session.user.uid, content: new Blob(),
session.user.gid, size: 0,
); });
} else {
continue;
} }
return {
state,
result: createErrorResult("AlreadyExists", "The file already exists", {}),
} satisfies CommandOutput<ShellError>;
} }
const result: ResultSuccess = createSuccessResult(COMMAND_NAME); const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
return { return {
+2 -4
View File
@@ -1,8 +1,6 @@
import type { UserInfo } from "@core/session_manager"; import type { UserInfo } from "@core/session_manager";
import { upTraverseTree } from "@core/util/tree_traversal"; import { upTraverseTree } from "@core/util/tree_traversal";
import { VDiskManager } from "@core/util/vdisk_manager"; import { VDiskManager } from "@core/util/vdisk_manager";
import type { Blob } from "node:buffer";
import type { Readable } from "node:stream";
import type { import type {
AlreadyExistsError, AlreadyExistsError,
DeviceNotFoundError, DeviceNotFoundError,
@@ -379,7 +377,7 @@ export class FileSystem {
mode: number; mode: number;
owner: number; owner: number;
group: number; group: number;
content: Blob | Readable; content: Blob | ReadableStream;
size: number; size: number;
} }
| { type: NodeType.Directory; mode: number; owner: number; group: number } | { type: NodeType.Directory; mode: number; owner: number; group: number }
@@ -507,7 +505,7 @@ export class FileSystem {
await dev.writeContent((node as FileNode).content, content); await dev.writeContent((node as FileNode).content, content);
} }
public streamContent(target: NodePointer): Readable { public streamContent(target: NodePointer): ReadableStream {
const dev = this._VDiskManager.getDisk(target.device); const dev = this._VDiskManager.getDisk(target.device);
const node = this.resolveNode(target); const node = this.resolveNode(target);
+7 -7
View File
@@ -1,6 +1,3 @@
import type { Blob } from "node:buffer";
import { Readable } from "node:stream";
import { blob } from "node:stream/consumers";
import { NodePointer, NodeType, type DirectoryNode, type Node, type NodeEntry, type NodeHash } from "./node"; import { NodePointer, NodeType, type DirectoryNode, type Node, type NodeEntry, type NodeHash } from "./node";
export function DefaultVDiskConfig(id: number): VDiskConfig { export function DefaultVDiskConfig(id: number): VDiskConfig {
@@ -53,7 +50,7 @@ export interface DataConfig {
export interface IDataStore { export interface IDataStore {
read(uuid: string): Promise<Uint8Array>; read(uuid: string): Promise<Uint8Array>;
stream(uuid: string): Readable; stream(uuid: string): ReadableStream;
put(uuid: string, blob: Blob): Promise<void>; put(uuid: string, blob: Blob): Promise<void>;
delete(uuid: string): Promise<void>; delete(uuid: string): Promise<void>;
has(uuid: string): Promise<boolean>; has(uuid: string): Promise<boolean>;
@@ -210,7 +207,7 @@ export class VDisk {
mode: number; mode: number;
owner: number; owner: number;
group: number; group: number;
content: Blob | Readable; content: Blob | ReadableStream;
size: number; size: number;
} }
| { type: NodeType.Directory; mode: number; owner: number; group: number } | { type: NodeType.Directory; mode: number; owner: number; group: number }
@@ -241,7 +238,10 @@ export class VDisk {
switch (data.type) { switch (data.type) {
case NodeType.File: case NodeType.File:
node = { ...base, type: NodeType.File, content: uuid, size: data.size }; node = { ...base, type: NodeType.File, content: uuid, size: data.size };
this.writeContent(uuid, data.content instanceof Readable ? await blob(data.content) : data.content); this.writeContent(
uuid,
data.content instanceof ReadableStream ? await new Response(data.content).blob() : data.content,
);
break; break;
case NodeType.Directory: case NodeType.Directory:
node = { ...base, type: NodeType.Directory, children: new Map() }; node = { ...base, type: NodeType.Directory, children: new Map() };
@@ -391,7 +391,7 @@ export class VDisk {
return this._dataStore.read(uuid); return this._dataStore.read(uuid);
} }
public streamContent(uuid: string): Readable { public streamContent(uuid: string): ReadableStream {
return this._dataStore.stream(uuid); return this._dataStore.stream(uuid);
} }
+5 -5
View File
@@ -1,9 +1,9 @@
const HISTORY_MAX_CAPACITY = 255; const HISTORY_MAX_CAPACITY = 255;
export type HistoryState = readonly string[]; export type HistoryState = readonly Uint8Array[];
export function addHistoryEntry(state: HistoryState, input: string): HistoryState { export function addHistoryEntry(state: HistoryState, input: Uint8Array): HistoryState {
const entries: string[] = [...state]; const entries: Uint8Array[] = [...state];
if (entries.length === HISTORY_MAX_CAPACITY) { if (entries.length === HISTORY_MAX_CAPACITY) {
entries.shift(); entries.shift();
@@ -12,11 +12,11 @@ export function addHistoryEntry(state: HistoryState, input: string): HistoryStat
entries.push(input); entries.push(input);
} }
const result: readonly string[] = entries; const result: readonly Uint8Array[] = entries;
return Object.freeze(result); return Object.freeze(result);
} }
export function getHistoryEntry(state: HistoryState, index: number): string { export function getHistoryEntry(state: HistoryState, index: number): Uint8Array {
const entry = state[index]; const entry = state[index];
if (entry === undefined) { if (entry === undefined) {
// Add a custom error object later // Add a custom error object later
+4 -1
View File
@@ -9,6 +9,7 @@ export interface ShellState {
readonly users: ReadonlyMap<number, UserInfo>; readonly users: ReadonlyMap<number, UserInfo>;
readonly groups: ReadonlyMap<number, GroupInfo>; readonly groups: ReadonlyMap<number, GroupInfo>;
readonly sessionStack: ReadonlyArray<SessionState>; readonly sessionStack: ReadonlyArray<SessionState>;
//readonly commmandRegistry: CommandRegistry;
} }
export function createInitialShellState( export function createInitialShellState(
@@ -16,12 +17,14 @@ export function createInitialShellState(
users: ReadonlyMap<number, UserInfo>, users: ReadonlyMap<number, UserInfo>,
groups: ReadonlyMap<number, GroupInfo>, groups: ReadonlyMap<number, GroupInfo>,
user: UserInfo, user: UserInfo,
//commandRegistry: CommandRegistry,
): ShellState { ): ShellState {
return Object.freeze({ return Object.freeze({
filesystem, filesystem,
users, users,
groups, groups,
sessionStack: Object.freeze([createInitialSessionState(user)]), sessionStack: Object.freeze([createInitialSessionState(user)]),
//commandRegistry,
}); });
} }
@@ -63,7 +66,7 @@ export function withCwd(state: ShellState, ptr: NodePointer): ShellState {
} satisfies ShellState); } satisfies ShellState);
} }
export function withHistory(state: ShellState, input: string): ShellState { export function withHistory(state: ShellState, input: Uint8Array): ShellState {
const session = getCurrentSession(state); const session = getCurrentSession(state);
const newSession = Object.freeze({ const newSession = Object.freeze({
-13
View File
@@ -1,13 +0,0 @@
//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: SIGNAL_MAP;
payload?: unknown;
};
export enum SIGNAL_MAP {
SIGINT = 2,
SIGTERM = 3,
SIGKILL = 9,
INPUT = 10,
}
+3 -2
View File
@@ -1,3 +1,5 @@
import type { SIGNAL_MAP } from "@shell/shell";
export interface ShellError { export interface ShellError {
readonly errorType: string; readonly errorType: string;
readonly message: string; readonly message: string;
@@ -219,6 +221,5 @@ export interface ProtocolError extends ShellError {
/** Process was killed by a signal (Exit = 128 + signalNumber) */ /** Process was killed by a signal (Exit = 128 + signalNumber) */
export interface SignalTerminationError extends ShellError { export interface SignalTerminationError extends ShellError {
errorType: "SignalTermination"; errorType: "SignalTermination";
signalNumber: number; // e.g., 9 (SIGKILL), 15 (SIGTERM), 2 (SIGINT) signal: SIGNAL_MAP;
signalName: string; // e.g., "SIGTERM", "SIGKILL"
} }
+2 -1
View File
@@ -6,13 +6,14 @@ interface UnclosedQuoteError {
timestamp: number; timestamp: number;
} }
export function tokenize(input: string): string[] { export function tokenize(buff: Uint8Array): string[] {
enum State { enum State {
Normal, Normal,
SingleQuote, SingleQuote,
DoubleQuote, DoubleQuote,
Escape, Escape,
} }
const input = new TextDecoder().decode(buff);
const tokens: string[] = []; const tokens: string[] = [];
const buffer: string[] = []; const buffer: string[] = [];
+1 -1
View File
@@ -131,7 +131,7 @@ function compareNode(
} }
case SortNodeBy.INODE: { case SortNodeBy.INODE: {
return r ? a.ptr.inode - b.ptr.inode : b.ptr.inode - a.ptr.inode; return r ? b.ptr.inode - a.ptr.inode : a.ptr.inode - b.ptr.inode;
} }
case SortNodeBy.TYPE: { case SortNodeBy.TYPE: {
+2 -4
View File
@@ -1,7 +1,5 @@
import type { Node } from "@core/filesystem/node"; import type { Node } from "@core/filesystem/node";
import type { IDataStore, IMetaStore } from "@core/filesystem/vdisk"; import type { IDataStore, IMetaStore } from "@core/filesystem/vdisk";
import type { Blob } from "node:buffer";
import { Readable } from "node:stream";
export class MemMetaStore implements IMetaStore { export class MemMetaStore implements IMetaStore {
private _data: Map<number, Node | null> = new Map(); private _data: Map<number, Node | null> = new Map();
@@ -35,11 +33,11 @@ export class MemDataStore implements IDataStore {
return new Uint8Array(buff); return new Uint8Array(buff);
} }
public stream(uuid: string): Readable { public stream(uuid: string): ReadableStream {
const blob = this._data.get(uuid); const blob = this._data.get(uuid);
if (!blob) throw new Error("Content missing - " + uuid); if (!blob) throw new Error("Content missing - " + uuid);
return Readable.from(blob.stream()); return blob.stream();
} }
public put(uuid: string, blob: Blob): Promise<void> { public put(uuid: string, blob: Blob): Promise<void> {
+21 -17
View File
@@ -1,7 +1,13 @@
import { getCurrentSession } from "@core/session_manager"; import { getCurrentSession } from "@core/session_manager";
import { resolvePointerToHome } from "@core/util/path_resolver"; import { resolvePointerToHome } from "@core/util/path_resolver";
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline";
import { Termos } from "./entry"; import { Termos } from "./entry";
process.stdin.setRawMode(true);
readline.emitKeypressEvents(process.stdin);
const rl = readline.createInterface({ input, output });
//import { deserializeFileSystem } from "@shell/serializer"; //import { deserializeFileSystem } from "@shell/serializer";
//import { Shell } from "@shell/shell"; //import { Shell } from "@shell/shell";
@@ -34,27 +40,25 @@ shell.on("result", payload => {
process.stdout.write("\n" + resolvePointerToHome(payload.state, getCurrentSession(payload.state).cwd) + "\n> "); process.stdout.write("\n" + resolvePointerToHome(payload.state, 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.on("stdout", payload => { shell.on("stdout", payload => {
const decoded = new TextDecoder().decode(payload.data); const decoded = new TextDecoder().decode(payload.data);
process.stdout.write(decoded); if (decoded === "\x1b[2J\x1b[0;0H") {
}); console.clear();
console.clear();
process.stdout.write(resolvePointerToHome(shell.State, getCurrentSession(shell.State).cwd) + "\n> ");
process.stdin.on("data", async data => {
if (shell.BoundPID !== null) {
shell.sendInput(data.toString().trim());
return; return;
} }
const input = data.toString().trim(); process.stdout.write(decoded);
await shell.execute(input);
}); });
//export { Termos }; let buff = "";
console.clear();
process.stdout.write(resolvePointerToHome(shell.State, getCurrentSession(shell.State).cwd) + "\n> ");
process.stdin.on("keypress", async (str, key) => {
if (key.sequence === "\f") console.clear();
if (buff.length > 3) buff = "";
buff = buff + key.name;
await shell.input(key);
});
+7
View File
@@ -1 +1,8 @@
export {
resolvePointer,
resolvePointerRelative,
resolvePointerToCwd,
resolvePointerToHome,
} from "@core/util/path_resolver";
export { Termos } from "./entry"; export { Termos } from "./entry";
export { type Shell } from "./shell/index";
+1
View File
@@ -0,0 +1 @@
export { type Shell } from "./shell";
+23 -41
View File
@@ -2,16 +2,15 @@ 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 { 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 { concatUint8Arrays, splitUint8Array } from "@termos/util/concat"; import { concatUint8Arrays, splitUint8Array } from "@termos/util/concat";
import { EventEmitter } from "./event_emitter"; import { EventEmitter } from "./event_emitter";
import type { ShellEventMap } from "./shell"; import { ShellEventMap, SIGNAL_MAP, type Input } from "./shell";
export class Process { export class Process {
private _SignalQueue: Signal[] = []; private _InputQueue: Input[] = [];
private _SignalHandler: ((signal: Signal) => void) | null = null; private _InputHandler: ((signal: Input) => void) | null = null;
private _StdoutChunks: Uint8Array[] = []; private _StdoutChunks: Uint8Array[] = [];
private _StderrChunks: Uint8Array[] = []; private _StderrChunks: Uint8Array[] = [];
private _Settled: boolean = false; private _Settled: boolean = false;
@@ -56,12 +55,12 @@ export class Process {
const io: CommandIO = { const io: CommandIO = {
writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data), writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data),
writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data), writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data),
getSignal: () => { onInput: () => {
const signal: Signal | undefined = this._SignalQueue.shift(); const signal: Input | undefined = this._InputQueue.shift();
if (signal !== undefined) return Promise.resolve(signal); if (signal !== undefined) return Promise.resolve(signal);
const promise = new Promise<Signal>(resolve => { const promise = new Promise<Input>(resolve => {
this._SignalHandler = resolve; this._InputHandler = resolve;
}); });
return promise; return promise;
}, },
@@ -115,51 +114,34 @@ export class Process {
}); });
} }
public sendSignal(signal: Signal): void { public sendInput(input: Input): void {
if (this._Settled) return;
if (this._InputHandler !== null) {
this._InputHandler(input);
this._InputHandler = null;
} else {
this._InputQueue.push(input);
}
}
public sendSignal(signal: SIGNAL_MAP): void {
if (this._Settled) return; if (this._Settled) return;
const result: ResultError<SignalTerminationError> = createErrorResult( const result: ResultError<SignalTerminationError> = createErrorResult(
"SignalTermination", "SignalTermination",
`Process ${this.Name}(${this.PID}) killed by a ${SIGNAL_MAP[signal.type]}(${signal.type})`, `Process ${this.Name} PID: ${this.PID} killed by a ${SIGNAL_MAP[signal]}`,
{ signalNumber: signal.type, signalName: SIGNAL_MAP[signal.type] }, { signal },
this.CommandDescriptor.name, this.CommandDescriptor.name,
); );
switch (signal.type) { switch (signal) {
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) {
this._SignalHandler(signal);
this._SignalHandler = null;
}
this._Settled = true;
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
return;
case SIGNAL_MAP.SIGINT: case SIGNAL_MAP.SIGINT:
if (this._SignalHandler !== null) {
this._SignalHandler(signal);
this._SignalHandler = null;
}
this._Settled = true; this._Settled = true;
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State }); this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
return; return;
default: default:
if (this._SignalHandler !== null) { break;
this._SignalHandler(signal);
this._SignalHandler = null;
} else {
this._SignalQueue.push(signal);
}
} }
} }
+14 -4
View File
@@ -1,9 +1,8 @@
import type { CommandDescriptor } from "@core/command"; import type { CommandDescriptor } from "@core/command";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import { SIGNAL_MAP, type Signal } from "@core/signal";
import { EventEmitter } from "./event_emitter"; import { EventEmitter } from "./event_emitter";
import { Process } from "./process"; import { Process } from "./process";
import type { ShellEventMap } from "./shell"; import { Input, ShellEventMap, SIGNAL_MAP } from "./shell";
export class ProcessManager { export class ProcessManager {
private _Processes: Map<number, Process> = new Map(); private _Processes: Map<number, Process> = new Map();
@@ -16,6 +15,7 @@ export class ProcessManager {
const process = new Process(pid, state, descriptor, args); const process = new Process(pid, state, descriptor, args);
this._Processes.set(pid, process); this._Processes.set(pid, process);
process.on("signal", payload => this._EventEmitter.emit("signal", payload));
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload)); process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
process.on("stderr", payload => this._EventEmitter.emit("stderr", payload)); process.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
process.on("result", payload => { process.on("result", payload => {
@@ -29,7 +29,7 @@ export class ProcessManager {
return pid; return pid;
} }
public sendSignal(pid: number, signal: Signal): void { public sendSignal(pid: number, signal: SIGNAL_MAP): void {
const process = this._Processes.get(pid); const process = this._Processes.get(pid);
if (!process) { if (!process) {
@@ -41,6 +41,16 @@ export class ProcessManager {
process.sendSignal(signal); process.sendSignal(signal);
} }
public sendInput(pid: number, input: Input): void {
const process = this._Processes.get(pid);
if (!process) {
//Implement a proper error object later to return to shell
console.error("PID not found");
return;
}
process.sendInput(input);
}
public kill(pid: number): void { public kill(pid: number): void {
const process = this._Processes.get(pid); const process = this._Processes.get(pid);
@@ -51,7 +61,7 @@ export class ProcessManager {
} }
//Make global signals an enum later //Make global signals an enum later
process.sendSignal({ type: SIGNAL_MAP.SIGKILL } satisfies Signal); process.sendSignal(SIGNAL_MAP.SIGINT);
} }
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 {
+5 -4
View File
@@ -1,7 +1,5 @@
import type { IDataStore, IMetaStore, VDiskConfig } from "@core/filesystem/vdisk"; import type { IDataStore, IMetaStore, VDiskConfig } from "@core/filesystem/vdisk";
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores"; import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
import { Blob } from "node:buffer";
import { randomUUID } from "node:crypto";
import { NodeType, type DirectoryNode, type FileNode, type Node, type SymlinkNode } from "../core/filesystem/node"; import { NodeType, type DirectoryNode, type FileNode, type Node, type SymlinkNode } from "../core/filesystem/node";
/* export function serializeFileSystem(map: ReadonlyMap<number, TreeNode | null>): string { /* export function serializeFileSystem(map: ReadonlyMap<number, TreeNode | null>): string {
@@ -10,6 +8,7 @@ import { NodeType, type DirectoryNode, type FileNode, type Node, type SymlinkNod
export function deserializeFileSystem(json: string): { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] { export function deserializeFileSystem(json: string): { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] {
const raw = JSON.parse(json); const raw = JSON.parse(json);
let index = 0;
// prettier-ignore // prettier-ignore
function parseNode(tree: any, parent: number, store: MemDataStore, map: Map<number, Node>): void { // eslint-disable-line @typescript-eslint/no-explicit-any function parseNode(tree: any, parent: number, store: MemDataStore, map: Map<number, Node>): void { // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -31,6 +30,8 @@ export function deserializeFileSystem(json: string): { dstore: IDataStore; mstor
return; return;
} }
if(tree.inode > index) index = tree.inode;
switch(tree.type) { switch(tree.type) {
case "directory": { case "directory": {
const children: Map<string, number> = new Map(); const children: Map<string, number> = new Map();
@@ -63,7 +64,7 @@ export function deserializeFileSystem(json: string): { dstore: IDataStore; mstor
break; break;
} }
case "regular": { case "regular": {
const uuid = randomUUID(); const uuid = crypto.randomUUID();
const fileNode: FileNode = { const fileNode: FileNode = {
type: NodeType.File, type: NodeType.File,
inode: tree.inode, inode: tree.inode,
@@ -121,7 +122,7 @@ export function deserializeFileSystem(json: string): { dstore: IDataStore; mstor
const config: VDiskConfig = { const config: VDiskConfig = {
id: dev.id, id: dev.id,
label: `disk-${dev.id}`, label: `disk-${dev.id}`,
index: 0, index,
readonly: false, readonly: false,
size: 1024 * 1024 * 1024 * 8, //8 GiB size: 1024 * 1024 * 1024 * 8, //8 GiB
base: map, base: map,
+69 -22
View File
@@ -1,36 +1,58 @@
import { COMMAND_REGISTRY } from "@core/command_registry"; 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, type SessionState } 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 { tokenize } from "@core/util/parser"; import { tokenize } from "@core/util/parser";
import { concatUint8Arrays } from "@termos/util/concat";
import { EventEmitter } from "./event_emitter"; import { EventEmitter } from "./event_emitter";
import { ProcessManager } from "./process_manager"; import { ProcessManager } from "./process_manager";
export interface TTYState {
width: number;
height: number;
}
export enum SIGNAL_MAP {
CLR = 0,
SIGINT = 1,
}
export interface Input {
sequence: string;
name: string;
ctrl: boolean;
meta: boolean;
shift: boolean;
}
export class Shell { export class Shell {
private _State: Readonly<ShellState>; private _State: Readonly<ShellState>;
private _Session: SessionState;
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, SIGNAL_MAP>; private _SignalMap: ReadonlyMap<string, SIGNAL_MAP> = new Map([
["\f", SIGNAL_MAP.CLR],
["\x03", SIGNAL_MAP.SIGINT],
]);
private readonly E: TextEncoder = new TextEncoder();
private readonly D: TextDecoder = new TextDecoder();
private _Stdin: Uint8Array = new Uint8Array();
public BoundPID: number | null = null; public BoundPID: number | null = null;
constructor(state: ShellState) { constructor(state: ShellState) {
this._State = Object.freeze(state); this._State = Object.freeze(state);
this._Session = state.sessionStack[state.sessionStack.length - 1]!;
//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));
this._ProcessManager.on("process", payload => this._EventEmitter.emit("process", payload)); this._ProcessManager.on("process", payload => this._EventEmitter.emit("process", payload));
this._ProcessManager.on("result", payload => { this._ProcessManager.on("result", payload => {
this._State = payload.state; this._State = payload.state;
this._Session = this._State.sessionStack[this._State.sessionStack.length - 1]!;
this._State = withExitCode( this._State = withExitCode(
this._State, this._State,
payload.result.type === "success" ? payload.result.exitCode : payload.result.error.exitCode, payload.result.type === "success" ? payload.result.exitCode : payload.result.error.exitCode,
@@ -39,9 +61,37 @@ export class Shell {
if (this.BoundPID === payload.pid) this.BoundPID = null; if (this.BoundPID === payload.pid) this.BoundPID = null;
this._EventEmitter.emit("result", payload); this._EventEmitter.emit("result", payload);
}); });
this._ProcessManager.on("signal", payload => this._EventEmitter.emit("signal", payload));
} }
public async execute(input: string): Promise<void> { public async input(key: {
sequence: string;
name: string;
ctrl: boolean;
meta: boolean;
shift: boolean;
}): Promise<void> {
const stdin = Uint8Array.from(this._Stdin);
switch (key.sequence) {
case "\x03":
if (!this.BoundPID) break;
const sig = this._SignalMap.get(key.sequence)!;
this._ProcessManager.sendSignal(this.BoundPID, sig);
break;
case "\r":
if (this.BoundPID) this._ProcessManager.sendInput(this.BoundPID, key);
this._Stdin = new Uint8Array();
this._execute(stdin);
break;
default:
if (this.BoundPID) this._ProcessManager.sendInput(this.BoundPID, key);
const buffer = this.E.encode(key.sequence);
this._Stdin = concatUint8Arrays([stdin, buffer]);
break;
}
}
private async _execute(input: Uint8Array): Promise<void> {
const parsed = tokenize(input); const parsed = tokenize(input);
if (!parsed[0]) return; if (!parsed[0]) return;
@@ -62,6 +112,7 @@ export class Shell {
); );
this._State = withExitCode(this._State, result.error.exitCode); this._State = withExitCode(this._State, result.error.exitCode);
this._Session = this._State.sessionStack[this._State.sessionStack.length - 1]!;
this._EventEmitter.emit("result", { pid: 0, result, state: this._State }); this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return; return;
} }
@@ -75,6 +126,7 @@ export class Shell {
); );
this._State = withExitCode(this._State, result.error.exitCode); this._State = withExitCode(this._State, result.error.exitCode);
this._Session = this._State.sessionStack[this._State.sessionStack.length - 1]!;
this._EventEmitter.emit("result", { pid: 0, result, state: this._State }); this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
return; return;
} }
@@ -85,24 +137,18 @@ export class Shell {
this.BoundPID = pid; this.BoundPID = pid;
} }
public sendInput(input: string): void { public getHistoryIndex(i: number): Uint8Array | undefined {
const signal = this._GlobalKeyMap.get(input); return this._Session.history[i];
if (signal !== undefined) {
if (this.BoundPID !== null) {
this._ProcessManager.sendSignal(this.BoundPID, { type: signal });
}
} else {
if (this.BoundPID !== null) {
this._ProcessManager.sendSignal(this.BoundPID, { type: SIGNAL_MAP.INPUT, payload: input });
}
}
} }
public get State(): Readonly<ShellState> { public get State(): Readonly<ShellState> {
return this._State; return this._State;
} }
public get Session(): Readonly<SessionState> {
return this._Session;
}
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 {
return this._EventEmitter.on(type, handler); return this._EventEmitter.on(type, handler);
} }
@@ -121,4 +167,5 @@ export interface ShellEventMap {
stdout: { pid: number; data: Uint8Array }; stdout: { pid: number; data: Uint8Array };
stderr: { pid: number; data: Uint8Array }; stderr: { pid: number; data: Uint8Array };
result: { pid: number; result: Result<ShellError>; state: ShellState }; result: { pid: number; result: Result<ShellError>; state: ShellState };
signal: { pid: number; sig: SIGNAL_MAP };
} }
+18
View File
@@ -0,0 +1,18 @@
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline";
process.stdin.setRawMode(true);
readline.emitKeypressEvents(process.stdin);
const rl = readline.createInterface({ input, output });
const d = new TextDecoder();
//@ts-ignore
rl.on("line", input => {
console.log(`Received: ${input}`);
});
process.stdin.on("keypress", async (str, key) => {
console.log(str, key);
});
-92
View File
@@ -1,92 +0,0 @@
import type { CommandIO } from "@core/command_io";
import { descriptor as cd } from "@core/commands/cd";
import type { ResultError, ResultSuccess } from "@core/result";
import type { UserInfo } from "@core/session_manager";
import { getCurrentSession } from "@core/session_manager";
import { withCwd, type ShellState } from "@core/shell_state";
import type { PathResolutionError } from "@core/util/errors";
import { Fixture } from "@tests/helpers/state_fixture";
import { expect, test } from "vitest";
const stdout: Uint8Array[] = [];
const stderr: Uint8Array[] = [];
const io: CommandIO = {
writeStdout: (data: Uint8Array) => {
stdout.push(data);
},
writeStderr: (data: Uint8Array) => {
stderr.push(data);
},
getSignal: () => {
return new Promise(() => {});
},
};
const users: Map<number, UserInfo> = new Map();
const user: UserInfo = {
username: "root",
uid: 0,
gid: 0,
group: [0],
home: 0,
};
users.set(0, user);
const state: ShellState = Fixture.State;
test("changes cwd to home", async () => {
let newState = withCwd(state, 2);
const output = await cd.fn(io, newState, [], []);
newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultSuccess).exitCode).toBe(0);
expect(session.cwd).toBe(Fixture.user.home);
expect(session.pwd).toBe(2);
});
test("changes cwd to pwd", async () => {
let newState = withCwd(state, 2);
const output = await cd.fn(io, newState, [], ["-"]);
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 4", async () => {
const output = await cd.fn(io, state, [], ["/folder2/subdir2"]);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultSuccess).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)", async () => {
const output = await cd.fn(io, state, [], ["/not/real"]);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultError<PathResolutionError>).error.exitCode).toBe(64);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(0);
});
test("returns an error result (tried to enter a file)", async () => {
const output = await cd.fn(io, state, [], ["/some-file"]);
const newState = output.state;
const result = output.result;
const session = getCurrentSession(newState);
expect((result as ResultError<PathResolutionError>).error.exitCode).toBe(64);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(0);
});
-33
View File
@@ -1,33 +0,0 @@
import type { CommandIO } from "@core/command_io";
import { descriptor as echo } from "@core/commands/echo";
import type { ResultSuccess } from "@core/result";
import { type ShellState } from "@core/shell_state";
import { Fixture } from "@tests/helpers/state_fixture";
import { expect, test } from "vitest";
const stdout: Uint8Array[] = [];
const stderr: Uint8Array[] = [];
const io: CommandIO = {
writeStdout: (data: Uint8Array) => {
stdout.push(data);
},
writeStderr: (data: Uint8Array) => {
stderr.push(data);
},
getSignal: () => {
return new Promise(() => {});
},
};
const state: ShellState = Fixture.State;
test("returns a Result of type success", async () => {
const output = await echo.fn(io, state, [], ["hello", "world"]);
const string = new TextDecoder().decode(stdout[0]);
expect(output.result.type).toBe("success");
expect((output.result as ResultSuccess).exitCode).toBe(0);
// Fix: added a newline character
expect(string).toEqual("hello world\n");
});
-36
View File
@@ -1,36 +0,0 @@
import type { ResultError } from "@core/result";
import { type ShellState } from "@core/shell_state";
import { SIGNAL_MAP } from "@core/signal";
import type { SignalTerminationError } from "@core/util/errors";
import { Shell } from "@shell/shell";
import { Fixture } from "@tests/helpers/state_fixture";
import { expect, test } from "vitest";
const state: ShellState = Fixture.State;
test("returns a Result of type success", async () => {
await Shell.init(state);
let result;
Shell.Instance?.on("result", payload => {
//const decoder = new TextDecoder();
//console.log(decoder.decode(payload.result.stdout.toArray()));
//console.log(payload);
result = payload.result;
expect(result.type).toBe("error");
expect((result as ResultError<SignalTerminationError>).error.exitCode).toEqual(130);
expect((result as ResultError<SignalTerminationError>).error.signalNumber).toEqual(SIGNAL_MAP.SIGINT);
});
await Shell.Instance?.execute("async");
Shell.Instance?.sendInput("a");
Shell.Instance?.sendInput("b");
Shell.Instance?.sendInput("c");
Shell.Instance?.sendInput("d");
Shell.Instance?.sendInput(
"right now technically anything goes because its just a plain string however i plan on improving this system a bit later on",
);
Shell.Instance?.sendInput("ctrl+c");
});
+85 -154
View File
@@ -1,14 +1,12 @@
// @core/filesystem/filesystem.test.ts // @core/filesystem/filesystem.test.ts
import { FileSystem, type FileSystemConfig } from "@core/filesystem/filesystem"; import { FileSystem, type FileSystemConfig } from "@core/filesystem/filesystem";
import { import {
fromPtr, NodePointer,
NodeType, NodeType,
toPtr,
type DirectoryNode, type DirectoryNode,
type FileNode, type FileNode,
type Node, type Node,
type NodeEntry, type NodeEntry,
type NodePointer,
type SymlinkNode, type SymlinkNode,
} from "@core/filesystem/node"; } from "@core/filesystem/node";
import { DefaultVDiskConfig, VDisk, type IDataStore, type IMetaStore } from "@core/filesystem/vdisk"; import { DefaultVDiskConfig, VDisk, type IDataStore, type IMetaStore } from "@core/filesystem/vdisk";
@@ -25,10 +23,8 @@ import {
expectNotADirectoryError, expectNotADirectoryError,
expectNotAFileError, expectNotAFileError,
} from "@tests/helpers/error_matchers"; } from "@tests/helpers/error_matchers";
import fc from "fast-check";
import { Blob } from "node:buffer";
import { Readable } from "node:stream";
import { afterEach, describe, expect, it, vi } from "vitest"; import { afterEach, describe, expect, it, vi } from "vitest";
("");
// ============================================================================ // ============================================================================
// Fixtures // Fixtures
@@ -89,7 +85,7 @@ function makeUser(overrides: Partial<UserInfo> = {}): UserInfo {
uid: 1000, uid: 1000,
gid: 1000, gid: 1000,
group: [], group: [],
home: 0, home: NodePointer.parse("0:0"),
...overrides, ...overrides,
}; };
} }
@@ -128,7 +124,7 @@ function buildReverseIndex(nodes: Map<number, Node>, deviceId: number): Map<Node
const [inode, pinode, name] = stack.pop()!; const [inode, pinode, name] = stack.pop()!;
const node = nodes.get(inode); const node = nodes.get(inode);
if (!node) continue; if (!node) continue;
const key = toPtr({ device_id: deviceId, inode }); const key = NodePointer.of(deviceId, inode);
const entry: NodeEntry = { pinode, pdevice_id: deviceId, name }; const entry: NodeEntry = { pinode, pdevice_id: deviceId, name };
const arr = index.get(key); const arr = index.get(key);
if (arr) arr.push(entry); if (arr) arr.push(entry);
@@ -161,7 +157,7 @@ function makeFakeDisk(id: number): FakeDisk {
unlinkNodeEntry: vi.fn(async () => undefined), unlinkNodeEntry: vi.fn(async () => undefined),
moveNodeEntry: vi.fn(async () => undefined), moveNodeEntry: vi.fn(async () => undefined),
writeContent: vi.fn(async () => undefined), writeContent: vi.fn(async () => undefined),
streamContent: vi.fn(() => Readable.from([Buffer.from("data")])), streamContent: vi.fn(() => new Blob(["data"]).stream()),
writeNodeEntry: vi.fn(async () => undefined), writeNodeEntry: vi.fn(async () => undefined),
}; };
return disk; return disk;
@@ -214,7 +210,7 @@ async function makeFS(
vi.spyOn(VDisk, "open").mockImplementation(async config => disks.get(config.id) as unknown as VDisk); vi.spyOn(VDisk, "open").mockImplementation(async config => disks.get(config.id) as unknown as VDisk);
const fs = FileSystem.init(vdiskConfigs, { const fs = await FileSystem.init(vdiskConfigs, {
maxNameLength: 255, maxNameLength: 255,
maxPathLength: Infinity, maxPathLength: Infinity,
maxSymlinkDepth: 40, maxSymlinkDepth: 40,
@@ -306,9 +302,9 @@ describe("FileSystem.init", () => {
* Fix is non-trivial (making `init` async changes the public API), so this * Fix is non-trivial (making `init` async changes the public API), so this
* documents the current behavior. When patched, this test should be deleted. * documents the current behavior. When patched, this test should be deleted.
*/ */
it("BUG: init returns before registerDisk resolves — no disk is available right after init", () => { it("BUG: init returns before registerDisk resolves — no disk is available right after init", async () => {
vi.spyOn(VDisk, "open").mockResolvedValue({} as VDisk); vi.spyOn(VDisk, "open").mockResolvedValue({} as VDisk);
const fs = FileSystem.init([ const fs = await FileSystem.init([
{ dstore: {} as IDataStore, mstore: {} as IMetaStore, config: DefaultVDiskConfig(0) }, { dstore: {} as IDataStore, mstore: {} as IMetaStore, config: DefaultVDiskConfig(0) },
]); ]);
expect(() => fs.getRoot()).toThrow(/system device not found/); expect(() => fs.getRoot()).toThrow(/system device not found/);
@@ -342,7 +338,7 @@ describe("FileSystem.init", () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
const longName = "a".repeat(256); const longName = "a".repeat(256);
expectInvalidNodeNameError(() => expectInvalidNodeNameError(() =>
fs.createNode(toPtr({ device_id: 0, inode: 0 }), longName, { fs.createNode(NodePointer.of(0, 0), longName, {
type: NodeType.Directory, type: NodeType.Directory,
mode: 0o755, mode: 0o755,
owner: 0, owner: 0,
@@ -357,7 +353,7 @@ describe("FileSystem.init", () => {
it("respects a custom maxNameLength", async () => { it("respects a custom maxNameLength", async () => {
const { fs } = await makeFS({ config: { maxNameLength: 5 } }); const { fs } = await makeFS({ config: { maxNameLength: 5 } });
expectInvalidNodeNameError(() => expectInvalidNodeNameError(() =>
fs.createNode(toPtr({ device_id: 0, inode: 0 }), "abcdef", { fs.createNode(NodePointer.of(0, 0), "abcdef", {
type: NodeType.Directory, type: NodeType.Directory,
mode: 0o755, mode: 0o755,
owner: 0, owner: 0,
@@ -375,7 +371,7 @@ describe("FileSystem.init", () => {
const { fs } = await makeFS({ config: { maxPathLength: 1, maxSymlinkDepth: 0 } }); const { fs } = await makeFS({ config: { maxPathLength: 1, maxSymlinkDepth: 0 } });
// No API path exercises these limits today; the calls below succeed regardless. // No API path exercises these limits today; the calls below succeed regardless.
expect(() => expect(() =>
fs.createNode(toPtr({ device_id: 0, inode: 0 }), "a-very-long-name", { fs.createNode(NodePointer.of(0, 0), "a-very-long-name", {
type: NodeType.Directory, type: NodeType.Directory,
mode: 0o755, mode: 0o755,
owner: 0, owner: 0,
@@ -436,7 +432,7 @@ describe("FileSystem.getNode", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }],
}); });
expect(fs.getNode(toPtr({ device_id: 0, inode: 1 }))).toBeDefined(); expect(fs.getNode(NodePointer.of(0, 1))).toBeDefined();
}); });
/** /**
@@ -444,7 +440,7 @@ describe("FileSystem.getNode", () => {
*/ */
it("returns undefined when the inode is missing on an existing device", async () => { it("returns undefined when the inode is missing on an existing device", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expect(fs.getNode(toPtr({ device_id: 0, inode: 99 }))).toBeUndefined(); expect(fs.getNode(NodePointer.of(0, 99))).toBeUndefined();
}); });
/** /**
@@ -452,7 +448,7 @@ describe("FileSystem.getNode", () => {
*/ */
it("returns undefined when the device does not exist", async () => { it("returns undefined when the device does not exist", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expect(fs.getNode(toPtr({ device_id: 99, inode: 0 }))).toBeUndefined(); expect(fs.getNode(NodePointer.of(99, 0))).toBeUndefined();
}); });
}); });
@@ -464,9 +460,9 @@ describe("FileSystem.exists", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }],
}); });
expect(fs.exists(toPtr({ device_id: 0, inode: 1 }))).toBe(true); expect(fs.exists(NodePointer.of(0, 1))).toBe(true);
expect(fs.exists(toPtr({ device_id: 0, inode: 42 }))).toBe(false); expect(fs.exists(NodePointer.of(0, 42))).toBe(false);
expect(fs.exists(toPtr({ device_id: 99, inode: 0 }))).toBe(false); expect(fs.exists(NodePointer.of(99, 0))).toBe(false);
}); });
}); });
@@ -482,7 +478,7 @@ describe("FileSystem.getNodeEntries", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }],
}); });
const entries = fs.getNodeEntries(toPtr({ device_id: 0, inode: 1 })); const entries = fs.getNodeEntries(NodePointer.of(0, 1));
expect(entries).toHaveLength(1); expect(entries).toHaveLength(1);
expect(entries![0]).toMatchObject({ pinode: 0, pdevice_id: 0, name: "a" }); expect(entries![0]).toMatchObject({ pinode: 0, pdevice_id: 0, name: "a" });
}); });
@@ -492,7 +488,7 @@ describe("FileSystem.getNodeEntries", () => {
*/ */
it("returns undefined when the pointer is not in the index", async () => { it("returns undefined when the pointer is not in the index", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expect(fs.getNodeEntries(toPtr({ device_id: 0, inode: 99 }))).toBeUndefined(); expect(fs.getNodeEntries(NodePointer.of(0, 99))).toBeUndefined();
}); });
/** /**
@@ -502,7 +498,7 @@ describe("FileSystem.getNodeEntries", () => {
*/ */
it("should throw DeviceNotFoundError when the device is missing", async () => { it("should throw DeviceNotFoundError when the device is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
await expectDeviceNotFoundError(() => fs.getNodeEntries(toPtr({ device_id: 99, inode: 0 }))); await expectDeviceNotFoundError(() => fs.getNodeEntries(NodePointer.of(99, 0)));
}); });
}); });
@@ -527,9 +523,9 @@ describe("FileSystem.isFile / isDirectory / isSymlink", () => {
}, },
], ],
}); });
const f = toPtr({ device_id: 0, inode: 1 }); const f = NodePointer.of(0, 1);
const d = toPtr({ device_id: 0, inode: 2 }); const d = NodePointer.of(0, 2);
const l = toPtr({ device_id: 0, inode: 3 }); const l = NodePointer.of(0, 3);
expect(fs.isFile(f)).toBe(true); expect(fs.isFile(f)).toBe(true);
expect(fs.isDirectory(f)).toBe(false); expect(fs.isDirectory(f)).toBe(false);
@@ -549,9 +545,9 @@ describe("FileSystem.isFile / isDirectory / isSymlink", () => {
*/ */
it("throws NodeNotFoundError when the node does not exist", async () => { it("throws NodeNotFoundError when the node does not exist", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expectNodeNotFoundError(() => fs.isFile(toPtr({ device_id: 0, inode: 99 }))); expectNodeNotFoundError(() => fs.isFile(NodePointer.of(0, 99)));
expectNodeNotFoundError(() => fs.isDirectory(toPtr({ device_id: 0, inode: 99 }))); expectNodeNotFoundError(() => fs.isDirectory(NodePointer.of(0, 99)));
expectNodeNotFoundError(() => fs.isSymlink(toPtr({ device_id: 0, inode: 99 }))); expectNodeNotFoundError(() => fs.isSymlink(NodePointer.of(0, 99)));
}); });
/** /**
@@ -560,9 +556,9 @@ describe("FileSystem.isFile / isDirectory / isSymlink", () => {
*/ */
it("should throw DeviceNotFoundError when the device is missing", async () => { it("should throw DeviceNotFoundError when the device is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
await expectDeviceNotFoundError(() => fs.isFile(toPtr({ device_id: 99, inode: 0 }))); await expectDeviceNotFoundError(() => fs.isFile(NodePointer.of(99, 0)));
await expectDeviceNotFoundError(() => fs.isDirectory(toPtr({ device_id: 99, inode: 0 }))); await expectDeviceNotFoundError(() => fs.isDirectory(NodePointer.of(99, 0)));
await expectDeviceNotFoundError(() => fs.isSymlink(toPtr({ device_id: 99, inode: 0 }))); await expectDeviceNotFoundError(() => fs.isSymlink(NodePointer.of(99, 0)));
}); });
}); });
@@ -577,7 +573,7 @@ describe("FileSystem.createNode", () => {
it("creates a file by delegating to the parent device", async () => { it("creates a file by delegating to the parent device", async () => {
const { fs, disks } = await makeFS(); const { fs, disks } = await makeFS();
const data = { type: NodeType.File as const, mode: 0o644, owner: 1, group: 1, content: new Blob(), size: 0 }; const data = { type: NodeType.File as const, mode: 0o644, owner: 1, group: 1, content: new Blob(), size: 0 };
fs.createNode(toPtr({ device_id: 0, inode: 0 }), "f", data); fs.createNode(NodePointer.of(0, 0), "f", data);
expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "f", data); expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "f", data);
}); });
@@ -587,7 +583,7 @@ describe("FileSystem.createNode", () => {
it("creates a directory", async () => { it("creates a directory", async () => {
const { fs, disks } = await makeFS(); const { fs, disks } = await makeFS();
const data = { type: NodeType.Directory as const, mode: 0o755, owner: 1, group: 1 }; const data = { type: NodeType.Directory as const, mode: 0o755, owner: 1, group: 1 };
fs.createNode(toPtr({ device_id: 0, inode: 0 }), "d", data); fs.createNode(NodePointer.of(0, 0), "d", data);
expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "d", data); expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "d", data);
}); });
@@ -597,7 +593,7 @@ describe("FileSystem.createNode", () => {
it("creates a symlink", async () => { it("creates a symlink", async () => {
const { fs, disks } = await makeFS(); const { fs, disks } = await makeFS();
const data = { type: NodeType.Symlink as const, mode: 0o777, owner: 1, group: 1, target: "/x" }; const data = { type: NodeType.Symlink as const, mode: 0o777, owner: 1, group: 1, target: "/x" };
fs.createNode(toPtr({ device_id: 0, inode: 0 }), "l", data); fs.createNode(NodePointer.of(0, 0), "l", data);
expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "l", data); expect(disks.get(0)!.createNodeEntry).toHaveBeenCalledWith(0, "l", data);
}); });
@@ -607,7 +603,7 @@ describe("FileSystem.createNode", () => {
it("throws DeviceNotFoundError when the parent's device is missing", async () => { it("throws DeviceNotFoundError when the parent's device is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
await expectDeviceNotFoundError(() => await expectDeviceNotFoundError(() =>
fs.createNode(toPtr({ device_id: 99, inode: 0 }), "x", { fs.createNode(NodePointer.of(99, 0), "x", {
type: NodeType.Directory, type: NodeType.Directory,
mode: 0o755, mode: 0o755,
owner: 0, owner: 0,
@@ -622,7 +618,7 @@ describe("FileSystem.createNode", () => {
it("throws NodeNotFoundError when the parent inode does not exist", async () => { it("throws NodeNotFoundError when the parent inode does not exist", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expectNodeNotFoundError(() => expectNodeNotFoundError(() =>
fs.createNode(toPtr({ device_id: 0, inode: 99 }), "x", { fs.createNode(NodePointer.of(0, 99), "x", {
type: NodeType.Directory, type: NodeType.Directory,
mode: 0o755, mode: 0o755,
owner: 0, owner: 0,
@@ -639,7 +635,7 @@ describe("FileSystem.createNode", () => {
devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }],
}); });
expectNotADirectoryError(() => expectNotADirectoryError(() =>
fs.createNode(toPtr({ device_id: 0, inode: 1 }), "x", { fs.createNode(NodePointer.of(0, 1), "x", {
type: NodeType.Directory, type: NodeType.Directory,
mode: 0o755, mode: 0o755,
owner: 0, owner: 0,
@@ -656,7 +652,7 @@ describe("FileSystem.createNode", () => {
devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }],
}); });
expectAlreadyExistsError(() => expectAlreadyExistsError(() =>
fs.createNode(toPtr({ device_id: 0, inode: 0 }), "f", { fs.createNode(NodePointer.of(0, 0), "f", {
type: NodeType.Directory, type: NodeType.Directory,
mode: 0o755, mode: 0o755,
owner: 0, owner: 0,
@@ -671,7 +667,7 @@ describe("FileSystem.createNode", () => {
it("throws InvalidNodeNameError when the name exceeds maxNameLength", async () => { it("throws InvalidNodeNameError when the name exceeds maxNameLength", async () => {
const { fs } = await makeFS({ config: { maxNameLength: 3 } }); const { fs } = await makeFS({ config: { maxNameLength: 3 } });
expectInvalidNodeNameError(() => expectInvalidNodeNameError(() =>
fs.createNode(toPtr({ device_id: 0, inode: 0 }), "four", { fs.createNode(NodePointer.of(0, 0), "four", {
type: NodeType.Directory, type: NodeType.Directory,
mode: 0o755, mode: 0o755,
owner: 0, owner: 0,
@@ -685,7 +681,7 @@ describe("FileSystem.createNode", () => {
*/ */
it("accepts a name whose length equals maxNameLength exactly", async () => { it("accepts a name whose length equals maxNameLength exactly", async () => {
const { fs, disks } = await makeFS({ config: { maxNameLength: 4 } }); const { fs, disks } = await makeFS({ config: { maxNameLength: 4 } });
fs.createNode(toPtr({ device_id: 0, inode: 0 }), "abcd", { fs.createNode(NodePointer.of(0, 0), "abcd", {
type: NodeType.Directory, type: NodeType.Directory,
mode: 0o755, mode: 0o755,
owner: 0, owner: 0,
@@ -707,7 +703,7 @@ describe("FileSystem.deleteNode", () => {
const { fs, disks } = await makeFS({ const { fs, disks } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }],
}); });
fs.deleteNode(toPtr({ device_id: 0, inode: 1 })); fs.deleteNode(NodePointer.of(0, 1));
expect(disks.get(0)!.unlinkNodeEntry).toHaveBeenCalledWith(0, "a"); expect(disks.get(0)!.unlinkNodeEntry).toHaveBeenCalledWith(0, "a");
}); });
@@ -716,7 +712,7 @@ describe("FileSystem.deleteNode", () => {
*/ */
it("throws IllegalMutationError when deleting device 0's root", async () => { it("throws IllegalMutationError when deleting device 0's root", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expectIllegalMutationError(() => fs.deleteNode(toPtr({ device_id: 0, inode: 0 }))); expectIllegalMutationError(() => fs.deleteNode(NodePointer.of(0, 0)));
}); });
/** /**
@@ -724,7 +720,7 @@ describe("FileSystem.deleteNode", () => {
*/ */
it("throws DeviceNotFoundError when the device does not exist", async () => { it("throws DeviceNotFoundError when the device does not exist", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
await expectDeviceNotFoundError(() => fs.deleteNode(toPtr({ device_id: 99, inode: 1 }))); await expectDeviceNotFoundError(() => fs.deleteNode(NodePointer.of(99, 1)));
}); });
}); });
@@ -740,7 +736,7 @@ describe("FileSystem.moveNode", () => {
const { fs, disks } = await makeFS({ const { fs, disks } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }],
}); });
fs.moveNode(toPtr({ device_id: 0, inode: 1 }), toPtr({ device_id: 0, inode: 0 }), "b"); fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 0), "b");
expect(disks.get(0)!.moveNodeEntry).toHaveBeenCalledWith(0, 0, "a", "b"); expect(disks.get(0)!.moveNodeEntry).toHaveBeenCalledWith(0, 0, "a", "b");
}); });
@@ -762,7 +758,7 @@ describe("FileSystem.moveNode", () => {
}, },
], ],
}); });
fs.moveNode(toPtr({ device_id: 0, inode: 3 }), toPtr({ device_id: 0, inode: 2 })); fs.moveNode(NodePointer.of(0, 3), NodePointer.of(0, 2));
expect(disks.get(0)!.moveNodeEntry).toHaveBeenCalledWith(1, 2, "f", undefined); expect(disks.get(0)!.moveNodeEntry).toHaveBeenCalledWith(1, 2, "f", undefined);
}); });
@@ -782,7 +778,7 @@ describe("FileSystem.moveNode", () => {
}, },
], ],
}); });
fs.moveNode(toPtr({ device_id: 0, inode: 3 }), toPtr({ device_id: 0, inode: 2 }), "g"); fs.moveNode(NodePointer.of(0, 3), NodePointer.of(0, 2), "g");
expect(disks.get(0)!.moveNodeEntry).toHaveBeenCalledWith(1, 2, "f", "g"); expect(disks.get(0)!.moveNodeEntry).toHaveBeenCalledWith(1, 2, "f", "g");
}); });
@@ -791,9 +787,7 @@ describe("FileSystem.moveNode", () => {
*/ */
it("throws DeviceNotFoundError when the source device is missing", async () => { it("throws DeviceNotFoundError when the source device is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
await expectDeviceNotFoundError(() => await expectDeviceNotFoundError(() => fs.moveNode(NodePointer.of(99, 1), NodePointer.of(0, 0)));
fs.moveNode(toPtr({ device_id: 99, inode: 1 }), toPtr({ device_id: 0, inode: 0 })),
);
}); });
/** /**
@@ -803,9 +797,7 @@ describe("FileSystem.moveNode", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }],
}); });
await expectDeviceNotFoundError(() => await expectDeviceNotFoundError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(99, 0)));
fs.moveNode(toPtr({ device_id: 0, inode: 1 }), toPtr({ device_id: 99, inode: 0 })),
);
}); });
/** /**
@@ -813,9 +805,7 @@ describe("FileSystem.moveNode", () => {
*/ */
it("throws NodeNotFoundError when the source node is missing", async () => { it("throws NodeNotFoundError when the source node is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expectNodeNotFoundError(() => expectNodeNotFoundError(() => fs.moveNode(NodePointer.of(0, 99), NodePointer.of(0, 0)));
fs.moveNode(toPtr({ device_id: 0, inode: 99 }), toPtr({ device_id: 0, inode: 0 })),
);
}); });
/** /**
@@ -825,9 +815,7 @@ describe("FileSystem.moveNode", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })) }],
}); });
expectIllegalMutationError(() => expectIllegalMutationError(() => fs.moveNode(NodePointer.of(0, 0), NodePointer.of(0, 1)));
fs.moveNode(toPtr({ device_id: 0, inode: 0 }), toPtr({ device_id: 0, inode: 1 })),
);
}); });
/** /**
@@ -837,9 +825,7 @@ describe("FileSystem.moveNode", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }],
}); });
expectNodeNotFoundError(() => expectNodeNotFoundError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 99)));
fs.moveNode(toPtr({ device_id: 0, inode: 1 }), toPtr({ device_id: 0, inode: 99 })),
);
}); });
/** /**
@@ -857,9 +843,7 @@ describe("FileSystem.moveNode", () => {
}, },
], ],
}); });
expectNotADirectoryError(() => expectNotADirectoryError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 2)));
fs.moveNode(toPtr({ device_id: 0, inode: 1 }), toPtr({ device_id: 0, inode: 2 })),
);
}); });
/** /**
@@ -879,9 +863,7 @@ describe("FileSystem.moveNode", () => {
}, },
], ],
}); });
expectAlreadyExistsError(() => expectAlreadyExistsError(() => fs.moveNode(NodePointer.of(0, 3), NodePointer.of(0, 2), "f"));
fs.moveNode(toPtr({ device_id: 0, inode: 3 }), toPtr({ device_id: 0, inode: 2 }), "f"),
);
}); });
/** /**
@@ -901,9 +883,7 @@ describe("FileSystem.moveNode", () => {
], ],
config: { maxNameLength: 2 }, config: { maxNameLength: 2 },
}); });
expectInvalidNodeNameError(() => expectInvalidNodeNameError(() => fs.moveNode(NodePointer.of(0, 3), NodePointer.of(0, 2), "abc"));
fs.moveNode(toPtr({ device_id: 0, inode: 3 }), toPtr({ device_id: 0, inode: 2 }), "abc"),
);
}); });
/** /**
@@ -921,9 +901,7 @@ describe("FileSystem.moveNode", () => {
}, },
], ],
}); });
expectDirectoryLoopError(() => expectDirectoryLoopError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 2)));
fs.moveNode(toPtr({ device_id: 0, inode: 1 }), toPtr({ device_id: 0, inode: 2 })),
);
}); });
/** /**
@@ -933,9 +911,7 @@ describe("FileSystem.moveNode", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })) }],
}); });
expectDirectoryLoopError(() => expectDirectoryLoopError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 1)));
fs.moveNode(toPtr({ device_id: 0, inode: 1 }), toPtr({ device_id: 0, inode: 1 })),
);
}); });
/** /**
@@ -948,9 +924,7 @@ describe("FileSystem.moveNode", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeDirectoryNode({ inode: 1 })) }],
}); });
expectAlreadyExistsError(() => expectAlreadyExistsError(() => fs.moveNode(NodePointer.of(0, 1), NodePointer.of(0, 0), "a"));
fs.moveNode(toPtr({ device_id: 0, inode: 1 }), toPtr({ device_id: 0, inode: 0 }), "a"),
);
}); });
/** /**
@@ -962,7 +936,7 @@ describe("FileSystem.moveNode", () => {
devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }, { id: 1 }], devices: [{ id: 0, setup: d => addChild(d, 0, "a", makeFileNode({ inode: 1 })) }, { id: 1 }],
}); });
const log = vi.spyOn(console, "error").mockImplementation(() => {}); const log = vi.spyOn(console, "error").mockImplementation(() => {});
fs.moveNode(toPtr({ device_id: 0, inode: 1 }), toPtr({ device_id: 1, inode: 0 })); fs.moveNode(NodePointer.of(0, 1), NodePointer.of(1, 0));
expect(log).toHaveBeenCalledWith(expect.stringMatching(/cross device/i)); expect(log).toHaveBeenCalledWith(expect.stringMatching(/cross device/i));
expect(disks.get(0)!.moveNodeEntry).not.toHaveBeenCalled(); expect(disks.get(0)!.moveNodeEntry).not.toHaveBeenCalled();
expect(disks.get(1)!.moveNodeEntry).not.toHaveBeenCalled(); expect(disks.get(1)!.moveNodeEntry).not.toHaveBeenCalled();
@@ -987,7 +961,7 @@ describe("FileSystem.writeContent", () => {
], ],
}); });
const blob = new Blob(["hello"]); const blob = new Blob(["hello"]);
fs.writeContent(toPtr({ device_id: 0, inode: 1 }), blob); fs.writeContent(NodePointer.of(0, 1), blob);
expect(disks.get(0)!.writeContent).toHaveBeenCalledWith("uuid-123", blob); expect(disks.get(0)!.writeContent).toHaveBeenCalledWith("uuid-123", blob);
}); });
@@ -996,7 +970,7 @@ describe("FileSystem.writeContent", () => {
*/ */
it("throws DeviceNotFoundError when the device is missing", async () => { it("throws DeviceNotFoundError when the device is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
await expectDeviceNotFoundError(() => fs.writeContent(toPtr({ device_id: 99, inode: 1 }), new Blob())); await expectDeviceNotFoundError(() => fs.writeContent(NodePointer.of(99, 1), new Blob()));
}); });
/** /**
@@ -1004,7 +978,7 @@ describe("FileSystem.writeContent", () => {
*/ */
it("throws NodeNotFoundError when the node is missing", async () => { it("throws NodeNotFoundError when the node is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expectNodeNotFoundError(() => fs.writeContent(toPtr({ device_id: 0, inode: 99 }), new Blob())); expectNodeNotFoundError(() => fs.writeContent(NodePointer.of(0, 99), new Blob()));
}); });
/** /**
@@ -1014,14 +988,14 @@ describe("FileSystem.writeContent", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "d", makeDirectoryNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "d", makeDirectoryNode({ inode: 1 })) }],
}); });
await expectNotAFileError(() => fs.writeContent(toPtr({ device_id: 0, inode: 1 }), new Blob())); await expectNotAFileError(() => fs.writeContent(NodePointer.of(0, 1), new Blob()));
}); });
it("rejects writing content to a symlink with NotAFileError", async () => { it("rejects writing content to a symlink with NotAFileError", async () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "l", makeSymlinkNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "l", makeSymlinkNode({ inode: 1 })) }],
}); });
await expectNotAFileError(() => fs.writeContent(toPtr({ device_id: 0, inode: 1 }), new Blob())); await expectNotAFileError(() => fs.writeContent(NodePointer.of(0, 1), new Blob()));
}); });
}); });
@@ -1042,9 +1016,9 @@ describe("FileSystem.streamContent", () => {
}, },
], ],
}); });
const stream = fs.streamContent(toPtr({ device_id: 0, inode: 1 })); const stream = fs.streamContent(NodePointer.of(0, 1));
expect(disks.get(0)!.streamContent).toHaveBeenCalledWith("uuid-123"); expect(disks.get(0)!.streamContent).toHaveBeenCalledWith("uuid-123");
expect(stream).toBeInstanceOf(Readable); expect(stream).toBeInstanceOf(ReadableStream);
}); });
/** /**
@@ -1052,7 +1026,7 @@ describe("FileSystem.streamContent", () => {
*/ */
it("throws DeviceNotFoundError when the device is missing", async () => { it("throws DeviceNotFoundError when the device is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
await expectDeviceNotFoundError(() => fs.streamContent(toPtr({ device_id: 99, inode: 1 }))); await expectDeviceNotFoundError(() => fs.streamContent(NodePointer.of(99, 1)));
}); });
/** /**
@@ -1060,7 +1034,7 @@ describe("FileSystem.streamContent", () => {
*/ */
it("throws NodeNotFoundError when the node is missing", async () => { it("throws NodeNotFoundError when the node is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expectNodeNotFoundError(() => fs.streamContent(toPtr({ device_id: 0, inode: 99 }))); expectNodeNotFoundError(() => fs.streamContent(NodePointer.of(0, 99)));
}); });
/** /**
@@ -1070,7 +1044,7 @@ describe("FileSystem.streamContent", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "d", makeDirectoryNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "d", makeDirectoryNode({ inode: 1 })) }],
}); });
await expectNotAFileError(() => fs.streamContent(toPtr({ device_id: 0, inode: 1 }))); await expectNotAFileError(() => fs.streamContent(NodePointer.of(0, 1)));
}); });
/** /**
@@ -1080,7 +1054,7 @@ describe("FileSystem.streamContent", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "l", makeSymlinkNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "l", makeSymlinkNode({ inode: 1 })) }],
}); });
expectNotAFileError(() => fs.streamContent(toPtr({ device_id: 0, inode: 1 }))); expectNotAFileError(() => fs.streamContent(NodePointer.of(0, 1)));
}); });
}); });
@@ -1096,7 +1070,7 @@ describe("FileSystem.modifyNode", () => {
const { fs, disks } = await makeFS({ const { fs, disks } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "f", makeFileNode({ inode: 1 })) }],
}); });
fs.modifyNode(toPtr({ device_id: 0, inode: 1 }), { mode: 0o600, owner: 7, group: 8 }); fs.modifyNode(NodePointer.of(0, 1), { mode: 0o600, owner: 7, group: 8 });
expect(disks.get(0)!.writeNodeEntry).toHaveBeenCalledWith(1, { mode: 0o600, owner: 7, group: 8 }); expect(disks.get(0)!.writeNodeEntry).toHaveBeenCalledWith(1, { mode: 0o600, owner: 7, group: 8 });
}); });
@@ -1105,7 +1079,7 @@ describe("FileSystem.modifyNode", () => {
*/ */
it("throws DeviceNotFoundError when the device is missing", async () => { it("throws DeviceNotFoundError when the device is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
await expectDeviceNotFoundError(() => fs.modifyNode(toPtr({ device_id: 99, inode: 1 }), { mode: 0 })); await expectDeviceNotFoundError(() => fs.modifyNode(NodePointer.of(99, 1), { mode: 0 }));
}); });
/** /**
@@ -1113,7 +1087,7 @@ describe("FileSystem.modifyNode", () => {
*/ */
it("throws NodeNotFoundError when the node is missing", async () => { it("throws NodeNotFoundError when the node is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
expectNodeNotFoundError(() => fs.modifyNode(toPtr({ device_id: 0, inode: 99 }), { mode: 0 })); expectNodeNotFoundError(() => fs.modifyNode(NodePointer.of(0, 99), { mode: 0 }));
}); });
/** /**
@@ -1125,7 +1099,7 @@ describe("FileSystem.modifyNode", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "d", makeDirectoryNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "d", makeDirectoryNode({ inode: 1 })) }],
}); });
await expectNotAFileError(() => fs.modifyNode(toPtr({ device_id: 0, inode: 1 }), { mode: 0 })); await expectNotAFileError(() => fs.modifyNode(NodePointer.of(0, 1), { mode: 0 }));
}); });
/** /**
@@ -1138,7 +1112,7 @@ describe("FileSystem.modifyNode", () => {
const { fs } = await makeFS({ const { fs } = await makeFS({
devices: [{ id: 0, setup: d => addChild(d, 0, "l", makeSymlinkNode({ inode: 1 })) }], devices: [{ id: 0, setup: d => addChild(d, 0, "l", makeSymlinkNode({ inode: 1 })) }],
}); });
await expectNotAFileError(() => fs.modifyNode(toPtr({ device_id: 0, inode: 1 }), { mode: 0o700 })); await expectNotAFileError(() => fs.modifyNode(NodePointer.of(0, 1), { mode: 0o700 }));
}); });
}); });
@@ -1175,9 +1149,9 @@ describe("FileSystem.canRead / canWrite / canExecute", () => {
const root = makeUser({ uid: 0 }); const root = makeUser({ uid: 0 });
for (const mode of [0, 0o777, 0o400, 0o040, 0o004]) { for (const mode of [0, 0o777, 0o400, 0o040, 0o004]) {
disks.get(0)!._nodes.set(1, makeFileNode({ inode: 1, mode })); disks.get(0)!._nodes.set(1, makeFileNode({ inode: 1, mode }));
expect(fs.canRead(toPtr({ device_id: 0, inode: 1 }), root)).toBe(true); expect(fs.canRead(NodePointer.of(0, 1), root)).toBe(true);
expect(fs.canWrite(toPtr({ device_id: 0, inode: 1 }), root)).toBe(true); expect(fs.canWrite(NodePointer.of(0, 1), root)).toBe(true);
expect(fs.canExecute(toPtr({ device_id: 0, inode: 1 }), root)).toBe(true); expect(fs.canExecute(NodePointer.of(0, 1), root)).toBe(true);
} }
}); });
@@ -1187,37 +1161,9 @@ describe("FileSystem.canRead / canWrite / canExecute", () => {
it("throws NodeNotFoundError when the node is missing", async () => { it("throws NodeNotFoundError when the node is missing", async () => {
const { fs } = await makeFS(); const { fs } = await makeFS();
const user = makeUser(); const user = makeUser();
await expectNodeNotFoundError(() => fs.canRead(toPtr({ device_id: 0, inode: 99 }), user)); await expectNodeNotFoundError(() => fs.canRead(NodePointer.of(0, 99), user));
await expectNodeNotFoundError(() => fs.canWrite(toPtr({ device_id: 0, inode: 99 }), user)); await expectNodeNotFoundError(() => fs.canWrite(NodePointer.of(0, 99), user));
await expectNodeNotFoundError(() => fs.canExecute(toPtr({ device_id: 0, inode: 99 }), user)); await expectNodeNotFoundError(() => fs.canExecute(NodePointer.of(0, 99), user));
});
/**
* Property: for every combination of (mode, owner, group, uid, gid) on a
* fresh file node, the three `can*` functions agree with a reference
* implementation of Unix permission bits. This is a regression guard against
* accidental bit-constant typos in the implementation.
*/
it("agrees with a reference Unix permission implementation for every mode/uid/gid combination", async () => {
const { fs, disks } = await makeFS();
const ptr = toPtr({ device_id: 0, inode: 1 });
fc.assert(
fc.property(
fc.integer({ min: 0, max: 0o777 }),
fc.integer({ min: 0, max: 1000 }),
fc.integer({ min: 0, max: 1000 }),
fc.integer({ min: 0, max: 1000 }),
fc.integer({ min: 0, max: 1000 }),
(mode, owner, group, uid, gid) => {
disks.get(0)!._nodes.set(1, makeFileNode({ inode: 1, mode, owner, group }));
const user = makeUser({ uid, gid });
expect(fs.canRead(ptr, user)).toBe(referenceCan("read", mode, { owner, group }, user));
expect(fs.canWrite(ptr, user)).toBe(referenceCan("write", mode, { owner, group }, user));
expect(fs.canExecute(ptr, user)).toBe(referenceCan("execute", mode, { owner, group }, user));
},
),
);
}); });
/** /**
@@ -1235,7 +1181,7 @@ describe("FileSystem.canRead / canWrite / canExecute", () => {
const user = makeUser({ uid: 1000, gid: 1000, group: [42, 99] }); const user = makeUser({ uid: 1000, gid: 1000, group: [42, 99] });
// User is not owner, primary gid is 1000, but supplementary group contains 42. // User is not owner, primary gid is 1000, but supplementary group contains 42.
// Correct Unix: `canRead` is true. // Correct Unix: `canRead` is true.
expect(fs.canRead(toPtr({ device_id: 0, inode: 1 }), user)).toBe(true); expect(fs.canRead(NodePointer.of(0, 1), user)).toBe(true);
}); });
}); });
@@ -1244,21 +1190,6 @@ describe("FileSystem.canRead / canWrite / canExecute", () => {
// ============================================================================ // ============================================================================
describe("fromPtr / toPtr", () => { describe("fromPtr / toPtr", () => {
/**
* Property: every valid pointer round-trips through toPtr → fromPtr.
*/
it("round-trips arbitrary device/inode pairs through toPtr/fromPtr", () => {
fc.assert(
fc.property(
fc.integer({ min: 0, max: 1_000_000 }),
fc.integer({ min: 0, max: 1_000_000 }),
(device_id, inode) => {
expect(fromPtr(toPtr({ device_id, inode }))).toEqual({ device_id, inode });
},
),
);
});
/** /**
* Invalid formats must throw. (Example-based because the failure mode is * Invalid formats must throw. (Example-based because the failure mode is
* a specific regex, not a property over generated strings.) * a specific regex, not a property over generated strings.)
@@ -1266,7 +1197,7 @@ describe("fromPtr / toPtr", () => {
it.each(["", ":", "abc", "1:", ":1", "1.5:2", "-1:2", "1 :2", "1: 2", "1:2abc", "1:2 ", " 1:2"])( it.each(["", ":", "abc", "1:", ":1", "1.5:2", "-1:2", "1 :2", "1: 2", "1:2abc", "1:2 ", " 1:2"])(
"throws on invalid pointer %j", "throws on invalid pointer %j",
bad => { bad => {
expect(() => fromPtr(bad)).toThrow(/Invalid node pointer format/); expect(() => NodePointer.parse(bad)).toThrow(/Invalid node pointer format/);
}, },
); );
}); });
@@ -1283,7 +1214,7 @@ describe("FileSystem integration", () => {
it("drives the underlying device through a typical file lifecycle", async () => { it("drives the underlying device through a typical file lifecycle", async () => {
const { fs, disks } = await makeFS(); const { fs, disks } = await makeFS();
const disk = disks.get(0)!; const disk = disks.get(0)!;
const root = toPtr({ device_id: 0, inode: 0 }); const root = NodePointer.of(0, 0);
fs.createNode(root, "hello.txt", { fs.createNode(root, "hello.txt", {
type: NodeType.File, type: NodeType.File,
@@ -1302,16 +1233,16 @@ describe("FileSystem integration", () => {
// Simulate the device having created the node. // Simulate the device having created the node.
addChild(disk, 0, "hello.txt", makeFileNode({ inode: 1, content: "uuid-1" })); addChild(disk, 0, "hello.txt", makeFileNode({ inode: 1, content: "uuid-1" }));
fs.modifyNode(toPtr({ device_id: 0, inode: 1 }), { mode: 0o600 }); fs.modifyNode(NodePointer.of(0, 1), { mode: 0o600 });
expect(disk.writeNodeEntry).toHaveBeenLastCalledWith(1, { mode: 0o600 }); expect(disk.writeNodeEntry).toHaveBeenLastCalledWith(1, { mode: 0o600 });
fs.writeContent(toPtr({ device_id: 0, inode: 1 }), new Blob(["updated"])); fs.writeContent(NodePointer.of(0, 1), new Blob(["updated"]));
expect(disk.writeContent).toHaveBeenLastCalledWith("uuid-1", expect.any(Blob)); expect(disk.writeContent).toHaveBeenLastCalledWith("uuid-1", expect.any(Blob));
fs.moveNode(toPtr({ device_id: 0, inode: 1 }), root, "renamed.txt"); fs.moveNode(NodePointer.of(0, 1), root, "renamed.txt");
expect(disk.moveNodeEntry).toHaveBeenLastCalledWith(0, 0, "hello.txt", "renamed.txt"); expect(disk.moveNodeEntry).toHaveBeenLastCalledWith(0, 0, "hello.txt", "renamed.txt");
fs.deleteNode(toPtr({ device_id: 0, inode: 1 })); fs.deleteNode(NodePointer.of(0, 1));
expect(disk.unlinkNodeEntry).toHaveBeenLastCalledWith(0, "hello.txt"); expect(disk.unlinkNodeEntry).toHaveBeenLastCalledWith(0, "hello.txt");
}); });
}); });
+39 -91
View File
@@ -1,9 +1,8 @@
// @tests/core/util/path_resolver.test.ts (adjust) // @tests/core/util/path_resolver.test.ts (adjust)
import { toPtr, type NodePointer } from "@core/filesystem/node"; import { NodePointer } from "@core/filesystem/node";
import { resolvePath } from "@core/util/path_resolver"; import { resolvePath } from "@core/util/path_resolver";
import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers"; import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers";
import { makeFS, makeShellState, makeTree, makeUser } from "@tests/helpers/filesystems_fixture"; import { makeFS, makeShellState, makeTree, makeUser } from "@tests/helpers/filesystems_fixture";
import fc from "fast-check";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
// ============================================================================ // ============================================================================
@@ -37,34 +36,9 @@ describe("resolvePath — path normalization", () => {
const t = makeTree(); const t = makeTree();
const work = t.addDir(0, "work"); const work = t.addDir(0, "work");
const fs = await makeFS([t.build()]); const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) }); const state = makeShellState(fs, { cwd: NodePointer.of(0, work) });
expect(resolvePath(state, "")).toEqual({ device_id: 0, inode: work }); expect(resolvePath(state, "")).toEqual({ device_id: 0, inode: work });
}); });
/**
* Property: leading, trailing, and interior redundant slashes never change
* the resolved pointer.
*/
it("resolves identically regardless of redundant slashes", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
t.addFile(a, "b");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs);
const expected = resolvePath(state, "/a/b");
fc.assert(
fc.property(
fc.integer({ min: 0, max: 5 }),
fc.integer({ min: 0, max: 5 }),
fc.integer({ min: 1, max: 4 }),
(lead, trail, mid) => {
const path = "/".repeat(lead) + "a" + "/".repeat(mid) + "b" + "/".repeat(trail);
expect(resolvePath(state, path)).toEqual(expected);
},
),
);
});
}); });
// ============================================================================ // ============================================================================
@@ -174,7 +148,7 @@ describe("resolvePath — relative paths", () => {
const work = t.addDir(0, "work"); const work = t.addDir(0, "work");
const file = t.addFile(work, "file"); const file = t.addFile(work, "file");
const fs = await makeFS([t.build()]); const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) }); const state = makeShellState(fs, { cwd: NodePointer.of(0, work) });
expect(resolvePath(state, "file")).toEqual({ device_id: 0, inode: file }); expect(resolvePath(state, "file")).toEqual({ device_id: 0, inode: file });
}); });
@@ -187,7 +161,7 @@ describe("resolvePath — relative paths", () => {
const sub = t.addDir(work, "sub"); const sub = t.addDir(work, "sub");
const leaf = t.addFile(sub, "leaf"); const leaf = t.addFile(sub, "leaf");
const fs = await makeFS([t.build()]); const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) }); const state = makeShellState(fs, { cwd: NodePointer.of(0, work) });
expect(resolvePath(state, "sub/leaf")).toEqual({ device_id: 0, inode: leaf }); expect(resolvePath(state, "sub/leaf")).toEqual({ device_id: 0, inode: leaf });
}); });
@@ -212,7 +186,7 @@ describe("resolvePath — '~' expansion", () => {
const t = makeTree(); const t = makeTree();
const home = t.addDir(0, "home"); const home = t.addDir(0, "home");
const fs = await makeFS([t.build()]); const fs = await makeFS([t.build()]);
const user = makeUser(toPtr({ device_id: 0, inode: home })); const user = makeUser(NodePointer.of(0, home));
const state = makeShellState(fs, { user }); const state = makeShellState(fs, { user });
expect(resolvePath(state, "~")).toEqual({ device_id: 0, inode: home }); expect(resolvePath(state, "~")).toEqual({ device_id: 0, inode: home });
}); });
@@ -225,7 +199,7 @@ describe("resolvePath — '~' expansion", () => {
const home = t.addDir(0, "home"); const home = t.addDir(0, "home");
const file = t.addFile(home, "file"); const file = t.addFile(home, "file");
const fs = await makeFS([t.build()]); const fs = await makeFS([t.build()]);
const user = makeUser(toPtr({ device_id: 0, inode: home })); const user = makeUser(NodePointer.of(0, home));
const state = makeShellState(fs, { user }); const state = makeShellState(fs, { user });
expect(resolvePath(state, "~/file")).toEqual({ device_id: 0, inode: file }); expect(resolvePath(state, "~/file")).toEqual({ device_id: 0, inode: file });
}); });
@@ -241,7 +215,7 @@ describe("resolvePath — '~' expansion", () => {
const home = t1.addDir(0, "home"); const home = t1.addDir(0, "home");
const file = t1.addFile(home, "file"); const file = t1.addFile(home, "file");
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
const user = makeUser(toPtr({ device_id: 1, inode: home })); const user = makeUser(NodePointer.of(1, home));
const state = makeShellState(fs, { user }); const state = makeShellState(fs, { user });
expect(resolvePath(state, "~/file")).toEqual({ device_id: 1, inode: file }); expect(resolvePath(state, "~/file")).toEqual({ device_id: 1, inode: file });
}); });
@@ -280,7 +254,7 @@ describe("resolvePath — mount points", () => {
const mnt = t0.addDir(0, "mnt"); const mnt = t0.addDir(0, "mnt");
const t1 = makeTree(); const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/mnt")).toEqual({ device_id: 1, inode: 0 }); expect(resolvePath(makeShellState(fs), "/mnt")).toEqual({ device_id: 1, inode: 0 });
}); });
@@ -295,7 +269,7 @@ describe("resolvePath — mount points", () => {
const t1 = makeTree(); const t1 = makeTree();
const file = t1.addFile(0, "file"); const file = t1.addFile(0, "file");
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/mnt/file")).toEqual({ device_id: 1, inode: file }); expect(resolvePath(makeShellState(fs), "/mnt/file")).toEqual({ device_id: 1, inode: file });
}); });
@@ -310,7 +284,7 @@ describe("resolvePath — mount points", () => {
const sub = t1.addDir(0, "sub"); const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf"); const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf }); expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
}); });
@@ -325,8 +299,8 @@ describe("resolvePath — mount points", () => {
const t1 = makeTree(); const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
fs.mount( fs.mount(
toPtr({ device_id: 0, inode: mnt }), // "0:2" — the mountpoint NodePointer.of(0, mnt), // "0:2" — the mountpoint
toPtr({ device_id: 1, inode: 0 }), NodePointer.of(1, 0),
); );
const state = makeShellState(fs); const state = makeShellState(fs);
@@ -349,7 +323,7 @@ describe("resolvePath — mount points", () => {
const t1 = makeTree(); const t1 = makeTree();
const sub = t1.addDir(0, "sub"); const sub = t1.addDir(0, "sub");
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: b }), toPtr({ device_id: 1, inode: sub })); fs.mount(NodePointer.of(0, b), NodePointer.of(1, sub));
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 1, inode: sub }); expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 1, inode: sub });
}); });
@@ -365,7 +339,7 @@ describe("resolvePath — mount points", () => {
const sub = t1.addDir(0, "sub"); const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf"); const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: b }), toPtr({ device_id: 1, inode: sub })); fs.mount(NodePointer.of(0, b), NodePointer.of(1, sub));
expect(resolvePath(makeShellState(fs), "/a/b/leaf")).toEqual({ device_id: 1, inode: leaf }); expect(resolvePath(makeShellState(fs), "/a/b/leaf")).toEqual({ device_id: 1, inode: leaf });
}); });
@@ -381,8 +355,8 @@ describe("resolvePath — mount points", () => {
const sub = t1.addDir(0, "sub"); const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf"); const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
fs.mount(toPtr({ device_id: 0, inode: other }), toPtr({ device_id: 1, inode: sub })); fs.mount(NodePointer.of(0, other), NodePointer.of(1, sub));
const state = makeShellState(fs); const state = makeShellState(fs);
expect(resolvePath(state, "/mnt/file")).toEqual({ device_id: 1, inode: file }); expect(resolvePath(state, "/mnt/file")).toEqual({ device_id: 1, inode: file });
@@ -406,7 +380,7 @@ describe("resolvePath — symlinks across mount points", () => {
const mnt = t0.addDir(0, "mnt"); const mnt = t0.addDir(0, "mnt");
const t1 = makeTree(); const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 1, inode: 0 }); expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 1, inode: 0 });
}); });
@@ -423,7 +397,7 @@ describe("resolvePath — symlinks across mount points", () => {
const t1 = makeTree(); const t1 = makeTree();
const file = t1.addFile(0, "file"); const file = t1.addFile(0, "file");
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
expect(resolvePath(makeShellState(fs), "/link/file")).toEqual({ device_id: 1, inode: file }); expect(resolvePath(makeShellState(fs), "/link/file")).toEqual({ device_id: 1, inode: file });
}); });
@@ -480,32 +454,6 @@ describe("resolvePath — known bugs", () => {
expect(thrown).not.toHaveProperty("type"); expect(thrown).not.toHaveProperty("type");
// ^ BUG: no `type` discriminant. Correct: typed (e.g. SymlinkLoop). // ^ BUG: no `type` discriminant. Correct: typed (e.g. SymlinkLoop).
}); });
/**
* BUG: a malformed cwd pointer is not validated; `fromPtr(session.cwd)`
* throws a raw `Error("Invalid node pointer format")`, not a typed one.
* Same "untyped" class as the symlink-depth bug.
*
* Fix: wrap `fromPtr` calls in a typed try/catch, or add a validating
* parse (e.g. `tryFromPtr`) that returns `undefined` on failure.
*/
it("BUG: malformed cwd throws a raw Error from fromPtr", async () => {
const fs = await makeFS([makeTree().build()]);
const state = makeShellState(fs, {
cwd: "garbage" as NodePointer,
});
expect(() => resolvePath(state, "foo")).toThrow(/Invalid node pointer format/);
});
/**
* BUG: same as above, for `session.user.home` when expanding `~`.
*/
it("BUG: malformed home pointer throws a raw Error from fromPtr", async () => {
const fs = await makeFS([makeTree().build()]);
const user = makeUser("garbage" as NodePointer);
const state = makeShellState(fs, { user });
expect(() => resolvePath(state, "~")).toThrow(/Invalid node pointer format/);
});
}); });
describe("resolvePath — '..' across mount boundaries", () => { describe("resolvePath — '..' across mount boundaries", () => {
@@ -521,9 +469,9 @@ describe("resolvePath — '..' across mount boundaries", () => {
const t0 = makeTree(); const t0 = makeTree();
const mnt = t0.addDir(0, "mnt"); const mnt = t0.addDir(0, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]); const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) }); const atMountedRoot = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 }); expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
}); });
@@ -538,9 +486,9 @@ describe("resolvePath — '..' across mount boundaries", () => {
const user = t0.addDir(home, "user"); const user = t0.addDir(home, "user");
const mnt = t0.addDir(user, "mnt"); const mnt = t0.addDir(user, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]); const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) }); const atMountedRoot = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: user }); expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: user });
}); });
@@ -557,9 +505,9 @@ describe("resolvePath — '..' across mount boundaries", () => {
const t1 = makeTree(); const t1 = makeTree();
const sub = t1.addDir(0, "sub"); const sub = t1.addDir(0, "sub");
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
const atSub = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: sub }) }); const atSub = makeShellState(fs, { cwd: NodePointer.of(1, sub) });
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 }); expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
}); });
@@ -576,21 +524,21 @@ describe("resolvePath — '..' across mount boundaries", () => {
const sub = t1.addDir(0, "sub"); const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf"); const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]); const fs = await makeFS([t0.build(), t1.build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
// Sanity: full descent lands at `1:leaf` // Sanity: full descent lands at `1:leaf`
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf }); expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
// One `..` up: /mnt/sub // One `..` up: /mnt/sub
const atLeaf = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: leaf }) }); const atLeaf = makeShellState(fs, { cwd: NodePointer.of(1, leaf) });
expect(resolvePath(atLeaf, "..")).toEqual({ device_id: 1, inode: sub }); expect(resolvePath(atLeaf, "..")).toEqual({ device_id: 1, inode: sub });
// Another `..`: /mnt's content = dev1 root // Another `..`: /mnt's content = dev1 root
const atSub = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: sub }) }); const atSub = makeShellState(fs, { cwd: NodePointer.of(1, sub) });
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 }); expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
// Final `..`: exit the mount → / // Final `..`: exit the mount → /
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) }); const atMountedRoot = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 }); expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
}); });
@@ -611,15 +559,15 @@ describe("resolvePath — '..' across mount boundaries", () => {
const nested = t0.addDir(b, "nested"); const nested = t0.addDir(b, "nested");
const fs = await makeFS([t0.build(), makeTree().build(), makeTree().build()]); const fs = await makeFS([t0.build(), makeTree().build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: a }), toPtr({ device_id: 1, inode: 0 })); // /a → dev1 await fs.mount(NodePointer.of(0, a), NodePointer.of(1, 0)); // /a → dev1
await fs.mount(toPtr({ device_id: 0, inode: nested }), toPtr({ device_id: 2, inode: 0 })); // /b/nested → dev2 await fs.mount(NodePointer.of(0, nested), NodePointer.of(2, 0)); // /b/nested → dev2
// `..` from dev1's root → parent of `/a` = `/` // `..` from dev1's root → parent of `/a` = `/`
const atDev1Root = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) }); const atDev1Root = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 }); expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
// `..` from dev2's root → parent of `/b/nested` = `/b` // `..` from dev2's root → parent of `/b/nested` = `/b`
const atDev2Root = makeShellState(fs, { cwd: toPtr({ device_id: 2, inode: 0 }) }); const atDev2Root = makeShellState(fs, { cwd: NodePointer.of(2, 0) });
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 0, inode: b }); expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 0, inode: b });
}); });
@@ -652,18 +600,18 @@ describe("resolvePath — '..' across mount boundaries", () => {
const b = t1.addDir(0, "b"); const b = t1.addDir(0, "b");
const fs = await makeFS([t0.build(), t1.build(), makeTree().build()]); const fs = await makeFS([t0.build(), t1.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); // /mnt → dev1 await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0)); // /mnt → dev1
await fs.mount(toPtr({ device_id: 1, inode: b }), toPtr({ device_id: 2, inode: 0 })); // /mnt/b → dev2 await fs.mount(NodePointer.of(1, b), NodePointer.of(2, 0)); // /mnt/b → dev2
// Sanity: /mnt/b resolves to dev2 root // Sanity: /mnt/b resolves to dev2 root
expect(resolvePath(makeShellState(fs), "/mnt/b")).toEqual({ device_id: 2, inode: 0 }); expect(resolvePath(makeShellState(fs), "/mnt/b")).toEqual({ device_id: 2, inode: 0 });
// `..` from dev2 root → exit B's mount → parent of `1:b` = `1:0` (dev1 root) // `..` from dev2 root → exit B's mount → parent of `1:b` = `1:0` (dev1 root)
const atDev2Root = makeShellState(fs, { cwd: toPtr({ device_id: 2, inode: 0 }) }); const atDev2Root = makeShellState(fs, { cwd: NodePointer.of(2, 0) });
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 1, inode: 0 }); expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 1, inode: 0 });
// `..` from dev1 root → exit A's mount → parent of `0:mnt` = `/` // `..` from dev1 root → exit A's mount → parent of `0:mnt` = `/`
const atDev1Root = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) }); const atDev1Root = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 }); expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
}); });
@@ -677,18 +625,18 @@ describe("resolvePath — '..' across mount boundaries", () => {
const t0 = makeTree(); const t0 = makeTree();
const mnt = t0.addDir(0, "mnt"); const mnt = t0.addDir(0, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]); const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 })); await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
// Start at /, enter /mnt // Start at /, enter /mnt
const fromRoot = makeShellState(fs); const fromRoot = makeShellState(fs);
expect(resolvePath(fromRoot, "/mnt")).toEqual({ device_id: 1, inode: 0 }); expect(resolvePath(fromRoot, "/mnt")).toEqual({ device_id: 1, inode: 0 });
// `..` from mounted root → / // `..` from mounted root → /
const atMnt = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) }); const atMnt = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
expect(resolvePath(atMnt, "..")).toEqual({ device_id: 0, inode: 0 }); expect(resolvePath(atMnt, "..")).toEqual({ device_id: 0, inode: 0 });
// `mnt` again from / → back to mounted root // `mnt` again from / → back to mounted root
const atRoot = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: 0 }) }); const atRoot = makeShellState(fs, { cwd: NodePointer.of(0, 0) });
expect(resolvePath(atRoot, "mnt")).toEqual({ device_id: 1, inode: 0 }); expect(resolvePath(atRoot, "mnt")).toEqual({ device_id: 1, inode: 0 });
}); });
}); });
-57
View File
@@ -1,57 +0,0 @@
import { createInitialSessionState, getCurrentSession, login, logout } from "@core/session_manager";
import { Fixture } from "@tests/helpers/state_fixture";
import { describe, expect, test } from "vitest";
const state = Fixture.State;
const passMap = new Map();
passMap.set(0, "123");
passMap.set(1000, "321");
test("createInitialSessionState - successfully creates a new session state", () => {
const state = createInitialSessionState(Fixture.user);
expect(state.cwd).toEqual(Fixture.user.home);
expect(state.pwd).toEqual(Fixture.user.home);
expect(state.exitCode).toEqual(0);
expect(state.user).toBe(Fixture.user);
expect(Object.isFrozen(state)).toBe(true);
});
describe("login", () => {
test("it successfully starts a new session under the user test", () => {
const newState = login(state, "user", "321", passMap);
const pop = getCurrentSession(newState);
expect(pop.user).toEqual(Fixture.user2);
});
test("fails to start a new session. Cause: no password mapped to the uid", () => {
//TODO: Fix to expect the correct object;
expect(() => login(state, "no pass", "321", passMap)).toThrow();
});
test("fails to start a new session. Cause: Incorrect password", () => {
//TODO: Fix to expect the correct object;
expect(() => login(state, "no pass", "333", passMap)).toThrow();
});
test("fails to start a new session. Cause: Specified user does not exist", () => {
//TODO: Fix to expect the correct object;
expect(() => login(state, "no user", "321", passMap)).toThrow();
});
});
describe("logout", () => {
test("returns the state with the current user poped from the stack", () => {
const newState = login(state, "user", "321", passMap);
const newPop = getCurrentSession(newState);
expect(newPop.user).toEqual(Fixture.user2);
const newNewState = logout(state);
const pop = getCurrentSession(newNewState);
expect(pop.user).toEqual(Fixture.user);
});
});
-64
View File
@@ -1,64 +0,0 @@
import { getCurrentSession } from "@core/session_manager";
import { withCwd, withEnv, withExitCode, withHistory } from "@core/shell_state";
import { Fixture } from "@tests/helpers/state_fixture";
import { expect, test } from "vitest";
const state = Fixture.State;
test("createInitialShellState - initializes successfully", () => {
expect(state.sessionStack.at(0)).toBeDefined();
expect(state.users.get(Fixture.user.uid)).toEqual(Fixture.user);
expect(Object.isFrozen(state)).toBe(true);
});
test("fails - tries to mutate a frozen immutable object", () => {
expect(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(state as any).sessionStack = [];
}).toThrow();
});
test("getCurrentSession - successfully returns the current (top most) session from the stack", () => {
const session = getCurrentSession(state);
expect(session.cwd).toBe(0);
expect(session.pwd).toBe(0);
expect(session.exitCode).toBe(0);
expect(session.history).toEqual([]);
expect(session.envVars.size).toBe(0);
expect(session.user).toBe(Fixture.user);
});
test("withCwd", () => {
const nstate = withCwd(state, 1);
const result = getCurrentSession(nstate);
expect(result.cwd).toBe(1);
expect(result.pwd).toBe(0);
expect(nstate.filesystem).toBe(state.filesystem);
expect(getCurrentSession(state).cwd).toBe(0);
});
test("withEnv", () => {
const nstate = withEnv(state, "foo", "Hello World!");
const result = getCurrentSession(nstate);
expect(result.envVars.get("foo")).toBe("Hello World!");
expect(nstate.filesystem).toBe(state.filesystem);
expect(getCurrentSession(state).envVars.get("foo")).toBeUndefined();
});
test("withHistory", () => {
const nstate = withHistory(state, 'echo "Hi!"');
const result = getCurrentSession(nstate);
expect(result.history).toContain('echo "Hi!"');
expect(nstate.filesystem).toBe(state.filesystem);
expect(getCurrentSession(state).history).not.toContain('echo "Hi!"');
});
test("withExitCode", () => {
const nstate = withExitCode(state, 10);
const result = getCurrentSession(nstate);
expect(result.exitCode).toEqual(10);
expect(nstate.filesystem).toBe(state.filesystem);
expect(getCurrentSession(state).exitCode).toEqual(0);
});
-86
View File
@@ -1,86 +0,0 @@
import { parseCommand } from "@core/util/parser";
import { describe, expect, test } from "vitest";
describe("parseCommand", () => {
test("returns an empty ParsedCommand object", () => {
expect(parseCommand("")).toEqual({ command: "", flags: [], args: [] });
});
test("returns an empty ParsedCommand object", () => {
expect(parseCommand("")).toEqual({ command: "", flags: [], args: [] });
});
test("returns an empty ParsedCommand object", () => {
expect(parseCommand("")).toEqual({ command: "", flags: [], args: [] });
});
test("returns a parsed ls command without any args", () => {
expect(parseCommand("ls")).toEqual({ command: "ls", flags: [], args: [] });
});
test("returns a parsed ls command with arg /tmp", () => {
expect(parseCommand("ls /tmp")).toEqual({ command: "ls", flags: [], args: ["/tmp"] });
});
test("returns a parsed ls command with flags l and no args", () => {
expect(parseCommand("ls -l")).toEqual({ command: "ls", flags: ["l"], args: [] });
});
test("returns a parsed command with flags l,a and no args", () => {
expect(parseCommand("ls -la")).toEqual({ command: "ls", flags: ["l", "a"], args: [] });
});
test("returns a parsed command with flags l,a and no args", () => {
expect(parseCommand("ls -l -a")).toEqual({ command: "ls", flags: ["l", "a"], args: [] });
});
test("returns a parsed command with flags l,a and a /tmp arg", () => {
expect(parseCommand("ls -la /tmp")).toEqual({ command: "ls", flags: ["l", "a"], args: ["/tmp"] });
});
test("returns a parsed grep command with a valued color flag", () => {
expect(parseCommand("grep --color=auto")).toEqual({ command: "grep", flags: ["color=auto"], args: [] });
});
test("returns a parsed grep command with a valued color and r flags", () => {
expect(parseCommand("grep --color=auto -r")).toEqual({
command: "grep",
flags: ["color=auto", "r"],
args: [],
});
});
test("returns a parsed grep command with a valued color in short form and r flags", () => {
expect(parseCommand("grep -color=auto -r")).toEqual({
command: "grep",
flags: ["color=auto", "r"],
args: [],
});
});
test("returns a parsed grep command with a valued w in short form and r flags", () => {
expect(parseCommand("grep -w=auto -r")).toEqual({
command: "grep",
flags: ["w=auto", "r"],
args: [],
});
});
test("returns a parsed echo command with a --version arg", () => {
expect(parseCommand("echo -- --version")).toEqual({ command: "echo", flags: [], args: ["--version"] });
});
test("returns a parsed echo command with a -f arg", () => {
expect(parseCommand("echo -- -f")).toEqual({ command: "echo", flags: [], args: ["-f"] });
});
test("returns a parsed echo command without any args", () => {
expect(parseCommand("echo --")).toEqual({ command: "echo", flags: [], args: [] });
});
test("returns a parsed ls command with flags l,a and a --tmp arg", () => {
expect(parseCommand("ls -la -- --tmp")).toEqual({ command: "ls", flags: ["l", "a"], args: ["--tmp"] });
});
test("returns a parsed rm command with flags r,f,no-preserve-root and a / arg", () => {
expect(parseCommand("rm -rf --no-preserve-root /")).toEqual({
command: "rm",
flags: ["r", "f", "no-preserve-root"],
args: ["/"],
});
});
test("throws an UnclosedQuote error", () => {
expect(() => parseCommand('echo "hello')).toThrow(expect.objectContaining({ type: "UnclosedQuote" }));
});
});
File diff suppressed because one or more lines are too long
+3 -4
View File
@@ -4,12 +4,11 @@
import { FileSystem } from "@core/filesystem/filesystem"; import { FileSystem } from "@core/filesystem/filesystem";
import { import {
NodePointer,
NodeType, NodeType,
toPtr,
type DirectoryNode, type DirectoryNode,
type FileNode, type FileNode,
type Node, type Node,
type NodePointer,
type SymlinkNode, type SymlinkNode,
} from "@core/filesystem/node"; } from "@core/filesystem/node";
import { DefaultVDiskConfig } from "@core/filesystem/vdisk"; import { DefaultVDiskConfig } from "@core/filesystem/vdisk";
@@ -63,7 +62,7 @@ export function makeSymlink(inode: number, target: string): SymlinkNode {
}; };
} }
export function makeUser(home: NodePointer = toPtr({ device_id: 0, inode: 0 })): UserInfo { export function makeUser(home: NodePointer = NodePointer.of(0, 0)): UserInfo {
return { return {
username: "test", username: "test",
uid: 1000, uid: 1000,
@@ -162,7 +161,7 @@ export function makeShellState(
fs: FileSystem, fs: FileSystem,
opts: { cwd?: NodePointer; home?: NodePointer; user?: UserInfo } = {}, opts: { cwd?: NodePointer; home?: NodePointer; user?: UserInfo } = {},
): ShellState { ): ShellState {
const cwd = opts.cwd ?? toPtr({ device_id: 0, inode: 0 }); const cwd = opts.cwd ?? NodePointer.of(0, 0);
const user = opts.user ?? makeUser(opts.home); const user = opts.user ?? makeUser(opts.home);
const session = { const session = {
user, user,
-8
View File
@@ -1,8 +0,0 @@
import { test } from "vitest";
//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"}`;
test("deserialize json into the correct tree structure", () => {
//const base = deserializeFileSystem(rawJson);
//expect(true).toEqual(false);
});
-29
View File
@@ -1,29 +0,0 @@
import { getCurrentSession } from "@core/session_manager";
import { Shell } from "@shell/shell";
import { Fixture } from "@tests/helpers/state_fixture";
import { describe, expect, test } from "vitest";
const state = Fixture.State;
describe("Shell tests", () => {
test("Successfully executes the cd command", async () => {
await Shell.init(state);
let result;
Shell.Instance?.on("result", payload => {
result = payload.result;
});
await Shell.Instance?.execute("cd /folder1");
const statee = Shell.Instance?.State;
expect(result!.type).toEqual("success");
expect(getCurrentSession(statee!).history.length).toBe(1);
expect(getCurrentSession(statee!).history[0]).toEqual("cd /folder1");
expect(getCurrentSession(statee!).cwd).toBe(1);
expect(getCurrentSession(statee!).exitCode).toBe(0);
});
test("Returns a proper command error from cd", () => {});
test("Returns an empty success result as per parsing a whitespace character or inputing nothing", () => {});
});