* Builds a hierarchical file tree from a flat list of file paths
(filePaths: string[])
| 771 | * Builds a hierarchical file tree from a flat list of file paths |
| 772 | */ |
| 773 | function buildFileTree(filePaths: string[]): FileTreeNode[] { |
| 774 | const tree: Record<string, FileTreeNode> = {} |
| 775 | |
| 776 | // Build the tree structure |
| 777 | for (const filePath of filePaths) { |
| 778 | const parts = filePath.split('/') |
| 779 | |
| 780 | for (let i = 0; i < parts.length; i++) { |
| 781 | const currentPath = parts.slice(0, i + 1).join('/') |
| 782 | const isFile = i === parts.length - 1 |
| 783 | |
| 784 | if (!tree[currentPath]) { |
| 785 | tree[currentPath] = { |
| 786 | name: parts[i], |
| 787 | type: isFile ? 'file' : 'directory', |
| 788 | filePath: currentPath, |
| 789 | children: isFile ? undefined : [], |
| 790 | } |
| 791 | } |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | // Organize into hierarchical structure |
| 796 | const rootNodes: FileTreeNode[] = [] |
| 797 | const processed = new Set<string>() |
| 798 | |
| 799 | for (const [path, node] of Object.entries(tree)) { |
| 800 | if (processed.has(path)) continue |
| 801 | |
| 802 | const parentPath = path.substring(0, path.lastIndexOf('/')) |
| 803 | if (parentPath && tree[parentPath]) { |
| 804 | // This node has a parent, add it to parent's children |
| 805 | const parent = tree[parentPath] |
| 806 | if ( |
| 807 | parent.children && |
| 808 | !parent.children.some((child) => child.filePath === path) |
| 809 | ) { |
| 810 | parent.children.push(node) |
| 811 | } |
| 812 | } else { |
| 813 | // This is a root node |
| 814 | rootNodes.push(node) |
| 815 | } |
| 816 | processed.add(path) |
| 817 | } |
| 818 | |
| 819 | // Sort function for nodes |
| 820 | function sortNodes(nodes: FileTreeNode[]): void { |
| 821 | nodes.sort((a, b) => { |
| 822 | // Directories first, then files |
| 823 | if (a.type !== b.type) { |
| 824 | return a.type === 'directory' ? -1 : 1 |
| 825 | } |
| 826 | return a.name.localeCompare(b.name) |
| 827 | }) |
| 828 | |
| 829 | // Recursively sort children |
| 830 | for (const node of nodes) { |
no test coverage detected