Files
termos/src/core/path_resolver.ts
T

74 lines
2.4 KiB
TypeScript

import type { NodeNotFoundError, NotADirectoryError } from "./filesystem/errors";
import type { FileSystem } from "./filesystem/filesystem";
import { TreeNodeType, type DirectoryNode, type TreeNode } 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;
}
export function resolveInode(fs: FileSystem, inode: number): string {
const node = fs.getNode(inode);
const components: string[] = [];
if (node === undefined) return "";
let currentInode = inode;
while (currentInode !== 0) {
const node = fs.getNode(currentInode) as TreeNode;
if (!node) break;
components.push(node.name);
currentInode = node.parent;
}
components.reverse();
components.unshift("");
return components.join("/");
}