- added an inode display to the `printTree` algorithm - removed a redundant type in *`signal.ts`* - improved `resolveInode` to now take `ShellState` instead of `FileSystem` and added an optional `abs` *`boolean`* argument to determine if the retuned path should be normalized or absolute - implemented a builtin `TreeNode` quicksort function - changed the `TreeNodeType` to a numeric enum - added a standalone `Posix` class that holds a const with character weights compliant with posix
62 lines
2.0 KiB
TypeScript
62 lines
2.0 KiB
TypeScript
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");
|
|
}
|