import type { FileSystem } from "@core/filesystem/filesystem"; import { TreeNodeType } from "@core/filesystem/treenode"; export function printTree(fs: FileSystem, root: number): string { const rootNode = fs.getNode(root); if (rootNode === undefined) return ""; const lines: string[] = []; lines.push(rootNode.name + ` (${rootNode.inode})`); type Frame = { inode: number; prefix: string; isLast: boolean; }; const stack: Frame[] = []; const getSorterChildren = (inode: number): number[] => { const node = fs.getNode(inode); if (!node || node.type !== TreeNodeType.Directory) return []; const entries = Object.entries(node.children); entries.sort(([a], [b]) => a.localeCompare(b)); return entries.map(([, childInode]) => childInode) as number[]; }; const rootChildren = getSorterChildren(root); for (let i = rootChildren.length - 1; i >= 0; i--) { const childInode: number = rootChildren[i] as number; const isLast = i === rootChildren.length - 1; stack.push({ inode: childInode, prefix: "", isLast }); } while (stack.length > 0) { const frame = stack.pop()!; const node = fs.getNode(frame.inode); if (!node) continue; const name = node.name; const connector = frame.isLast ? "└── " : "├── "; lines.push(frame.prefix + connector + name + ` (${node.inode})`); if (node.type === TreeNodeType.Directory) { const childPrefix = frame.prefix + (frame.isLast ? " " : "│ "); const children = getSorterChildren(frame.inode); for (let i = children.length - 1; i >= 0; i--) { const childInode = children[i] as number; const childIsLast = i === children.length - 1; stack.push({ inode: childInode, prefix: childPrefix, isLast: childIsLast }); } } } return lines.join("\n"); }