resolvePath function implemented and tested, all green.
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
import type { NodeNotFoundError, NotADirectoryError } from "./filesystem/errors";
|
||||
import type { FileSystem } from "./filesystem/filesystem";
|
||||
import { TreeNodeType, type DirectoryNode } from "./filesystem/treenode";
|
||||
|
||||
export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
|
||||
const isAbsolute = path.startsWith("/");
|
||||
|
||||
const normalizedPath: string = path.replace(/^\/+|\/+$/g, "");
|
||||
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0);
|
||||
|
||||
if (pathComponents.length === 0 && isAbsolute) return 0;
|
||||
if (pathComponents.length === 0) return cwd;
|
||||
|
||||
let currentNode = isAbsolute ? fs.getRoot() : (fs.getNode(cwd) as DirectoryNode);
|
||||
if (!currentNode) {
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: `CWD node under inode ${cwd} not found`,
|
||||
timestamp: Date.now(),
|
||||
inode: cwd,
|
||||
} satisfies NodeNotFoundError;
|
||||
}
|
||||
|
||||
for (const name of pathComponents) {
|
||||
if (name === ".") continue;
|
||||
|
||||
if (name === "..") {
|
||||
currentNode = fs.getNode(currentNode.parent) as DirectoryNode;
|
||||
continue;
|
||||
}
|
||||
|
||||
const inode = currentNode.children[name];
|
||||
|
||||
if (!inode)
|
||||
throw {
|
||||
type: "NodeNotFound",
|
||||
message: `Child node in ${currentNode.name} under name ${name} not found`,
|
||||
timestamp: Date.now(),
|
||||
inode: currentNode.inode,
|
||||
} satisfies NodeNotFoundError;
|
||||
if (fs.isFile(inode))
|
||||
throw {
|
||||
type: "NotADirectory",
|
||||
message: `Child node ${name} is not a directory`,
|
||||
timestamp: Date.now(),
|
||||
inode: inode,
|
||||
nodeType: TreeNodeType.File,
|
||||
} satisfies NotADirectoryError;
|
||||
|
||||
currentNode = fs.getNode(inode) as DirectoryNode;
|
||||
}
|
||||
|
||||
return currentNode.inode;
|
||||
}
|
||||
Reference in New Issue
Block a user