import { getCurrentSession } from "@core/session_manager"; import type { ShellState } from "@core/shell_state"; import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors"; import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode"; export function resolvePath(state: ShellState, path: string): number { const session = getCurrentSession(state); 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 session.cwd; let currentNode = isAbsolute ? state.filesystem.getRoot() : (state.filesystem.getNode(session.cwd) as DirectoryNode); if (!currentNode) { throw { type: "NodeNotFound", message: `CWD node under inode ${session.cwd} not found`, timestamp: Date.now(), inode: session.cwd, } satisfies NodeNotFoundError; } for (const name of pathComponents) { if (name === ".") continue; if (name === "..") { currentNode = state.filesystem.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 (state.filesystem.isFile(inode)) throw { type: "NotADirectory", message: `Child node ${name} is not a directory`, timestamp: Date.now(), inode: inode, nodeType: TreeNodeType.File, } satisfies NotADirectoryError; currentNode = state.filesystem.getNode(inode) as DirectoryNode; } return currentNode.inode; } export function resolveInode(state: ShellState, inode: number, abs: boolean = false): string { const node = state.filesystem.getNode(inode); const components: string[] = []; if (node === undefined) return ""; let currentInode = inode; while (currentInode !== 0) { const node = state.filesystem.getNode(currentInode) as TreeNode; if (!node) break; components.push(node.name); currentInode = node.parent; } if (components.length === 0) { components.push("/"); return components.join(""); } components.reverse().unshift(""); let result = components.join("/"); if (abs) return result; const home = resolveInode(state, getCurrentSession(state).user.home, true); const cwd = resolveInode(state, getCurrentSession(state).cwd, true); if (result.startsWith(home)) { result = `~${result.slice(home.length)}`; } else if (result.startsWith(cwd) && cwd !== "/") { result = `.${result.slice(cwd.length)}`; } return result; }