- Fixed resolvePath

- Added symlink resolution
- Added mount resolution
- Fixed filesystem not awaiting for disks to be mounted
(now `FileSystem.init()` needs to be called with `await`)
- Removed old test fixture files
- Added a feature-full `resolvePath`test suite

*all tests passing green*
This commit is contained in:
2026-11-10 08:04:57 +01:00
parent dd804f6f14
commit 4fa284de13
14 changed files with 4608 additions and 657 deletions
+1
View File
@@ -29,6 +29,7 @@
"vitest": "^4.1.10" "vitest": "^4.1.10"
}, },
"dependencies": { "dependencies": {
"fast-check": "^4.10.2",
"zod": "^4.4.3" "zod": "^4.4.3"
}, },
"allowScripts": { "allowScripts": {
+2028
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
allowBuilds:
esbuild: true
+14
View File
@@ -47,6 +47,13 @@ export interface DeviceNotFoundError {
timestamp: number; timestamp: number;
} }
export interface MountPointNotFoundError {
type: "MountPointNotFound";
message: string;
pointer: NodePointer;
timestamp: number;
}
export interface IllegalMutationError { export interface IllegalMutationError {
type: "IllegalMutation"; type: "IllegalMutation";
message: string; message: string;
@@ -68,3 +75,10 @@ export interface InvalidNodeNameError {
pointer: NodePointer; pointer: NodePointer;
attemptedName: string; attemptedName: string;
} }
export interface FileSystemCorruptionError {
type: "FileSystemCorruption";
message: string;
timestamp: number;
override?: {};
}
+157 -41
View File
@@ -7,6 +7,7 @@ import type {
AlreadyExistsError, AlreadyExistsError,
DeviceNotFoundError, DeviceNotFoundError,
DirectoryLoopError, DirectoryLoopError,
FileSystemCorruptionError,
FileSystemInitializationError, FileSystemInitializationError,
IllegalMutationError, IllegalMutationError,
InvalidNodeNameError, InvalidNodeNameError,
@@ -32,25 +33,20 @@ export interface FileSystemConfig {
} }
export class FileSystem { export class FileSystem {
private readonly _maxNameLength: number; private _Mounts: Map<NodePointer, NodePointer> = new Map();
private readonly _maxPathLength: number; private _RMounts: Map<NodePointer, NodePointer> = new Map();
private readonly _maxSymlinkDepth: number;
private _Mounts: Map<NodePointer, { tinode: number; tdevice_id: number }> = new Map();
private _VDiskManager: VDiskManager; private _VDiskManager: VDiskManager;
private constructor( readonly maxNameLength: number;
devices: Array<{ dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }>, readonly maxPathLength: number;
config: FileSystemConfig, readonly maxSymlinkDepth: number;
) {
this._maxNameLength = config.maxNameLength;
this._maxPathLength = config.maxPathLength;
this._maxSymlinkDepth = config.maxSymlinkDepth;
this._VDiskManager = new VDiskManager(); private constructor(manager: VDiskManager, config: FileSystemConfig) {
for (const dev of devices) { this.maxNameLength = config.maxNameLength;
this._VDiskManager.registerDisk(dev.config, dev.dstore, dev.mstore); this.maxPathLength = config.maxPathLength;
} this.maxSymlinkDepth = config.maxSymlinkDepth;
this._VDiskManager = manager;
} }
private resolveNode(ptr: NodePointer): Node | undefined { private resolveNode(ptr: NodePointer): Node | undefined {
@@ -61,10 +57,11 @@ export class FileSystem {
return dev.getNode(fptr.inode); return dev.getNode(fptr.inode);
} }
public static init( // Make async
public static async init(
devices: Array<{ dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }>, devices: Array<{ dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }>,
config: FileSystemConfig = { maxNameLength: 255, maxPathLength: Infinity, maxSymlinkDepth: 40 }, config: FileSystemConfig = { maxNameLength: 255, maxPathLength: Infinity, maxSymlinkDepth: 40 },
): FileSystem { ): Promise<FileSystem> {
if (devices.length === 0) { if (devices.length === 0) {
throw { throw {
type: "FileSystemInitializationError", type: "FileSystemInitializationError",
@@ -89,19 +86,39 @@ export class FileSystem {
} satisfies FileSystemInitializationError; } satisfies FileSystemInitializationError;
} }
return new FileSystem(devices, config); const manager = new VDiskManager();
for (const dev of devices) {
await manager.registerDisk(dev.config, dev.dstore, dev.mstore);
}
return new FileSystem(manager, config);
} }
public getRoot(): DirectoryNode { public getRoot(): DirectoryNode {
const dev = this._VDiskManager.getDisk(0); const dev = this._VDiskManager.getDisk(0);
if (!dev) throw new Error("Filesystem corrupted, system device not found!"); if (!dev) {
throw {
type: "FileSystemCorruption",
message: "System device not registered. File System corrupted!",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
return dev.getNode(0) as DirectoryNode; return dev.getNode(0) as DirectoryNode;
} }
public getNodeEntries(ptr: NodePointer): readonly NodeEntry[] | undefined { public getNodeEntries(ptr: NodePointer): readonly NodeEntry[] | undefined {
const fptr = fromPtr(ptr); const fptr = fromPtr(ptr);
const dev = this._VDiskManager.getDisk(fptr.device_id)!; const dev = this._VDiskManager.getDisk(fptr.device_id);
if (!dev) {
throw {
type: "DeviceNotFound",
message: `Device under id ${fptr.device_id} not found`,
timestamp: Date.now(),
device_id: fptr.device_id,
} satisfies DeviceNotFoundError;
}
return dev.getIndex().get(ptr); return dev.getIndex().get(ptr);
} }
@@ -114,10 +131,79 @@ export class FileSystem {
return this.resolveNode(ptr) !== undefined; return this.resolveNode(ptr) !== undefined;
} }
public mount(mount: NodePointer, target: NodePointer) {
const mptr = fromPtr(mount);
const tptr = fromPtr(target);
if (!this._VDiskManager.hasDisk(mptr.device_id)) {
throw {
type: "DeviceNotFound",
message: `Device under id ${mptr.device_id} not found`,
timestamp: Date.now(),
device_id: mptr.device_id,
} satisfies DeviceNotFoundError;
}
if (!this._VDiskManager.hasDisk(tptr.device_id)) {
throw {
type: "DeviceNotFound",
message: `Device under id ${tptr.device_id} not found`,
timestamp: Date.now(),
device_id: tptr.device_id,
} satisfies DeviceNotFoundError;
}
if (!this.getNode(mount)) {
throw {
type: "NodeNotFound",
message: `Node under inode ${mptr.inode} not found under device ${mptr.device_id}`,
timestamp: Date.now(),
pointer: mount,
} satisfies NodeNotFoundError;
}
if (!this.getNode(target)) {
throw {
type: "NodeNotFound",
message: `Node under inode ${tptr.inode} not found under device ${tptr.device_id}`,
timestamp: Date.now(),
pointer: target,
} satisfies NodeNotFoundError;
}
this._Mounts.set(mount, target);
this._RMounts.set(target, mount);
}
public isMountPoint(ptr: NodePointer): boolean {
return this._Mounts.has(ptr);
}
public isMountTarget(target: NodePointer): boolean {
return this._RMounts.has(target);
}
public getMountTarget(ptr: NodePointer): NodePointer | undefined {
return this._Mounts.get(ptr);
}
public getMountPoint(target: NodePointer): NodePointer | undefined {
return this._RMounts.get(target);
}
public isFile(ptr: NodePointer): boolean { public isFile(ptr: NodePointer): boolean {
const fptr = fromPtr(ptr); const fptr = fromPtr(ptr);
const node = this.resolveNode(ptr); const node = this.resolveNode(ptr);
if (!this._VDiskManager.hasDisk(fptr.device_id)) {
throw {
type: "DeviceNotFound",
message: `Device under id ${fptr.device_id} not found`,
timestamp: Date.now(),
device_id: fptr.device_id,
} satisfies DeviceNotFoundError;
}
if (node === undefined) { if (node === undefined) {
throw { throw {
type: "NodeNotFound", type: "NodeNotFound",
@@ -134,6 +220,15 @@ export class FileSystem {
const fptr = fromPtr(ptr); const fptr = fromPtr(ptr);
const node = this.resolveNode(ptr); const node = this.resolveNode(ptr);
if (!this._VDiskManager.hasDisk(fptr.device_id)) {
throw {
type: "DeviceNotFound",
message: `Device under id ${fptr.device_id} not found`,
timestamp: Date.now(),
device_id: fptr.device_id,
} satisfies DeviceNotFoundError;
}
if (node === undefined) { if (node === undefined) {
throw { throw {
type: "NodeNotFound", type: "NodeNotFound",
@@ -150,6 +245,15 @@ export class FileSystem {
const fptr = fromPtr(ptr); const fptr = fromPtr(ptr);
const node = this.resolveNode(ptr); const node = this.resolveNode(ptr);
if (!this._VDiskManager.hasDisk(fptr.device_id)) {
throw {
type: "DeviceNotFound",
message: `Device under id ${fptr.device_id} not found`,
timestamp: Date.now(),
device_id: fptr.device_id,
} satisfies DeviceNotFoundError;
}
if (node === undefined) { if (node === undefined) {
throw { throw {
type: "NodeNotFound", type: "NodeNotFound",
@@ -162,7 +266,7 @@ export class FileSystem {
return node.type === NodeType.Symlink ? true : false; return node.type === NodeType.Symlink ? true : false;
} }
public moveNode(source: NodePointer, destination: NodePointer, name?: string) { public async moveNode(source: NodePointer, destination: NodePointer, name?: string) {
const sptr = fromPtr(source); const sptr = fromPtr(source);
const dptr = fromPtr(destination); const dptr = fromPtr(destination);
const sdev = this._VDiskManager.getDisk(sptr.device_id); const sdev = this._VDiskManager.getDisk(sptr.device_id);
@@ -226,7 +330,13 @@ export class FileSystem {
const sdevIndex = sdev.getIndex(); const sdevIndex = sdev.getIndex();
const s_entry = sdevIndex.get(source); const s_entry = sdevIndex.get(source);
if (!s_entry || !s_entry[0]) throw new Error("File System corruption, reverse index is missing a field"); if (!s_entry || !s_entry[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
const pinode = s_entry[0].pinode; const pinode = s_entry[0].pinode;
@@ -242,7 +352,7 @@ export class FileSystem {
} satisfies AlreadyExistsError; } satisfies AlreadyExistsError;
} }
if (nodeName.length > this._maxNameLength) { if (nodeName.length > this.maxNameLength) {
throw { throw {
type: "InvalidNodeName", type: "InvalidNodeName",
message: `Invalid name for the ${source} source node`, message: `Invalid name for the ${source} source node`,
@@ -263,13 +373,13 @@ export class FileSystem {
} }
if (sptr.device_id === dptr.device_id) { if (sptr.device_id === dptr.device_id) {
ddev.moveNodeEntry(pinode, dptr.inode, s_entry[0].name, name); await ddev.moveNodeEntry(pinode, dptr.inode, s_entry[0].name, name);
} else { } else {
console.error("cross device node movement not yet implemented"); console.error("cross device node movement not yet implemented");
} }
} }
public createNode( public async createNode(
parent: NodePointer, parent: NodePointer,
name: string, name: string,
data: data:
@@ -326,7 +436,7 @@ export class FileSystem {
} satisfies AlreadyExistsError; } satisfies AlreadyExistsError;
} }
if (name.length > this._maxNameLength) { if (name.length > this.maxNameLength) {
throw { throw {
type: "InvalidNodeName", type: "InvalidNodeName",
message: `Invalid name for the new node`, message: `Invalid name for the new node`,
@@ -336,14 +446,14 @@ export class FileSystem {
} satisfies InvalidNodeNameError; } satisfies InvalidNodeNameError;
} }
pdev.createNodeEntry(pptr.inode, name, data); await pdev.createNodeEntry(pptr.inode, name, data);
} }
public deleteNode(target: NodePointer) { public async deleteNode(target: NodePointer) {
const tptr = fromPtr(target); const tptr = fromPtr(target);
const tdev = this._VDiskManager.getDisk(tptr.device_id); const tdev = this._VDiskManager.getDisk(tptr.device_id);
if (tptr.device_id === 0 && tptr.inode === 0) { if (tptr.inode === 0) {
throw { throw {
type: "IllegalMutation", type: "IllegalMutation",
message: `Attempt at illegal mutation of node under inode 0 (root)`, message: `Attempt at illegal mutation of node under inode 0 (root)`,
@@ -362,12 +472,18 @@ export class FileSystem {
const tdevIndex = tdev.getIndex(); const tdevIndex = tdev.getIndex();
const t_entry = tdevIndex.get(target); const t_entry = tdevIndex.get(target);
if (!t_entry || !t_entry[0]) throw new Error("File System corruption, reverse index is missing a field"); if (!t_entry || !t_entry[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
tdev.unlinkNodeEntry(tptr.inode, t_entry[0].name); await tdev.unlinkNodeEntry(t_entry[0].pinode, t_entry[0].name);
} }
public writeContent(target: NodePointer, content: Blob) { public async writeContent(target: NodePointer, content: Blob) {
const ptr = fromPtr(target); const ptr = fromPtr(target);
const dev = this._VDiskManager.getDisk(ptr.device_id); const dev = this._VDiskManager.getDisk(ptr.device_id);
const node = this.resolveNode(target); const node = this.resolveNode(target);
@@ -390,7 +506,7 @@ export class FileSystem {
} satisfies NodeNotFoundError; } satisfies NodeNotFoundError;
} }
if (node.type === NodeType.Directory) { if (node.type === NodeType.Directory || node.type === NodeType.Symlink) {
throw { throw {
type: "NotAFile", type: "NotAFile",
message: `Node is not a file`, message: `Node is not a file`,
@@ -400,7 +516,7 @@ export class FileSystem {
} satisfies NotAFileError; } satisfies NotAFileError;
} }
dev.writeContent((node as FileNode).content, content); await dev.writeContent((node as FileNode).content, content);
} }
public streamContent(target: NodePointer): Readable { public streamContent(target: NodePointer): Readable {
@@ -439,7 +555,7 @@ export class FileSystem {
return dev.streamContent((node as FileNode).content); return dev.streamContent((node as FileNode).content);
} }
public modifyNode(target: NodePointer, data: { mode?: number; owner?: number; group?: number }) { public async modifyNode(target: NodePointer, data: { mode?: number; owner?: number; group?: number }) {
const ptr = fromPtr(target); const ptr = fromPtr(target);
const dev = this._VDiskManager.getDisk(ptr.device_id); const dev = this._VDiskManager.getDisk(ptr.device_id);
const node = this.resolveNode(target); const node = this.resolveNode(target);
@@ -462,7 +578,7 @@ export class FileSystem {
} satisfies NodeNotFoundError; } satisfies NodeNotFoundError;
} }
if (node.type === NodeType.Directory) { if (node.type === NodeType.Directory || node.type === NodeType.Symlink) {
throw { throw {
type: "NotAFile", type: "NotAFile",
message: `Node is not a file`, message: `Node is not a file`,
@@ -472,7 +588,7 @@ export class FileSystem {
} satisfies NotAFileError; } satisfies NotAFileError;
} }
dev.writeNodeEntry(node.inode, data); await dev.writeNodeEntry(node.inode, data);
} }
public canRead(nodep: NodePointer, user: UserInfo): boolean { public canRead(nodep: NodePointer, user: UserInfo): boolean {
@@ -490,7 +606,7 @@ export class FileSystem {
if (user.uid === node.owner) { if (user.uid === node.owner) {
return (node.mode & 0o400) !== 0; return (node.mode & 0o400) !== 0;
} else if (user.gid === node.group) { } else if (user.gid === node.group || user.group.includes(node.group)) {
return (node.mode & 0o040) !== 0; return (node.mode & 0o040) !== 0;
} else { } else {
return (node.mode & 0o004) !== 0; return (node.mode & 0o004) !== 0;
@@ -512,7 +628,7 @@ export class FileSystem {
if (user.uid === node.owner) { if (user.uid === node.owner) {
return (node.mode & 0o200) !== 0; return (node.mode & 0o200) !== 0;
} else if (user.gid === node.group) { } else if (user.gid === node.group || user.group.includes(node.group)) {
return (node.mode & 0o020) !== 0; return (node.mode & 0o020) !== 0;
} else { } else {
return (node.mode & 0o002) !== 0; return (node.mode & 0o002) !== 0;
@@ -534,7 +650,7 @@ export class FileSystem {
if (user.uid === node.owner) { if (user.uid === node.owner) {
return (node.mode & 0o100) !== 0; return (node.mode & 0o100) !== 0;
} else if (user.gid === node.group) { } else if (user.gid === node.group || user.group.includes(node.group)) {
return (node.mode & 0o010) !== 0; return (node.mode & 0o010) !== 0;
} else { } else {
return (node.mode & 0o001) !== 0; return (node.mode & 0o001) !== 0;
+3 -2
View File
@@ -3,7 +3,7 @@ export type Node = FileNode | DirectoryNode | SymlinkNode;
export type NodeHash = ReadonlyMap<number, Node>; export type NodeHash = ReadonlyMap<number, Node>;
export type ShadowHash = ReadonlyMap<number, Node | null>; export type ShadowHash = ReadonlyMap<number, Node | null>;
export type NodePointer = string; export type NodePointer = `${string}:${string}`;
export interface NodeEntry { export interface NodeEntry {
readonly pinode: number; readonly pinode: number;
@@ -62,7 +62,8 @@ export function toPtr({ device_id, inode }: { device_id: number; inode: number }
} }
export function fromPtr(ptr: NodePointer): { device_id: number; inode: number } { export function fromPtr(ptr: NodePointer): { device_id: number; inode: number } {
if (!ptr.match(/\d+[:]\d+$/g)) { if (!ptr.match(/^\d+[:]\d+$/)) {
//TODO: Make typed
throw new Error("Invalid node pointer format"); throw new Error("Invalid node pointer format");
} }
const arr = ptr.split(":"); const arr = ptr.split(":");
+4 -3
View File
@@ -1,3 +1,4 @@
import type { NodePointer } from "./filesystem/node";
import { type HistoryState } from "./history_state"; import { type HistoryState } from "./history_state";
import { createShellState, type ShellState } from "./shell_state"; import { createShellState, type ShellState } from "./shell_state";
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors"; import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
@@ -13,15 +14,15 @@ export interface UserInfo {
readonly uid: number; readonly uid: number;
readonly gid: number; readonly gid: number;
readonly group: readonly number[]; readonly group: readonly number[];
readonly home: number; readonly home: NodePointer;
} }
export interface SessionState { export interface SessionState {
readonly user: UserInfo; readonly user: UserInfo;
readonly envVars: ReadonlyMap<string, string>; readonly envVars: ReadonlyMap<string, string>;
readonly history: HistoryState; readonly history: HistoryState;
readonly cwd: number; readonly cwd: NodePointer;
readonly pwd: number; readonly pwd: NodePointer;
readonly exitCode: number; readonly exitCode: number;
} }
+166 -50
View File
@@ -1,7 +1,7 @@
import type { FileSystemCorruptionError, NodeNotFoundError, NotADirectoryError } from "@core/filesystem/errors";
import { fromPtr, NodeType, toPtr, type Node, type NodePointer } from "@core/filesystem/node";
import { getCurrentSession } from "@core/session_manager"; import { getCurrentSession } from "@core/session_manager";
import type { ShellState } from "@core/shell_state"; import type { ShellState } from "@core/shell_state";
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
import { type DirectoryNode, type NodeEntry, type NodePointer } from "../filesystem/node";
/* /*
/home/grzegorz/Documents/homework /home/grzegorz/Documents/homework
@@ -9,77 +9,193 @@ import { type DirectoryNode, type NodeEntry, type NodePointer } from "../filesys
"" ""
*/ */
export function resolvePath(state: ShellState, path: string): NodeEntry { export function resolvePath(state: ShellState, path: string): { device_id: number; inode: number } {
let linkDepth = 0;
const maxDepth = state.filesystem.maxSymlinkDepth;
const session = getCurrentSession(state); const session = getCurrentSession(state);
const isAbsolute = path.startsWith("/"); // true const isAbsolute = path.startsWith("/");
const normalizedPath: string = path.replace(/^\/+|\/+$/g, ""); // home/grzegorz/Documents/homework const pathComponents: string[] = path.split("/").filter(c => c.length > 0);
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0); // ["home", "grzegorz", "Documents", "homework"]
let currentVD: number = state.filesystem.getSysPartitionID();
// Fix to dynamically get the root inode VV let currentDeviceId: number;
if (pathComponents.length === 0 && isAbsolute) return [0, currentVD]; let currentNode: Node;
// Move behaviour into cd built-in
if (pathComponents.length === 0) return [session.cwd, currentVD];
let currentNode = isAbsolute === true ? state.filesystem.getRoot() : state.filesystem.getNode(session.cwd)!; if (isAbsolute) {
currentDeviceId = 0;
currentNode = state.filesystem.getRoot();
} else if (!isAbsolute && pathComponents[0] === "~") {
const home = fromPtr(session.user.home);
currentDeviceId = home.device_id;
currentNode = state.filesystem.getNode(session.user.home)!;
if (!currentNode) {
throw {
type: "NodeNotFound",
message: `[Panic] ${session.user.username}'s home directory does not exist!`,
timestamp: Date.now(),
pointer: session.user.home,
} satisfies NodeNotFoundError;
}
pathComponents.shift();
if (!currentNode) { if (currentNode.type === NodeType.Symlink) {
throw Error("Current working directory does not exist in the filesystem! Is the userdata corrupted?"); if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
const target = currentNode.target;
if (target.startsWith("/")) {
currentDeviceId = 0;
currentNode = state.filesystem.getRoot();
} else {
const entries = state.filesystem.getNodeEntries(session.user.home);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(
toPtr({ device_id: entries[0].pdevice_id, inode: entries[0].pinode }),
)!;
}
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
}
} else {
const cwd = fromPtr(session.cwd);
currentDeviceId = cwd.device_id;
currentNode = state.filesystem.getNode(session.cwd)!;
if (!currentNode) {
throw {
type: "NodeNotFound",
message: "[Panic] Current working directory does not exist!",
timestamp: Date.now(),
pointer: session.cwd,
} satisfies NodeNotFoundError;
}
} }
for (let i = 0; i < pathComponents.length; i++) { while (pathComponents.length > 0) {
// Null assertion because by this point the array cannot be empty const name = pathComponents.shift()!;
const name: string = pathComponents[i]!;
if (state.filesystem.isFile(currentNode.inode) && !(i === pathComponents.length - 1)) if (name === ".") continue;
if (name === "..") {
if (state.filesystem.isMountTarget(toPtr({ device_id: currentDeviceId, inode: currentNode.inode }))) {
const mount = state.filesystem.getMountPoint(
toPtr({ device_id: currentDeviceId, inode: currentNode.inode }),
);
if (!mount) {
throw {
type: "FileSystemCorruption",
message: "Mount registry entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
const entries = state.filesystem.getNodeEntries(mount);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(
toPtr({ device_id: entries[0].pdevice_id, inode: entries[0].pinode }),
)!;
continue;
}
if (currentNode.inode === 0) continue;
const entries = state.filesystem.getNodeEntries(
toPtr({ device_id: currentDeviceId, inode: currentNode.inode }),
);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(
toPtr({ device_id: entries[0].pdevice_id, inode: entries[0].pinode }),
)!;
continue;
}
if (currentNode.type !== NodeType.Directory) {
throw { throw {
type: "NotADirectory", type: "NotADirectory",
message: `${name} is not a directory`, message: "Not a directory",
timestamp: Date.now(), timestamp: Date.now(),
inode: currentNode.inode, inode: currentNode.inode,
nodeType: TreeNodeType.File, nodeType: currentNode.type,
} satisfies NotADirectoryError; } satisfies NotADirectoryError;
if (currentNode.type === TreeNodeType.Device) {
currentVD = currentNode.target_id;
continue;
} }
if (currentNode.type === TreeNodeType.Symlink) { const childInode = currentNode.children.get(name);
const ptr: NodePointer = resolvePath(state, currentNode.target); if (childInode === undefined) {
currentNode = state.filesystem.getNode(ptr)!;
if (!currentNode) {
throw {
type: "NodeNotFound",
message: `${name} not found`,
timestamp: Date.now(),
inode: ptr[0],
} satisfies NodeNotFoundError;
}
continue;
}
if (name === "~") {
currentNode = state.filesystem.getNode(session.user.home) as DirectoryNode;
continue;
}
const inode = currentNode.content.get(name);
if (!inode)
throw { throw {
type: "NodeNotFound", type: "NodeNotFound",
message: `${name} not found`, message: `${name} not found`,
timestamp: Date.now(), timestamp: Date.now(),
inode: currentNode.inode, pointer: toPtr({ device_id: currentDeviceId, inode: currentNode.inode }),
} satisfies NodeNotFoundError; } satisfies NodeNotFoundError;
}
currentNode = state.filesystem.getNode(inode) as DirectoryNode; let childPtr = toPtr({ device_id: currentDeviceId, inode: childInode });
if (state.filesystem.isMountPoint(childPtr)) {
const mount = state.filesystem.getMountTarget(childPtr)!.split("-")[0] as NodePointer;
childPtr = mount;
currentDeviceId = fromPtr(mount).device_id;
}
let child = state.filesystem.getNode(childPtr);
if (!child) {
throw {
type: "NodeNotFound",
message: `Node under ${childPtr} not found (probable dangling orphan)`,
timestamp: Date.now(),
pointer: childPtr,
} satisfies NodeNotFoundError;
}
if (child.type === NodeType.Symlink) {
// Change to typed error later on
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
const target = child.target;
if (target.startsWith("/")) {
currentDeviceId = 0;
currentNode = state.filesystem.getRoot();
} else {
const entries = state.filesystem.getNodeEntries(childPtr);
if (!entries?.[0]) {
throw {
type: "FileSystemCorruption",
message: "Reverse index entry missing, FileSystem corrupted",
timestamp: Date.now(),
} satisfies FileSystemCorruptionError;
}
currentDeviceId = entries[0].pdevice_id;
currentNode = state.filesystem.getNode(
toPtr({ device_id: entries[0].pdevice_id, inode: entries[0].pinode }),
)!;
}
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
continue;
}
currentNode = child;
} }
return [currentNode.inode, currentVD]; return { device_id: currentDeviceId, inode: currentNode.inode };
} }
export function resolveInode(state: ShellState, inode: number): string { export function resolveInode(state: ShellState, inode: number): string {
+32 -23
View File
@@ -1,58 +1,67 @@
import type { FileSystem } from "@core/filesystem/filesystem"; import type { FileSystem } from "@core/filesystem/filesystem";
import { TreeNodeType } from "@core/filesystem/node"; import { fromPtr, NodeType, toPtr, type NodePointer, type SymlinkNode } from "@core/filesystem/node";
export function printTree(fs: FileSystem, root: number): string { export function printTree(fs: FileSystem, root: NodePointer, rootLabel = "/"): string {
const rootNode = fs.getNode(root); const rootNode = fs.getNode(root);
if (rootNode === undefined) return ""; if (rootNode === undefined) return "";
const lines: string[] = []; const lines: string[] = [];
const rootFptr = fromPtr(root);
lines.push(rootNode.name + ` (${rootNode.inode})`); lines.push(`${rootLabel} (${rootFptr.device_id}:${rootFptr.inode})`);
type Frame = { type Frame = {
inode: number; ptr: NodePointer;
name: string;
prefix: string; prefix: string;
isLast: boolean; isLast: boolean;
}; };
const stack: Frame[] = []; const stack: Frame[] = [];
const getSorterChildren = (inode: number): number[] => { const getSortedChildren = (ptr: NodePointer): Array<{ name: string; ptr: NodePointer }> => {
const node = fs.getNode(inode); const node = fs.getNode(ptr);
if (!node || node.type !== TreeNodeType.Directory) return []; if (!node || node.type !== NodeType.Directory) return [];
const entries = Object.entries(node.children); const { device_id } = fromPtr(ptr);
const entries = Array.from(node.children.entries());
entries.sort(([a], [b]) => a.localeCompare(b)); entries.sort(([a], [b]) => a.localeCompare(b));
return entries.map(([, childInode]) => childInode) as number[];
return entries.map(([name, inode]) => ({
name,
ptr: toPtr({ device_id, inode }),
}));
}; };
const rootChildren = getSorterChildren(root); const rootChildren = getSortedChildren(root);
for (let i = rootChildren.length - 1; i >= 0; i--) { for (let i = rootChildren.length - 1; i >= 0; i--) {
const childInode: number = rootChildren[i] as number; const child = rootChildren[i]!;
const isLast = i === rootChildren.length - 1; const isLast = i === rootChildren.length - 1;
stack.push({ ptr: child.ptr, name: child.name, prefix: "", isLast });
stack.push({ inode: childInode, prefix: "", isLast });
} }
while (stack.length > 0) { while (stack.length > 0) {
const frame = stack.pop()!; const frame = stack.pop()!;
const node = fs.getNode(frame.inode); const node = fs.getNode(frame.ptr);
if (!node) continue; if (!node) continue;
const name = node.name; const fptr = fromPtr(frame.ptr);
const connector = frame.isLast ? "└── " : "├── "; const connector = frame.isLast ? "└── " : "├── ";
lines.push(frame.prefix + connector + name + ` (${node.inode})`); const symlinkSuffix = node.type === NodeType.Symlink ? ` -> ${(node as SymlinkNode).target}` : "";
lines.push(`${frame.prefix}${connector}${frame.name} (${fptr.device_id}:${fptr.inode})${symlinkSuffix}`);
if (node.type === TreeNodeType.Directory) { if (node.type === NodeType.Directory) {
const childPrefix = frame.prefix + (frame.isLast ? " " : "│ "); const childPrefix = frame.prefix + (frame.isLast ? " " : "│ ");
const children = getSorterChildren(frame.inode); const children = getSortedChildren(frame.ptr);
for (let i = children.length - 1; i >= 0; i--) { for (let i = children.length - 1; i >= 0; i--) {
const childInode = children[i] as number; const child = children[i]!;
const childIsLast = i === children.length - 1; const childIsLast = i === children.length - 1;
stack.push({
stack.push({ inode: childInode, prefix: childPrefix, isLast: childIsLast }); ptr: child.ptr,
name: child.name,
prefix: childPrefix,
isLast: childIsLast,
});
} }
} }
} }
File diff suppressed because it is too large Load Diff
+856 -55
View File
@@ -1,73 +1,874 @@
import { resolveInode, resolvePath } from "@core/util/path_resolver"; // @tests/core/util/path_resolver.test.ts (adjust)
import { FileSystem } from "@core/filesystem/filesystem";
import {
NodeType,
toPtr,
type DirectoryNode,
type FileNode,
type Node,
type NodePointer,
type SymlinkNode,
} from "@core/filesystem/node";
import { DefaultVDiskConfig } from "@core/filesystem/vdisk";
import type { SessionState, UserInfo } from "@core/session_manager";
import type { ShellState } from "@core/shell_state";
import { resolvePath } from "@core/util/path_resolver";
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers"; import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers";
import { Fixture7Depth } from "@tests/helpers/state_fixture"; import fc from "fast-check";
import { describe, expect, test } from "vitest"; import { describe, expect, it } from "vitest";
const state = Fixture7Depth.State; // ============================================================================
const fs = state.filesystem; // Node fixtures
// ============================================================================
describe("resolvePath", () => { function makeDir(inode: number, children: Record<string, number> = {}): DirectoryNode {
test("returns an inode from an absolute path", () => { return {
const path = "/d1/d2/d3/d4/"; type: NodeType.Directory,
const result = resolvePath(fs, 1, path); inode,
link_count: 2,
mode: 0o755,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
children: new Map(Object.entries(children)),
};
}
expect(result).toBeDefined(); function makeFile(inode: number): FileNode {
expect(fs.getNode(result as number)!.name).toBe("d4"); return {
type: NodeType.File,
inode,
link_count: 1,
mode: 0o644,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
content: `uuid-${inode}`,
size: 0,
};
}
function makeSymlink(inode: number, target: string): SymlinkNode {
return {
type: NodeType.Symlink,
inode,
link_count: 1,
mode: 0o777,
owner: 0,
group: 0,
mtime: 0,
ctime: 0,
atime: 0,
target,
};
}
function makeUser(home: NodePointer = toPtr({ device_id: 0, inode: 0 })): UserInfo {
return {
username: "test",
uid: 1000,
gid: 1000,
group: [],
home,
};
}
// ============================================================================
// Tree builder — auto-assigns inodes, validates before use
// ============================================================================
interface TreeBuilder {
addDir(parentInode: number, name: string): number;
addFile(parentInode: number, name: string): number;
addSymlink(parentInode: number, name: string, target: string): number;
build(): Map<number, Node>;
}
function makeTree(): TreeBuilder {
const nodes = new Map<number, Node>([[0, makeDir(0)]]);
let nextInode = 1;
function attach(parentInode: number, name: string, childInode: number): void {
const parent = nodes.get(parentInode);
if (!parent || parent.type !== NodeType.Directory) {
throw new Error(`Parent inode ${parentInode} is not a directory`);
}
const children = new Map(parent.children);
children.set(name, childInode);
nodes.set(parentInode, { ...parent, children });
}
function add(node: Node, parentInode: number, name: string): number {
attach(parentInode, name, node.inode);
nodes.set(node.inode, node);
return node.inode;
}
return {
addDir(parentInode, name) {
return add(makeDir(nextInode++), parentInode, name);
},
addFile(parentInode, name) {
return add(makeFile(nextInode++), parentInode, name);
},
addSymlink(parentInode, name, target) {
return add(makeSymlink(nextInode++, target), parentInode, name);
},
build() {
for (const [key, node] of nodes) {
if (node.inode !== key) {
throw new Error(`inode mismatch: key=${key}, node.inode=${node.inode}`);
}
if (node.type === NodeType.Directory) {
for (const [cname, cinode] of node.children) {
if (!nodes.has(cinode)) {
throw new Error(`dangling child '${cname}' → inode ${cinode}`);
}
}
}
}
return nodes;
},
};
}
// ============================================================================
// FileSystem builder — real VDisk stack, one device per base map
// ============================================================================
async function makeFS(bases: Map<number, Node>[]): Promise<FileSystem> {
const devices = bases.map((base, id) => ({
dstore: new MemDataStore(),
mstore: new MemMetaStore(),
config: {
...DefaultVDiskConfig(id),
base,
index: Math.max(0, ...base.keys()),
},
}));
const fs = FileSystem.init(devices);
// `FileSystem.init` does not await `registerDisk` (see the init suite BUG);
// flush a macrotask so every disk is registered before the first resolve.
await new Promise(r => setImmediate(r));
return fs;
}
// ============================================================================
// Shell state fixture
// ============================================================================
function makeShellState(
fs: FileSystem,
opts: { cwd?: NodePointer; home?: NodePointer; user?: UserInfo } = {},
): ShellState {
const cwd = opts.cwd ?? toPtr({ device_id: 0, inode: 0 });
const user = opts.user ?? makeUser(opts.home);
const session = {
user,
envVars: new Map<string, string>(),
history: [],
cwd,
pwd: cwd,
exitCode: 0,
} as unknown as SessionState;
return {
filesystem: fs,
users: new Map(),
groups: new Map(),
sessionStack: [session],
} as unknown as ShellState;
}
// ============================================================================
// Path normalization
// ============================================================================
describe("resolvePath — path normalization", () => {
/**
* `/` is the root of device 0; no traversal is needed.
*/
it("resolves '/' to the root of device 0", async () => {
const fs = await makeFS([makeTree().build()]);
expect(resolvePath(makeShellState(fs), "/")).toEqual({ device_id: 0, inode: 0 });
}); });
test("returns an inode from a relative path", () => { /**
const path = "./d2/d3/d4/"; * Redundant leading slashes are stripped by the normalizer.
const result = resolvePath(fs, 1, path); */
it("resolves '/', '//', and '///' identically", async () => {
expect(result).toBeDefined(); const fs = await makeFS([makeTree().build()]);
expect(fs.getNode(result as number)!.name).toBe("d4"); const state = makeShellState(fs);
for (const p of ["/", "//", "///"]) {
expect(resolvePath(state, p)).toEqual({ device_id: 0, inode: 0 });
}
}); });
test("returns an inode from a relative parent path", () => { /**
const path = "../d1/d2/d3/d4/"; * Empty path returns the current working directory without traversal.
const result = resolvePath(fs, 1, path); */
it("resolves an empty string to the current working directory", async () => {
expect(result).toBeDefined(); const t = makeTree();
expect(fs.getNode(result as number)!.name).toBe("d4"); const work = t.addDir(0, "work");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) });
expect(resolvePath(state, "")).toEqual({ device_id: 0, inode: work });
}); });
test("returns inode 0", () => { /**
const path = "/"; * Property: leading, trailing, and interior redundant slashes never change
const result = resolvePath(fs, 1, path); * 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");
expect(result).toBeDefined(); fc.assert(
expect(result).toBe(0); fc.property(
expect(fs.getNode(result as number)!.name).toBe("root"); fc.integer({ min: 0, max: 5 }),
}); fc.integer({ min: 0, max: 5 }),
fc.integer({ min: 1, max: 4 }),
test("returns inode 1 (cwd)", () => { (lead, trail, mid) => {
const path = ""; const path = "/".repeat(lead) + "a" + "/".repeat(mid) + "b" + "/".repeat(trail);
const result = resolvePath(fs, 1, path); expect(resolvePath(state, path)).toEqual(expected);
},
expect(result).toBeDefined(); ),
expect(result).toBe(1); );
expect(fs.getNode(result as number)!.name).toBe("d1");
});
test("throws because of a nonexistent path", () => {
expectNodeNotFoundError(() => resolvePath(fs, 1, "/d3"));
});
test("throws because of file path component", () => {
expectNotADirectoryError(() => resolvePath(fs, 6, "./deep_file.txt/d8"));
});
test("throws because of a nonexistent cwd inode (technicaly should never happen)", () => {
expectNodeNotFoundError(() => resolvePath(fs, 69, "/d3"));
}); });
}); });
describe("resolveInode", () => { // ============================================================================
test("returns an the path from the d4 node", () => { // Absolute paths
expect(resolveInode(state, 4, true)).toBe("/d1/d2/d3/d4"); // ============================================================================
describe("resolvePath — absolute paths", () => {
/**
* Single-component absolute path resolves to the child's pointer.
*/
it("resolves '/name' to the child node of root", async () => {
const t = makeTree();
const foo = t.addFile(0, "foo");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/foo")).toEqual({ device_id: 0, inode: foo });
}); });
test("returns an empty string from a non existent inode", () => { /**
expect(resolveInode(state, 999)).toBe(""); * Nested paths traverse each directory in turn.
*/
it("resolves a nested path '/a/b' to the final child", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
const b = t.addFile(a, "b");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 0, inode: b });
});
/**
* Deeper paths traverse more levels.
*/
it("resolves a deep path '/a/b/c/d' to the final child", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
const b = t.addDir(a, "b");
const c = t.addDir(b, "c");
const d = t.addFile(c, "d");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/a/b/c/d")).toEqual({ device_id: 0, inode: d });
});
/**
* Trailing slash is stripped and resolves the same as without it.
*/
it("resolves '/a/b/' to the same pointer as '/a/b'", async () => {
const t = makeTree();
const a = t.addDir(0, "a");
t.addFile(a, "b");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs);
expect(resolvePath(state, "/a/b/")).toEqual(resolvePath(state, "/a/b"));
});
/**
* Missing top-level component raises a typed NodeNotFound.
*/
it("throws NodeNotFound when the first component does not exist", async () => {
const fs = await makeFS([makeTree().build()]);
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/missing"));
});
/**
* Missing intermediate component raises a typed NodeNotFound.
*/
it("throws NodeNotFound when an intermediate component does not exist", async () => {
const t = makeTree();
t.addDir(0, "a");
const fs = await makeFS([t.build()]);
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/a/missing/b"));
});
/**
* Descending through a file at a non-final position is rejected with
* NotADirectory (this one works — the isFile check fires because `a` is
* not the last component).
*/
it("throws NotADirectory when traversing through a file at a non-final position", async () => {
const t = makeTree();
t.addFile(0, "a");
const fs = await makeFS([t.build()]);
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b/c"));
});
/**
* EXPECTED-TO-FAIL: descending through a file at the final position should
* also throw NotADirectory. Current implementation skips the isFile check
* on the last iteration and then crashes on `(file as Directory).children`.
*/
it("should throw NotADirectory when descending through a file at the final position", async () => {
const t = makeTree();
t.addFile(0, "a");
const fs = await makeFS([t.build()]);
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b"));
});
});
// ============================================================================
// Relative paths
// ============================================================================
describe("resolvePath — relative paths", () => {
/**
* A single relative component resolves against cwd.
*/
it("resolves a relative path from a device-0 cwd", async () => {
const t = makeTree();
const work = t.addDir(0, "work");
const file = t.addFile(work, "file");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) });
expect(resolvePath(state, "file")).toEqual({ device_id: 0, inode: file });
});
/**
* Multi-component relative paths traverse from cwd.
*/
it("resolves a multi-component relative path from cwd", async () => {
const t = makeTree();
const work = t.addDir(0, "work");
const sub = t.addDir(work, "sub");
const leaf = t.addFile(sub, "leaf");
const fs = await makeFS([t.build()]);
const state = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: work }) });
expect(resolvePath(state, "sub/leaf")).toEqual({ device_id: 0, inode: leaf });
});
/**
* Missing relative component raises a typed NodeNotFound.
*/
it("throws NodeNotFound for a missing relative component", async () => {
const fs = await makeFS([makeTree().build()]);
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "nope"));
});
});
// ============================================================================
// ~ expansion
// ============================================================================
describe("resolvePath — '~' expansion", () => {
/**
* `~` expands to the user's home directory (home on device 0).
*/
it("expands '~' to the user's home directory", async () => {
const t = makeTree();
const home = t.addDir(0, "home");
const fs = await makeFS([t.build()]);
const user = makeUser(toPtr({ device_id: 0, inode: home }));
const state = makeShellState(fs, { user });
expect(resolvePath(state, "~")).toEqual({ device_id: 0, inode: home });
});
/**
* `~/name` expands home first, then resolves `name` beneath it.
*/
it("expands '~/name' to a child of home", async () => {
const t = makeTree();
const home = t.addDir(0, "home");
const file = t.addFile(home, "file");
const fs = await makeFS([t.build()]);
const user = makeUser(toPtr({ device_id: 0, inode: home }));
const state = makeShellState(fs, { user });
expect(resolvePath(state, "~/file")).toEqual({ device_id: 0, inode: file });
});
/**
* EXPECTED-TO-FAIL: `~` expansion never touches `currentVD`, so a home on
* device 1 resolves the first component but then reads subsequent children
* from device 0 — usually crashing on a missing inode.
*/
it("should resolve '~/file' when home lives on device 1", async () => {
const t0 = makeTree();
const t1 = makeTree();
const home = t1.addDir(0, "home");
const file = t1.addFile(home, "file");
const fs = await makeFS([t0.build(), t1.build()]);
const user = makeUser(toPtr({ device_id: 1, inode: home }));
const state = makeShellState(fs, { user });
expect(resolvePath(state, "~/file")).toEqual({ device_id: 1, inode: file });
});
});
// ============================================================================
// Symlink resolution
// ============================================================================
describe("resolvePath — symlink resolution", () => {
/**
* Absolute symlink targets resolve from device 0's root.
*/
it("follows an absolute symlink target", async () => {
const t = makeTree();
const real = t.addDir(0, "real");
const leaf = t.addFile(real, "leaf");
t.addSymlink(0, "link", "/real/leaf");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 0, inode: leaf });
});
});
// ============================================================================
// Mount points
// ============================================================================
describe("resolvePath — mount points", () => {
/**
* EXPECTED-TO-FAIL: mount redirect must fire on the child before descent.
* `/mnt` alone should return the mounted device's root, not the mountpoint
* directory on the parent device.
*/
it("should resolve '/mnt' to the mounted device's root", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/mnt")).toEqual({ device_id: 1, inode: 0 });
});
/**
* EXPECTED-TO-FAIL: `/mnt/file` should descend through the mount and land
* on `/file` on device 1 — the trailing component must not be consumed by
* the redirect.
*/
it("should resolve '/mnt/file' to '/file' on the mounted device", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const file = t1.addFile(0, "file");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/mnt/file")).toEqual({ device_id: 1, inode: file });
});
/**
* EXPECTED-TO-FAIL: deep paths through a mount must traverse the mounted
* device for every subsequent component.
*/
it("should resolve '/mnt/sub/leaf' to '/sub/leaf' on the mounted device", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
});
/**
* A non-mountpoint directory resolves to itself on the parent device —
* `/a` is not a mount, so no redirect.
*/
it("resolves a non-mountpoint directory to itself on the parent device", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a"); // /a = device 0:1 (not a mountpoint)
const mnt = t0.addDir(0, "mnt"); // /mnt = device 0:2 (the mountpoint)
const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(
toPtr({ device_id: 0, inode: mnt }), // "0:2" — the mountpoint
toPtr({ device_id: 1, inode: 0 }),
);
const state = makeShellState(fs);
// /a is not a mountpoint → resolves to itself on device 0
expect(resolvePath(state, "/a")).toEqual({ device_id: 0, inode: a });
// /mnt IS a mountpoint → redirects to device 1's root
// (this is already covered by the /mnt tests; include for contrast or drop)
expect(resolvePath(state, "/mnt")).toEqual({ device_id: 1, inode: 0 });
});
/**
* EXPECTED-TO-FAIL: nested mount at `/a/b` should redirect to dev1's sub.
*/
it("should resolve '/a/b' (nested mount) to the mounted device's sub", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a");
const b = t0.addDir(a, "b");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: b }), toPtr({ device_id: 1, inode: sub }));
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 1, inode: sub });
});
/**
* EXPECTED-TO-FAIL: continuation of the nested case — `/a/b/leaf` should
* land on dev1's leaf through the mounted sub.
*/
it("should resolve '/a/b/leaf' through a nested mount", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a");
const b = t0.addDir(a, "b");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: b }), toPtr({ device_id: 1, inode: sub }));
expect(resolvePath(makeShellState(fs), "/a/b/leaf")).toEqual({ device_id: 1, inode: leaf });
});
/**
* EXPECTED-TO-FAIL: two independent mounts must redirect independently.
*/
it("should resolve multiple independent mounts", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const other = t0.addDir(0, "other");
const t1 = makeTree();
const file = t1.addFile(0, "file");
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
fs.mount(toPtr({ device_id: 0, inode: other }), toPtr({ device_id: 1, inode: sub }));
const state = makeShellState(fs);
expect(resolvePath(state, "/mnt/file")).toEqual({ device_id: 1, inode: file });
expect(resolvePath(state, "/other/leaf")).toEqual({ device_id: 1, inode: leaf });
});
});
// ============================================================================
// Symlinks across mount points
// ============================================================================
describe("resolvePath — symlinks across mount points", () => {
/**
* EXPECTED-TO-FAIL: symlink whose target lands on another device must
* return the target's device id in the result. Without threading, the loop
* terminates with currentNode from dev1 but currentVD still 0.
*/
it("should thread the target's device into currentVD after a symlink→mount hop", async () => {
const t0 = makeTree();
t0.addSymlink(0, "link", "/mnt");
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 1, inode: 0 });
});
/**
* EXPECTED-TO-FAIL: full traversal through the symlink and across the
* mount. Verifies not only the final pointer is right, but that the loop
* can continue descending on the mounted device.
*/
it("should resolve through a symlink→mount hop and continue on the mounted device", async () => {
const t0 = makeTree();
t0.addSymlink(0, "link", "/mnt");
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const file = t1.addFile(0, "file");
const fs = await makeFS([t0.build(), t1.build()]);
fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
expect(resolvePath(makeShellState(fs), "/link/file")).toEqual({ device_id: 1, inode: file });
});
});
// ============================================================================
// Integration
// ============================================================================
describe("resolvePath — integration", () => {
/**
* Full traversal across multiple levels with a file terminus.
*/
it("resolves a multi-level path through directories to a file", async () => {
const t = makeTree();
const varInode = t.addDir(0, "var");
const logInode = t.addDir(varInode, "log");
const appLog = t.addFile(logInode, "app.log");
const fs = await makeFS([t.build()]);
expect(resolvePath(makeShellState(fs), "/var/log/app.log")).toEqual({ device_id: 0, inode: appLog });
});
});
// ============================================================================
// Known bugs — each test asserts *current* behavior and goes red on the fix.
// ============================================================================
describe("resolvePath — known bugs", () => {
/**
* BUG: symlink depth overflow throws a raw `Error`, not a typed error.
* Same setup as above; asserts the thrown object isn't a discriminated
* union member (no `type` field).
*
* Fix: throw a typed `SymlinkLoopError` (or similar) from `errors.ts`.
*/
it("BUG: symlink depth overflow throws a raw Error, not a typed one", async () => {
const t = makeTree();
const sNames = Array.from({ length: 41 }, (_, i) => `s${i + 1}`);
t.addFile(0, "target");
for (let i = 0; i < 40; i++) {
t.addSymlink(0, sNames[i]!, `/${sNames[i + 1]}`);
}
t.addSymlink(0, sNames[40]!, "/target");
const fs = await makeFS([t.build()]);
let thrown: unknown = undefined;
try {
resolvePath(makeShellState(fs), "/s1");
} catch (e) {
thrown = e;
}
expect(thrown).toBeInstanceOf(Error);
expect(thrown).not.toHaveProperty("type");
// ^ 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", () => {
/**
* BASIC CASE. Mount `/mnt` (device 0) → device 1's root. From inside the
* mount (at `1:0`), `..` must exit through the reverse mount index to
* `/mnt`'s parent (`/`) — not stay put via the `inode === 0` shortcut.
*
* This is the direct fix target: the `..` branch must check
* `getMountSource(currentPtr)` *before* the `inode === 0` shortcut.
*/
it("'..' from a mount root returns to the mountpoint's parent", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
});
/**
* NON-ROOT MOUNTPOINT. Mount `/home/user/mnt` → device 1's root. `..` from
* the mounted root must land on `/home/user` (device 0), *not* `/`.
* Catches a fix that hardcodes "go to root on mount exit".
*/
it("'..' from a non-root mount returns to the mountpoint's immediate parent", async () => {
const t0 = makeTree();
const home = t0.addDir(0, "home");
const user = t0.addDir(home, "user");
const mnt = t0.addDir(user, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: user });
});
/**
* INSIDE-MOUNT `..`. A subdirectory of the mounted device is *not* the
* mount root, so `..` from `1:sub` must stay inside device 1 (regular
* reverse-index walk), not exit the mount. Catches a fix that exits the
* mount on every `..` inside the mounted device instead of only at its
* root.
*/
it("'..' from inside a mount (not at its root) stays inside the mount", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const fs = await makeFS([t0.build(), t1.build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
const atSub = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: sub }) });
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
});
/**
* MULTI-STEP `..`. From `/mnt/sub/leaf`, three consecutive `..` should
* produce `/mnt/sub` → `/mnt` → `/`. Exercises both the in-mount walk and
* the final mount exit in one flow. Catches a fix that only handles the
* "already at mount root" case but breaks when coming from deeper.
*/
it("multi-step '..' walks from deep inside a mount out to the parent device", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const sub = t1.addDir(0, "sub");
const leaf = t1.addFile(sub, "leaf");
const fs = await makeFS([t0.build(), t1.build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
// Sanity: full descent lands at `1:leaf`
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
// One `..` up: /mnt/sub
const atLeaf = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: leaf }) });
expect(resolvePath(atLeaf, "..")).toEqual({ device_id: 1, inode: sub });
// Another `..`: /mnt's content = dev1 root
const atSub = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: sub }) });
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
// Final `..`: exit the mount → /
const atMountedRoot = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
});
/**
* INDEPENDENT MOUNTS AT DIFFERENT DEPTHS. Mount A at `/a` (dev0 → dev1)
* and Mount B at `/b/nested` (dev0 → dev2). `..` from dev1's root must go
* to `/` (parent of `/a`), while `..` from dev2's root must go to `/b`
* (parent of `/b/nested`).
*
* Catches a fix that collapses the reverse index to a single entry — e.g.,
* if `getMountSource` returns the *first* mount's mountpoint for any
* target, or if `mount()` overwrites the wrong entry.
*/
it("'..' from different mounts returns to each mountpoint's own parent", async () => {
const t0 = makeTree();
const a = t0.addDir(0, "a");
const b = t0.addDir(0, "b");
const nested = t0.addDir(b, "nested");
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(toPtr({ device_id: 0, inode: nested }), toPtr({ device_id: 2, inode: 0 })); // /b/nested → dev2
// `..` from dev1's root → parent of `/a` = `/`
const atDev1Root = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
// `..` from dev2's root → parent of `/b/nested` = `/b`
const atDev2Root = makeShellState(fs, { cwd: toPtr({ device_id: 2, inode: 0 }) });
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 0, inode: b });
});
/**
* MOUNT NESTED IN A MOUNTED DEVICE'S TREE. The most realistic cross-device
* scenario:
*
* dev0: /mnt (0:1)
* dev1: / (1:0)
* /b (1:2) ← mountpoint of B
* dev2: / (2:0)
*
* Mount A: 0:1 → 1:0 (/mnt shows dev1)
* Mount B: 1:2 → 2:0 (/mnt/b shows dev2)
*
* From `/mnt/b` (dev2 root), `..` must exit B's mount to `/mnt/b`'s parent
* in the *mounted* device 1 (`1:0`), not skip straight to device 0. A
* second `..` then exits A's mount to `/`.
*
* This is the true "chained mount exit" case. Each `..` handles exactly
* one mount; the reverse index for `1:2` (B's mountpoint) lands on `1:0`
* (dev1 root), which is itself a mount target of A. The second `..` then
* exits A. Both steps go through the same `getMountSource` branch.
*/
it("'..' walks out of a mount nested inside another mount's device tree", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const t1 = makeTree();
const b = t1.addDir(0, "b");
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(toPtr({ device_id: 1, inode: b }), toPtr({ device_id: 2, inode: 0 })); // /mnt/b → dev2
// Sanity: /mnt/b resolves to dev2 root
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)
const atDev2Root = makeShellState(fs, { cwd: toPtr({ device_id: 2, inode: 0 }) });
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 1, inode: 0 });
// `..` from dev1 root → exit A's mount → parent of `0:mnt` = `/`
const atDev1Root = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
});
/**
* ROUND TRIP. `cd /mnt`, `cd ..`, `cd mnt` should land back at `{1:0}`.
* Catches a fix that mutates mount state (e.g., a stale `currentDeviceId`
* that leaks across calls) or that resolves `/mnt` differently after a
* `..` exit.
*/
it("entering and exiting a mount via resolvePath round-trips", async () => {
const t0 = makeTree();
const mnt = t0.addDir(0, "mnt");
const fs = await makeFS([t0.build(), makeTree().build()]);
await fs.mount(toPtr({ device_id: 0, inode: mnt }), toPtr({ device_id: 1, inode: 0 }));
// Start at /, enter /mnt
const fromRoot = makeShellState(fs);
expect(resolvePath(fromRoot, "/mnt")).toEqual({ device_id: 1, inode: 0 });
// `..` from mounted root → /
const atMnt = makeShellState(fs, { cwd: toPtr({ device_id: 1, inode: 0 }) });
expect(resolvePath(atMnt, "..")).toEqual({ device_id: 0, inode: 0 });
// `mnt` again from / → back to mounted root
const atRoot = makeShellState(fs, { cwd: toPtr({ device_id: 0, inode: 0 }) });
expect(resolvePath(atRoot, "mnt")).toEqual({ device_id: 1, inode: 0 });
}); });
}); });
+84 -15
View File
@@ -1,17 +1,23 @@
// @core/filesystem/errors.test-util.ts (adjust path to match yours)
import type { import type {
AlreadyExistsError, AlreadyExistsError,
DeviceNotFoundError,
DirectoryLoopError, DirectoryLoopError,
FileSystemCorruptionError,
FileSystemInitializationError,
IllegalMutationError, IllegalMutationError,
InvalidNodeNameError,
NodeNotFoundError, NodeNotFoundError,
NotADirectoryError, NotADirectoryError,
NotAFileError,
} from "@core/filesystem/errors"; } from "@core/filesystem/errors";
import type { TreeNodeType } from "@core/filesystem/node"; import type { NodeType } from "@core/filesystem/node";
import { expect } from "vitest"; import { expect } from "vitest";
export function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) { export async function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
let thrown: unknown; let thrown: unknown;
try { try {
fn(); await fn();
} catch (e) { } catch (e) {
thrown = e; thrown = e;
} }
@@ -20,19 +26,19 @@ export function expectThrows(fn: () => unknown, expectedShape: Record<string, un
expect(thrown).toMatchObject(expectedShape); expect(thrown).toMatchObject(expectedShape);
} }
export function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) { export async function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) {
expectThrows(fn, { return await expectThrows(fn, {
type: "NotADirectory", type: "NotADirectory",
inode: expect.any(Number) as number, inode: expect.any(Number) as number,
message: expect.any(String) as string, message: expect.any(String) as string,
timestamp: expect.any(Number) as number, timestamp: expect.any(Number) as number,
nodeType: expect.any(Number) as TreeNodeType, nodeType: expect.any(Number) as NodeType,
...overrides, ...overrides,
}); });
} }
export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) { export async function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) {
expectThrows(fn, { return await expectThrows(fn, {
type: "AlreadyExists", type: "AlreadyExists",
parentInode: expect.any(Number) as number, parentInode: expect.any(Number) as number,
name: expect.any(String) as string, name: expect.any(String) as string,
@@ -42,18 +48,23 @@ export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<
}); });
} }
export function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) { /**
expectThrows(fn, { * FIXED: `NodeNotFoundError` has `pointer: NodePointer` (a string), not `inode: number`.
* The previous version asserted `inode: expect.any(Number)` and would have failed
* against every real thrown `NodeNotFoundError`.
*/
export async function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) {
return await expectThrows(fn, {
type: "NodeNotFound", type: "NodeNotFound",
inode: expect.any(Number) as number, pointer: expect.any(String) as string,
message: expect.any(String) as string, message: expect.any(String) as string,
timestamp: expect.any(Number) as number, timestamp: expect.any(Number) as number,
...overrides, ...overrides,
}); });
} }
export function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) { export async function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) {
expectThrows(fn, { return await expectThrows(fn, {
type: "IllegalMutation", type: "IllegalMutation",
message: expect.any(String) as string, message: expect.any(String) as string,
timestamp: expect.any(Number) as number, timestamp: expect.any(Number) as number,
@@ -61,8 +72,8 @@ export function expectIllegalMutationError(fn: () => unknown, overrides?: Partia
}); });
} }
export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) { export async function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) {
expectThrows(fn, { return await expectThrows(fn, {
type: "DirectoryLoop", type: "DirectoryLoop",
descendantInode: expect.any(Number) as number, descendantInode: expect.any(Number) as number,
ancestorInode: expect.any(Number) as number, ancestorInode: expect.any(Number) as number,
@@ -71,3 +82,61 @@ export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<Dir
...overrides, ...overrides,
}); });
} }
// ---- NEW helpers below ----
export async function expectDeviceNotFoundError(fn: () => unknown, overrides?: Partial<DeviceNotFoundError>) {
return await expectThrows(fn, {
type: "DeviceNotFound",
device_id: expect.any(Number) as number,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export async function expectNotAFileError(fn: () => unknown, overrides?: Partial<NotAFileError>) {
return await expectThrows(fn, {
type: "NotAFile",
inode: expect.any(Number) as number,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
nodeType: expect.any(Number) as NodeType,
...overrides,
});
}
export async function expectFileSystemInitializationError(
fn: () => unknown,
overrides?: Partial<FileSystemInitializationError>,
) {
return await expectThrows(fn, {
type: "FileSystemInitializationError",
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export async function expectInvalidNodeNameError(fn: () => unknown, overrides?: Partial<InvalidNodeNameError>) {
return await expectThrows(fn, {
type: "InvalidNodeName",
pointer: expect.any(String) as string,
attemptedName: expect.any(String) as string,
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
export async function expectFileSystemCorruptionError(
fn: () => unknown,
overrides?: Partial<FileSystemCorruptionError>,
) {
return await expectThrows(fn, {
type: "FileSystemCorruption",
message: expect.any(String) as string,
timestamp: expect.any(Number) as number,
...overrides,
});
}
-91
View File
@@ -1,91 +0,0 @@
import { FileSystem } from "@core/filesystem/filesystem";
import type { TreeNode } from "@core/filesystem/node";
import type { GroupInfo, UserInfo } from "@core/session_manager";
import { createInitialShellState, type ShellState } from "@core/shell_state";
import { deserializeFileSystem } from "@shell/serializer";
import { buildTestFS } from "./filesystems_fixture";
import { depth7Tree } from "./tree_fixture";
export class Fixture {
/*
root (0)
├── folder1 (1)
│ └── subdir1 (2)
├── folder2 (3)
│ ├── subdir2 (4)
│ └── subdir3 (5)
│ └── empty-foo (6)
└── some-file (7)
*/
static 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"}`;
static user: UserInfo = {
username: "root",
uid: 0,
gid: 0, // <- PRIMARY GID
group: [0], // <- GROUPS ARRAY
home: 0,
};
static user2: UserInfo = {
username: "user",
uid: 1000,
gid: 1000,
group: [1000],
home: 1,
};
static nopass: UserInfo = {
username: "no pass",
uid: 1001,
gid: 1000,
group: [1000],
home: 2,
};
static group: GroupInfo = {
groupname: "root",
gid: 0,
members: [0], // <- UID
};
static group2: GroupInfo = {
groupname: "user",
gid: 1000,
members: [1000, 1001], // <- UID
};
public static get State(): ShellState {
const rawJson = `{"atime": 1786341244,"children": [{"atime": 1786341264,"children": [{"atime": 1786341330,"children": [],"content": null,"ctime": 1786341330,"group": 1000,"inode": 2,"mode": 493,"mtime": 1786341330,"name": "subdir1","owner": 1000,"parent": 1,"type": "directory"}],"content": null,"ctime": 1786341330,"group": 1000,"inode": 1,"mode": 493,"mtime": 1786341330,"name": "folder1","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341269,"children": [{"atime": 1786341344,"children": [],"content": null,"ctime": 1786341344,"group": 1000,"inode": 4,"mode": 493,"mtime": 1786341344,"name": "subdir2","owner": 1000,"parent": 3,"type": "directory"},{"atime": 1786341345,"children": [{"atime": 1786341356,"children": [],"content": [],"ctime": 1786341356,"group": 1000,"inode": 6,"mode": 420,"mtime": 1786341356,"name": "empty-foo","owner": 1000,"parent": 5,"type": "regular"}],"content": null,"ctime": 1786341356,"group": 1000,"inode": 5,"mode": 493,"mtime": 1786341356,"name": "subdir3","owner": 1000,"parent": 3,"type": "directory"}],"content": null,"ctime": 1786341345,"group": 1000,"inode": 3,"mode": 493,"mtime": 1786341345,"name": "folder2","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341312,"children": [],"content": [72,101,108,108,111,44,32,87,111,114,108,100,33,10],"ctime": 1786341312,"group": 1000,"inode": 7,"mode": 420,"mtime": 1786341312,"name": "some-file","owner": 1000,"parent": 0,"type": "regular"}],"content": null,"ctime": 1786341312,"group": 1000,"inode": 0,"mode": 493,"mtime": 1786341312,"name": "root","owner": 1000,"parent": 0,"type": "directory"}`;
const base = deserializeFileSystem(rawJson);
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
const fs = FileSystem.init(base, overlay, base.size - 1);
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
users.set(0, Fixture.user);
users.set(1000, Fixture.user2);
users.set(1001, Fixture.nopass);
groups.set(0, Fixture.group);
groups.set(1000, Fixture.group2);
return createInitialShellState(fs, users, groups, Fixture.user);
}
}
export class Fixture7Depth extends Fixture {
public static get State(): ShellState {
const fs = buildTestFS(depth7Tree);
const users: Map<number, UserInfo> = new Map();
const groups: Map<number, GroupInfo> = new Map();
users.set(0, Fixture7Depth.user);
users.set(1000, Fixture7Depth.user2);
groups.set(0, Fixture7Depth.group);
groups.set(1000, Fixture7Depth.group2);
return createInitialShellState(fs, users, groups, Fixture7Depth.user);
}
}
-58
View File
@@ -1,58 +0,0 @@
import type { FixtureNode } from "./filesystems_fixture";
export const depth7Tree: FixtureNode = {
inode: 0,
name: "root",
type: "Dir",
children: [
{
inode: 1,
name: "d1",
type: "Dir",
children: [
{
inode: 2,
name: "d2",
type: "Dir",
children: [
{
inode: 3,
name: "d3",
type: "Dir",
children: [
{
inode: 4,
name: "d4",
type: "Dir",
children: [
{
inode: 5,
name: "d5",
type: "Dir",
children: [
{
inode: 6,
name: "d6",
type: "Dir",
children: [
{
inode: 7,
name: "deep_file.txt",
type: "File",
content: "Deepest node at depth 7",
children: [],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
};